-
Notifications
You must be signed in to change notification settings - Fork 38
/
fixuid.go
557 lines (483 loc) · 13.6 KB
/
fixuid.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
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"golang.org/x/exp/slices"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
config "github.com/go-ozzo/ozzo-config"
)
const ranFile = "/var/run/fixuid.ran"
var logger = log.New(os.Stderr, "", 0)
var quietFlag = flag.Bool("q", false, "quiet mode")
func main() {
runtime.GOMAXPROCS(1)
logger.SetPrefix("fixuid: ")
flag.Parse()
// development warning
logInfo("fixuid should only ever be used on development systems. DO NOT USE IN PRODUCTION")
argsWithoutProg := flag.Args()
// detect what user we are running as
runtimeUIDInt := os.Getuid()
runtimeUID := strconv.Itoa(runtimeUIDInt)
runtimeGIDInt := os.Getgid()
runtimeGID := strconv.Itoa(runtimeGIDInt)
// only run once on the system
if _, err := os.Stat(ranFile); !os.IsNotExist(err) {
logInfo("already ran on this system; will not attempt to change UID/GID")
exitOrExec(runtimeUID, runtimeUIDInt, runtimeGIDInt, -1, argsWithoutProg)
}
// check that script is running as root
if os.Geteuid() != 0 {
logger.Fatalln(`fixuid is not running as root, ensure that the following criteria are met:
- fixuid binary is owned by root: 'chown root:root /path/to/fixuid'
- fixuid binary has the setuid bit: 'chmod u+s /path/to/fixuid'
- NoNewPrivileges is disabled in container security profile
- volume containing fixuid binary does not have the 'nosuid' mount option`)
}
// load config from /etc/fixuid/config.[json|toml|yaml|yml]
rootConfig := config.New()
configError := errors.New("could not find config at /etc/fixuid/config.[json|toml|yaml|yml]")
var filePath string
for _, fileName := range [...]string{"config.json", "config.toml", "config.yaml", "config.yml"} {
filePath = path.Join("/etc/fixuid", fileName)
if _, err := os.Stat(filePath); !os.IsNotExist(err) {
configError = rootConfig.Load(filePath)
if configError != nil {
logInfo("error when loading configuration file " + filePath)
} else {
break
}
}
}
if configError != nil {
logger.Fatalln(configError)
}
// validate the container user from the config
containerUser := rootConfig.GetString("user")
if containerUser == "" {
logger.Fatalln("cannot find key 'user' in configuration file " + filePath)
}
containerUID, containerUIDError := findUID(containerUser)
if containerUIDError != nil {
logger.Fatalln(containerUIDError)
}
if containerUID == "" {
logger.Fatalln("user '" + containerUser + "' does not exist")
}
containerUIDInt, err := strconv.Atoi(containerUID)
if err != nil {
logger.Fatal(err)
}
containerUIDUint32 := uint32(containerUIDInt)
// validate the container group from the config
containerGroup := rootConfig.GetString("group")
if containerGroup == "" {
logger.Fatalln("cannot find key 'group' in configuration file " + filePath)
}
containerGID, containerGIDError := findGID(containerGroup)
if containerGIDError != nil {
logger.Fatalln(containerGIDError)
}
if containerGID == "" {
logger.Fatalln("group '" + containerGroup + "' does not exist")
}
containerGIDInt, err := strconv.Atoi(containerGID)
if err != nil {
logger.Fatal(err)
}
containerGIDUint32 := uint32(containerGIDInt)
// validate the paths from the config
var paths []string
err = rootConfig.Configure(&paths, "paths")
if err != nil {
switch err.(type) {
case *config.ConfigPathError:
paths = append(paths, "/")
default:
logger.Fatalln("key 'paths' is malformed; should be an array of strings in configuration file " + filePath)
}
}
// declare uid/gid vars and
var oldUID, newUID, oldGID, newGID string
needChown := false
// decide if need to change UIDs
existingUser, existingUserError := findUser(runtimeUID)
if existingUserError != nil {
logger.Fatalln(existingUserError)
}
if existingUser == "" {
logInfo("updating user '" + containerUser + "' to UID '" + runtimeUID + "'")
needChown = true
oldUID = containerUID
newUID = runtimeUID
} else {
oldUID = ""
newUID = ""
if existingUser == containerUser {
logInfo("runtime UID '" + runtimeUID + "' already matches container user '" + containerUser + "' UID")
} else {
logInfo("runtime UID '" + runtimeUID + "' matches existing user '" + existingUser + "'; not changing UID")
needChown = true
}
}
// decide if need to change GIDs
existingGroup, existingGroupError := findGroup(runtimeGID)
if existingGroupError != nil {
logger.Fatalln(existingGroupError)
}
if existingGroup == "" {
logInfo("updating group '" + containerGroup + "' to GID '" + runtimeGID + "'")
needChown = true
oldGID = containerGID
newGID = runtimeGID
} else {
oldGID = ""
newGID = ""
if existingGroup == containerGroup {
logInfo("runtime GID '" + runtimeGID + "' already matches container group '" + containerGroup + "' GID")
} else {
logInfo("runtime GID '" + runtimeGID + "' matches existing group '" + existingGroup + "'; not changing GID")
needChown = true
}
}
// update /etc/passwd if necessary
if oldUID != newUID || oldGID != newGID {
err := updateEtcPasswd(containerUser, oldUID, newUID, oldGID, newGID)
if err != nil {
logger.Fatalln(err)
}
}
// update /etc/group if necessary
if oldGID != newGID {
err := updateEtcGroup(containerGroup, oldGID, newGID)
if err != nil {
logger.Fatalln(err)
}
}
// search entire filesystem and chown containerUID:containerGID to runtimeUID:runtimeGID
if needChown {
// process /proc/mounts
mounts, err := parseProcMounts()
if err != nil {
logger.Fatalln(err)
}
// store the current mountpoint
var mountpoint string
// this function is called for every file visited
visit := func(filePath string, fileInfo os.FileInfo, err error) error {
// an error to lstat or filepath.readDirNames
// see https://github.com/boxboat/fixuid/issues/4
if err != nil {
logInfo("error when visiting " + filePath)
logInfo(err)
return nil
}
// stat file to determine UID and GID
sys, ok := fileInfo.Sys().(*syscall.Stat_t)
if !ok {
logInfo("cannot stat " + filePath)
return filepath.SkipDir
}
// prevent recursing into mounts
if findMountpoint(filePath, mounts) != mountpoint {
if sys.Uid == containerUIDUint32 && sys.Gid == containerGIDUint32 {
logInfo("skipping mounted path " + filePath)
}
if fileInfo.IsDir() {
return filepath.SkipDir
}
return nil
}
// only chown if file is containerUID:containerGID
if sys.Uid == containerUIDUint32 && sys.Gid == containerGIDUint32 {
logInfo("chown " + filePath)
err := syscall.Lchown(filePath, runtimeUIDInt, runtimeGIDInt)
if err != nil {
logInfo("error changing owner of " + filePath)
logInfo(err)
}
return nil
}
return nil
}
for _, path := range paths {
// stat the path to ensure it exists
_, err := os.Stat(path)
if err != nil {
logInfo("error accessing path: " + path)
logInfo(err)
continue
}
mountpoint = findMountpoint(path, mounts)
logInfo("recursively searching path " + path)
filepath.Walk(path, visit)
}
}
// mark the script as ran
if err := os.WriteFile(ranFile, []byte{}, 0644); err != nil {
logger.Fatalln(err)
}
// if the existing HOME directory is "/", change it to the user's home directory
existingHomeDir := os.Getenv("HOME")
if existingHomeDir == "/" {
homeDir, homeDirErr := findHomeDir(runtimeUID)
if homeDirErr == nil && homeDir != "" && homeDir != "/" {
if len(argsWithoutProg) > 0 {
os.Setenv("HOME", homeDir)
} else {
fmt.Println(`export HOME="` + strings.Replace(homeDir, `"`, `\"`, -1) + `"`)
}
}
}
oldGIDInt := -1
if oldGID != "" && oldGID != newGID {
if gid, err := strconv.Atoi(oldGID); err != nil {
oldGIDInt = gid
}
}
// all done
exitOrExec(runtimeUID, runtimeUIDInt, runtimeGIDInt, oldGIDInt, argsWithoutProg)
}
func logInfo(v ...interface{}) {
if !*quietFlag {
logger.Println(v...)
}
}
// oldGIDInt should be -1 if the GID was not changed
func exitOrExec(runtimeUID string, runtimeUIDInt, runtimeGIDInt, oldGIDInt int, argsWithoutProg []string) {
if len(argsWithoutProg) > 0 {
// exec mode - de-escalate privileges and exec new process
binary, err := exec.LookPath(argsWithoutProg[0])
if err != nil {
logger.Fatalln(err)
}
// get real user
user, err := findUser(runtimeUID)
if err != nil {
logger.Fatalln(err)
}
// set groups
if user != "" {
// get all existing group IDs
existingGIDs, err := syscall.Getgroups()
if err != nil {
logger.Fatalln(err)
}
// get primary GID from /etc/passwd
primaryGID, err := findPrimaryGID(runtimeUID)
if err != nil {
logger.Fatalln(err)
}
// get supplementary GIDs from /etc/group
supplementaryGIDs, err := findUserSupplementaryGIDs(user)
if err != nil {
logger.Fatalln(err)
}
// add all GIDs to a map
allGIDs := append(existingGIDs, primaryGID)
allGIDs = append(allGIDs, supplementaryGIDs...)
gidMap := make(map[int]struct{})
for _, gid := range allGIDs {
gidMap[gid] = struct{}{}
}
// remove the old GID if it was changed
if oldGIDInt >= 0 {
delete(gidMap, oldGIDInt)
}
groups := make([]int, 0, len(gidMap))
for gid := range gidMap {
groups = append(groups, gid)
}
// set groups
err = syscall.Setgroups(groups)
if err != nil {
logger.Fatalln(err)
}
}
// de-escalate the group back to the original
if err := syscall.Setegid(runtimeGIDInt); err != nil {
logger.Fatalln(err)
}
// de-escalate the user back to the original
if err := syscall.Seteuid(runtimeUIDInt); err != nil {
logger.Fatalln(err)
}
// exec new process
env := os.Environ()
if err := syscall.Exec(binary, argsWithoutProg, env); err != nil {
logger.Fatalln(err)
}
}
// nothing to exec; exit the program
os.Exit(0)
}
func searchColonDelimitedFile(filePath string, search string, searchOffset int, returnOffset int) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
cols := strings.Split(scanner.Text(), ":")
if len(cols) < (searchOffset+1) || len(cols) < (returnOffset+1) {
continue
}
if cols[searchOffset] == search {
return cols[returnOffset], nil
}
}
return "", nil
}
func findUID(user string) (string, error) {
return searchColonDelimitedFile("/etc/passwd", user, 0, 2)
}
func findUser(uid string) (string, error) {
return searchColonDelimitedFile("/etc/passwd", uid, 2, 0)
}
// returns -1 if not found
func findPrimaryGID(uid string) (int, error) {
gid, err := searchColonDelimitedFile("/etc/passwd", uid, 2, 3)
if err != nil {
return -1, err
}
if gid == "" {
return -1, nil
}
return strconv.Atoi(gid)
}
func findHomeDir(uid string) (string, error) {
return searchColonDelimitedFile("/etc/passwd", uid, 2, 5)
}
func findGID(group string) (string, error) {
return searchColonDelimitedFile("/etc/group", group, 0, 2)
}
func findGroup(gid string) (string, error) {
return searchColonDelimitedFile("/etc/group", gid, 2, 0)
}
func findUserSupplementaryGIDs(user string) ([]int, error) {
// group:pass:gid:users
file, err := os.Open("/etc/group")
if err != nil {
return nil, err
}
var gids []int
scanner := bufio.NewScanner(file)
for scanner.Scan() {
cols := strings.Split(scanner.Text(), ":")
if len(cols) < 4 {
continue
}
users := strings.Split(cols[3], ",")
if !slices.Contains(users, user) {
continue
}
gid, err := strconv.Atoi(cols[2])
if err != nil {
continue
}
gids = append(gids, gid)
}
file.Close()
if err := scanner.Err(); err != nil {
return nil, err
}
return gids, nil
}
func updateEtcPasswd(user string, oldUID string, newUID string, oldGID string, newGID string) error {
// user:pass:uid:gid:comment:home dir:shell
file, err := os.Open("/etc/passwd")
if err != nil {
return err
}
newLines := ""
scanner := bufio.NewScanner(file)
for scanner.Scan() {
cols := strings.Split(scanner.Text(), ":")
if len(cols) < 4 {
continue
}
if oldUID != "" && newUID != "" && cols[0] == user && cols[2] == oldUID {
cols[2] = newUID
}
if oldGID != "" && newGID != "" && cols[3] == oldGID {
cols[3] = newGID
}
newLines += strings.Join(cols, ":") + "\n"
}
file.Close()
if err := scanner.Err(); err != nil {
return err
}
if err := os.WriteFile("/etc/passwd", []byte(newLines), 0644); err != nil {
return err
}
return nil
}
func updateEtcGroup(group string, oldGID string, newGID string) error {
// group:pass:gid:users
file, err := os.Open("/etc/group")
if err != nil {
return err
}
newLines := ""
scanner := bufio.NewScanner(file)
for scanner.Scan() {
cols := strings.Split(scanner.Text(), ":")
if len(cols) < 3 {
continue
}
if oldGID != "" && newGID != "" && cols[0] == group && cols[2] == oldGID {
cols[2] = newGID
}
newLines += strings.Join(cols, ":") + "\n"
}
file.Close()
if err := scanner.Err(); err != nil {
return err
}
if err := os.WriteFile("/etc/group", []byte(newLines), 0644); err != nil {
return err
}
return nil
}
func parseProcMounts() (map[string]bool, error) {
// device mountpoint type options dump fsck
// spaces appear as \040
file, err := os.Open("/proc/mounts")
if err != nil {
return nil, err
}
mounts := make(map[string]bool)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
cols := strings.Fields(scanner.Text())
if len(cols) >= 2 {
mounts[filepath.Clean(strings.Replace(cols[1], "\\040", " ", -1))] = true
}
}
file.Close()
return mounts, nil
}
func findMountpoint(path string, mounts map[string]bool) string {
path = filepath.Clean(path)
var lastPath string
for path != lastPath {
if _, ok := mounts[path]; ok {
return path
}
lastPath = path
path = filepath.Dir(path)
}
return "/"
}