forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jailer.go
103 lines (83 loc) · 2.09 KB
/
jailer.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
package jailer
import (
"context"
"fmt"
"os"
"os/exec"
"os/user"
"path"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/pkg/errors"
"github.com/rancher/rancher/pkg/settings"
"github.com/sirupsen/logrus"
)
const BaseJailPath = "/opt/jail"
var lock = sync.Mutex{}
// CreateJail sets up the named directory for use with chroot
func CreateJail(name string) error {
lock.Lock()
defer lock.Unlock()
jailPath := path.Join(BaseJailPath, name)
// Check for the done file, if that exists the jail is ready to be used
_, err := os.Stat(path.Join(jailPath, "done"))
if err == nil {
return nil
}
// If the base dir exists without the done file rebuild the directory
_, err = os.Stat(jailPath)
if err == nil {
if err := os.RemoveAll(jailPath); err != nil {
return err
}
}
logrus.Debugf("Creating jail for %v", name)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "/usr/bin/jailer.sh", name)
out, err := cmd.CombinedOutput()
if err != nil {
return errors.WithMessage(err, fmt.Sprintf("error running the jail command: %v", string(out)))
}
logrus.Debugf("Output from create jail command %v", string(out))
return nil
}
// GetUserCred looks up the user and provides it in syscall.Credential
func GetUserCred() (*syscall.Credential, error) {
u, err := user.Current()
if err != nil {
uID := os.Getuid()
u, err = user.LookupId(strconv.Itoa(uID))
if err != nil {
return nil, err
}
}
i, err := strconv.ParseUint(u.Uid, 10, 32)
if err != nil {
return nil, err
}
uid := uint32(i)
i, err = strconv.ParseUint(u.Gid, 10, 32)
if err != nil {
return nil, err
}
gid := uint32(i)
return &syscall.Credential{Uid: uid, Gid: gid}, nil
}
func WhitelistEnvvars(envvars []string) []string {
wl := settings.WhitelistEnvironmentVars.Get()
envWhiteList := strings.Split(wl, ",")
if len(envWhiteList) == 0 {
return envvars
}
for _, wlVar := range envWhiteList {
wlVar = strings.TrimSpace(wlVar)
if val := os.Getenv(wlVar); val != "" {
envvars = append(envvars, wlVar+"="+val)
}
}
return envvars
}