forked from hlandau/acmetool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredirector.go
252 lines (213 loc) · 7.01 KB
/
redirector.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Package redirector provides a basic HTTP server for redirecting HTTP
// requests to HTTPS requests and serving ACME HTTP challenge values.
package redirector
import (
"errors"
"fmt"
deos "github.com/hlandau/goutils/os"
"github.com/hlandau/xlog"
"gopkg.in/hlandau/svcutils.v1/chroot"
"gopkg.in/hlandau/svcutils.v1/passwd"
"gopkg.in/tylerb/graceful.v1"
"html"
"net"
"net/http"
"os"
"sync/atomic"
"time"
)
var log, Log = xlog.New("acme.redirector")
// Configuration for redirector.
type Config struct {
Bind string `default:":80" usage:"Bind address"`
ChallengePath string `default:"" usage:"Path containing HTTP challenge files"`
ChallengeGID string `default:"" usage:"GID to chgrp the challenge path to (optional)"`
ReadTimeout time.Duration `default:"" usage:"Maximum duration before timing out read of the request"`
WriteTimeout time.Duration `default:"" usage:"Maximum duration before timing out write of the response"`
StatusCode int `default:"308" usage:"HTTP redirect status code"`
}
// Simple HTTP to HTTPS redirector.
type Redirector struct {
cfg Config
httpServer graceful.Server
httpListener net.Listener
stopping uint32
}
// Instantiate an HTTP to HTTPS redirector.
func New(cfg Config) (*Redirector, error) {
r := &Redirector{
cfg: cfg,
httpServer: graceful.Server{
Timeout: 100 * time.Millisecond,
NoSignalHandling: true,
Server: &http.Server{
Addr: cfg.Bind,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
},
},
}
if r.cfg.StatusCode == 0 {
r.cfg.StatusCode = 308
}
// Try and make the challenge path if it doesn't exist.
err := os.MkdirAll(r.cfg.ChallengePath, 0755)
if err != nil {
return nil, err
}
if r.cfg.ChallengeGID != "" {
err := enforceGID(r.cfg.ChallengeGID, r.cfg.ChallengePath)
if err != nil {
return nil, err
}
}
l, err := net.Listen("tcp", r.httpServer.Server.Addr)
if err != nil {
return nil, err
}
r.httpListener = l
return r, nil
}
func enforceGID(gid, path string) error {
newGID, err := passwd.ParseGID(gid)
if err != nil {
return err
}
// So this is a surprisingly complicated dance if we want to be free of
// potentially hazardous race conditions. We have a path. We can't assume
// anything about its ownership, or mode, whether it's a symlink, etc.
//
// The big risk is that someone is able to create a symlink pointing to
// something they want to illicitly access. Note that since /var/run will
// commonly be used and because this directory is world-writeable, ala /tmp,
// this is a real risk.
//
// So we have to make sure we don't follow symlinks. Assume we are running
// as root (necessary, since we're chowning), and that nothing running as
// root is malicious.
//
// We open the directory as a file so we can modify it using that reference
// without worrying about the resolution of the path changing under us. But
// we need to make sure we don't follow symlinks. This requires special OS
// support, alas.
dir, err := deos.OpenNoSymlinks(path)
if err != nil {
return err
}
defer dir.Close()
fi, err := dir.Stat()
if err != nil {
return err
}
// Attributes of the directory can still change, but its type certainly
// can't. This guarantee is enough for our purposes.
if (fi.Mode() & os.ModeType) != os.ModeDir {
return fmt.Errorf("challenge path %#v is not a directory", path)
}
curUID, err := deos.GetFileUID(fi)
if err != nil {
return err
}
dir.Chmod((fi.Mode() | 0070) & ^os.ModeType) // Ignore errors.
dir.Chown(curUID, newGID) // Ignore errors.
return nil
}
func (r *Redirector) commonHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Server", "acmetool-redirector")
rw.Header().Set("Content-Security-Policy", "default-src 'none'")
h.ServeHTTP(rw, req)
})
}
// Start the redirector.
func (r *Redirector) Start() error {
serveMux := http.NewServeMux()
r.httpServer.Handler = r.commonHandler(serveMux)
challengePath, ok := chroot.Rel(r.cfg.ChallengePath)
if !ok {
return fmt.Errorf("challenge path is not addressible inside chroot: %s", r.cfg.ChallengePath)
}
serveMux.HandleFunc("/", r.handleRedirect)
serveMux.Handle("/.well-known/acme-challenge/",
http.StripPrefix("/.well-known/acme-challenge/", http.FileServer(nolsDir(challengePath))))
go func() {
err := r.httpServer.Serve(r.httpListener)
if atomic.LoadUint32(&r.stopping) == 0 {
log.Fatale(err, "serve")
}
}()
log.Debugf("redirector running")
return nil
}
// Stop the redirector.
func (r *Redirector) Stop() error {
atomic.StoreUint32(&r.stopping, 1)
r.httpServer.Stop(r.httpServer.Timeout)
<-r.httpServer.StopChan()
return nil
}
// Respond to a request with a redirect.
func (r *Redirector) handleRedirect(rw http.ResponseWriter, req *http.Request) {
// Redirect.
u := *req.URL
u.Scheme = "https"
if u.Host == "" {
u.Host = req.Host
}
if u.Host == "" {
rw.WriteHeader(400)
return
}
us := u.String()
rw.Header().Set("Location", us)
// If we are receiving any cookies, these must be insecure cookies, ergo
// cookies aren't being set securely properly. This is a security issue.
// Deleting cookies after the fact doesn't change the fact that they were
// sent in cleartext and are thus forever untrustworthy. But it increases
// the probability of somebody noticing something is up.
//
// ... However, the HTTP specification makes it impossible to delete a cookie
// unless we know its domain and path, which aren't transmitted in requests.
if req.Method == "GET" {
rw.Header().Set("Cache-Control", "public; max-age=31536000")
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
}
// This is a permanent redirect and the request method should be preserved.
// It's unfortunate if the client has transmitted information in cleartext
// via POST, etc., but there's nothing we can do about it at this stage.
rw.WriteHeader(r.cfg.StatusCode)
if req.Method == "GET" {
// Redirects issued in response to GET SHOULD have a body pointing to the
// new URL for clients which don't support redirects. (Whether the set of
// clients supporting acceptably modern versions of TLS and not supporting
// HTTP redirects is non-empty is another matter.)
ue := html.EscapeString(us)
rw.Write([]byte(fmt.Sprintf(redirBody, ue, ue)))
}
}
const redirBody = `<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head><title>Permanently Moved</title></head>
<body><h1>Permanently Moved</h1>
<p>This resource has <strong>moved permanently</strong> to
<a href="%s">%s</a>.</p>
</body></html>`
// Like http.Dir, but doesn't allow directory listings.
type nolsDir string
var errNoListing = errors.New("http: directory listing not allowed")
func (d nolsDir) Open(name string) (http.File, error) {
f, err := http.Dir(d).Open(name)
if err != nil {
return nil, err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return nil, err
}
if fi.IsDir() {
f.Close()
return nil, os.ErrNotExist
}
return f, nil
}