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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
|
package main
import (
"crypto/rand"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/sirupsen/logrus"
"gitlab.com/gitlab-org/labkit/log"
"gitlab.com/gitlab-org/gitlab-pages/internal/config"
"gitlab.com/gitlab-org/gitlab-pages/internal/jail"
)
const (
daemonRunProgram = "gitlab-pages-unprivileged"
)
func daemonMain() {
if os.Args[0] != daemonRunProgram {
return
}
// Validate that a working directory is valid
// https://man7.org/linux/man-pages/man2/getcwd.2.html
wd, err := os.Getwd()
if err != nil {
fatal(err, "could not get current working directory")
} else if strings.HasPrefix(wd, "(unreachable)") {
fatal(os.ErrPermission, "could not get current working directory")
}
logrus.WithFields(logrus.Fields{
"uid": syscall.Getuid(),
"gid": syscall.Getgid(),
"wd": wd,
}).Info("starting the daemon as unprivileged user")
// read the configuration from the pipe "ExtraFiles"
var config config.Config
if err := json.NewDecoder(os.NewFile(3, "options")).Decode(&config); err != nil {
fatal(err, "could not decode app config")
}
runApp(&config)
os.Exit(0)
}
func daemonReexec(uid, gid uint, args ...string) (cmd *exec.Cmd, err error) {
path, err := os.Executable()
if err != nil {
return
}
cmd = &exec.Cmd{
Path: path,
Args: args,
Env: os.Environ(),
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
SysProcAttr: &syscall.SysProcAttr{
Credential: &syscall.Credential{
Uid: uint32(uid),
Gid: uint32(gid),
},
Setsid: true,
},
}
return
}
func daemonUpdateFd(cmd *exec.Cmd, fd uintptr) (childFd uintptr) {
file := os.NewFile(fd, "[socket]")
// we add 3 since, we have a 3 predefined FDs
childFd = uintptr(3 + len(cmd.ExtraFiles))
cmd.ExtraFiles = append(cmd.ExtraFiles, file)
return
}
func daemonUpdateFds(cmd *exec.Cmd, fds []uintptr) {
for idx, fd := range fds {
fds[idx] = daemonUpdateFd(cmd, fd)
}
}
func killProcess(cmd *exec.Cmd) {
if cmd.Process != nil {
cmd.Process.Kill()
}
cmd.Wait()
for _, file := range cmd.ExtraFiles {
file.Close()
}
}
func passSignals(cmd *exec.Cmd) {
if cmd.Process == nil {
return
}
s := make(chan os.Signal)
signal.Notify(s, syscall.SIGTERM, os.Interrupt, os.Kill)
go func() {
for cmd.Process != nil {
cmd.Process.Signal(<-s)
}
}()
}
func chrootDaemon(cmd *exec.Cmd) (*jail.Jail, error) {
wd, err := os.Getwd()
if err != nil {
return nil, err
}
chroot := jail.Into(wd)
// Generate a probabilistically-unique suffix for the copy of the pages
// binary being placed into the chroot
suffix := make([]byte, 16)
if _, err := rand.Read(suffix); err != nil {
return nil, err
}
tempExecutablePath := fmt.Sprintf("/.daemon.%x", suffix)
if err := chroot.CopyTo(tempExecutablePath, cmd.Path); err != nil {
return nil, err
}
// Update command to use chroot
cmd.SysProcAttr.Chroot = chroot.Path()
cmd.Path = tempExecutablePath
cmd.Dir = "/"
return chroot, nil
}
func jailCopyCertDir(cage *jail.Jail, sslCertDir, jailCertsDir string) error {
logrus.WithFields(logrus.Fields{
"ssl-cert-dir": sslCertDir,
}).Debug("Copying certs from SSL_CERT_DIR")
entries, err := ioutil.ReadDir(sslCertDir)
if err != nil {
return fmt.Errorf("failed to read SSL_CERT_DIR: %+v", err)
}
for _, fi := range entries {
// Copy only regular files and symlinks
mode := fi.Mode()
if !(mode.IsRegular() || mode&os.ModeSymlink != 0) {
continue
}
err = cage.CopyTo(jailCertsDir+"/"+fi.Name(), sslCertDir+"/"+fi.Name())
if err != nil {
logrus.WithError(err).Errorf("failed to copy cert: %q", fi.Name())
// Go on and try to copy other files. We don't want the whole
// startup process to fail due to a single failure here.
}
}
return nil
}
func jailDaemonCerts(cmd *exec.Cmd, cage *jail.Jail) error {
sslCertFile := os.Getenv("SSL_CERT_FILE")
sslCertDir := os.Getenv("SSL_CERT_DIR")
if sslCertFile == "" && sslCertDir == "" {
logrus.Warn("Neither SSL_CERT_FILE nor SSL_CERT_DIR environment variable is set. HTTPS requests will fail.")
return nil
}
// This assumes cage.MkDir("/etc") has already been called
cage.MkDir("/etc/ssl", 0755)
// Copy SSL_CERT_FILE inside the jail
if sslCertFile != "" {
jailCertsFile := "/etc/ssl/ca-bundle.pem"
err := cage.CopyTo(jailCertsFile, sslCertFile)
if err != nil {
return fmt.Errorf("failed to copy SSL_CERT_FILE: %+v", err)
}
cmd.Env = append(cmd.Env, "SSL_CERT_FILE="+jailCertsFile)
}
// Copy all files and symlinks from SSL_CERT_DIR into the jail
if sslCertDir != "" {
jailCertsDir := "/etc/ssl/certs"
cage.MkDir(jailCertsDir, 0755)
err := jailCopyCertDir(cage, sslCertDir, jailCertsDir)
if err != nil {
return err
}
cmd.Env = append(cmd.Env, "SSL_CERT_DIR="+jailCertsDir)
}
return nil
}
func jailCreate(cmd *exec.Cmd) (*jail.Jail, error) {
cage := jail.CreateTimestamped("gitlab-pages", 0755)
// Add /dev/urandom and /dev/random inside the jail. This is required to
// support Linux versions < 3.17, which do not have the getrandom() syscall
cage.MkDir("/dev", 0755)
if err := cage.CharDev("/dev/urandom"); err != nil {
return nil, err
}
if err := cage.CharDev("/dev/random"); err != nil {
return nil, err
}
// Add gitlab-pages inside the jail
err := cage.CopyTo("/gitlab-pages", cmd.Path)
if err != nil {
return nil, err
}
// Add /etc/resolv.conf, /etc/hosts and /etc/nsswitch.conf inside the jail
cage.MkDir("/etc", 0755)
err = cage.Copy("/etc/resolv.conf")
if err != nil {
return nil, err
}
err = cage.Copy("/etc/hosts")
if err != nil {
return nil, err
}
// When cgo is disabled, Go does not read `/etc/hosts` unless `/etc/nsswitch.conf` exists
// https://github.com/golang/go/issues/22846
err = cage.Copy("/etc/nsswitch.conf")
if err != nil {
logrus.WithError(err).Warn("/etc/nsswitch.conf couldn't be copied to the jail, /etc/hosts might not be applicable")
}
// Add certificates inside the jail
err = jailDaemonCerts(cmd, cage)
if err != nil {
return nil, err
}
return cage, nil
}
func jailDaemon(pagesRoot string, cmd *exec.Cmd) (*jail.Jail, error) {
cage, err := jailCreate(cmd)
if err != nil {
return nil, err
}
// Bind mount shared folder
cage.MkDirAll(pagesRoot, 0755)
cage.Bind(pagesRoot, pagesRoot)
// Update command to use chroot
cmd.SysProcAttr.Chroot = cage.Path()
cmd.Path = "/gitlab-pages"
cmd.Dir = pagesRoot
return cage, nil
}
func daemonize(config *config.Config) error {
uid := config.Daemon.UID
gid := config.Daemon.GID
inPlace := config.Daemon.InplaceChroot
enableJail := config.Daemon.EnableJail
pagesRoot := config.General.RootDir
// Ensure pagesRoot is an absolute path. This will produce a different path
// if any component of pagesRoot is a symlink (not likely). For example,
// -pages-root=/some-path where ln -s /other-path /some-path
// pagesPath will become: /other-path and we will fail to serve files from /some-path.
// GitLab Rails also resolves the absolute path for `pages_path`
// https://gitlab.com/gitlab-org/gitlab/blob/981ad651d8bd3690e28583eec2363a79f775af89/config/initializers/1_settings.rb#L296
pagesRoot, err := filepath.Abs(pagesRoot)
if err != nil {
return err
}
logrus.WithFields(logrus.Fields{
"uid": uid,
"gid": gid,
"in-place": inPlace,
"enable-jail": enableJail,
"pages-root": pagesRoot,
}).Info("running the daemon as unprivileged user")
cmd, err := daemonReexec(uid, gid, daemonRunProgram)
if err != nil {
return err
}
defer killProcess(cmd)
if enableJail {
wrapper, err := createChroot(cmd, pagesRoot, inPlace)
if err != nil {
log.WithError(err).Error("create chroot failed")
return err
}
defer wrapper.Dispose()
// Unshare mount namespace
// 1. If this fails, in a worst case changes to mounts will propagate to other processes
// 2. Ensures that jail mount is not propagated to the parent mount namespace
// to avoid populating `tmp` directory with old mounts
_ = wrapper.Unshare()
if err := wrapper.Build(); err != nil {
log.WithError(err).Error("chroot build failed")
return err
}
}
// Create a pipe to pass the configuration
configReader, configWriter, err := os.Pipe()
if err != nil {
return err
}
defer configWriter.Close()
cmd.ExtraFiles = append(cmd.ExtraFiles, configReader)
updateFds(config, cmd)
// Start the process
if err := cmd.Start(); err != nil {
logrus.WithError(err).Error("start failed")
return err
}
// Write the configuration
if err := json.NewEncoder(configWriter).Encode(config); err != nil {
return err
}
configWriter.Close()
// Pass through signals
passSignals(cmd)
// Wait for process to exit
return cmd.Wait()
}
func createChroot(cmd *exec.Cmd, pagesRoot string, inPlace bool) (*jail.Jail, error) {
// Run daemon in chroot environment
var wrapper *jail.Jail
var err error
if inPlace {
wrapper, err = chrootDaemon(cmd)
} else {
wrapper, err = jailDaemon(pagesRoot, cmd)
}
return wrapper, err
}
func updateFds(config *config.Config, cmd *exec.Cmd) {
for _, fds := range [][]uintptr{
config.Listeners.HTTP,
config.Listeners.HTTPS,
config.Listeners.Proxy,
config.Listeners.HTTPSProxyv2,
} {
daemonUpdateFds(cmd, fds)
}
for _, fdPtr := range []*uintptr{
&config.ListenMetrics,
} {
if *fdPtr != 0 {
*fdPtr = daemonUpdateFd(cmd, *fdPtr)
}
}
}
|