-
Notifications
You must be signed in to change notification settings - Fork 25
/
environment_linux.go
375 lines (324 loc) · 8.12 KB
/
environment_linux.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
package container
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"sync"
"syscall"
"github.com/criyle/go-sandbox/pkg/forkexec"
"github.com/criyle/go-sandbox/pkg/mount"
"github.com/criyle/go-sandbox/pkg/unixsocket"
"github.com/criyle/go-sandbox/runner"
"golang.org/x/sys/unix"
)
// PathEnv defines path environment variable for the container init process
const PathEnv = "PATH=/usr/local/bin:/usr/bin:/bin"
// Builder builds instance of container environment
type Builder struct {
// Root is container root mount path, empty uses current work path
Root string
// Mounts defines container mount points, empty uses default mounts
Mounts []mount.Mount
// WorkDir defines container default work directory (default: /w)
WorkDir string
// Stderr defines whether to dup container stderr to stderr for debug
Stderr io.Writer
// ExecFile defines executable that called Init, otherwise defer current
// executable (/proc/self/exe)
ExecFile string
// CredGenerator defines a credential generator used to create new container
CredGenerator CredGenerator
// Clone flags defines unshare clone flag to create container
CloneFlags uintptr
// HostName set container hostname (default: go-sandbox)
HostName string
// DomainName set container domainname (default: go-sandbox)
DomainName string
// ContainerUID & ContainerGID set the container uid / gid mapping
ContainerUID int
ContainerGID int
}
// CredGenerator generates uid / gid credential used by container
// to isolate process and file system access
type CredGenerator interface {
Get() syscall.Credential
}
// Environment holds single progrem containerized environment
type Environment interface {
Ping() error
Open([]OpenCmd) ([]*os.File, error)
Delete(p string) error
Reset() error
Execve(context.Context, ExecveParam) <-chan runner.Result
Destroy() error
}
// container manages single pre-forked container environment
type container struct {
process *os.Process // underlying container init pid
socket *socket // host - container communication
mu sync.Mutex // lock to avoid race condition
done chan struct{}
err error
doneOnce sync.Once
recvCh chan recvReply
sendCh chan sendCmd
execveWaitCh chan execveWait
}
type recvReply struct {
Reply reply
Msg unixsocket.Msg
}
type sendCmd struct {
Cmd cmd
Msg unixsocket.Msg
}
// Build creates new environment with underlying container
func (b *Builder) Build() (Environment, error) {
c, err := b.startContainer()
if err != nil {
return nil, err
}
// avoid non cinit enabled executable running as container init process
if err = c.Ping(); err != nil {
c.Destroy()
return nil, fmt.Errorf("container: container init not responding to ping %v", err)
}
// container mount points
mounts := b.Mounts
if len(mounts) == 0 {
mounts = mount.NewDefaultBuilder().
WithTmpfs("w", ""). // work dir
WithTmpfs("tmp", ""). // tmp
FilterNotExist().Mounts
}
// container root directory on the host
root := b.Root
if root == "" {
if root, err = os.Getwd(); err != nil {
return nil, fmt.Errorf("container: failed to get work directory %v", err)
}
}
workDir := containerWD
if b.WorkDir != "" {
workDir = b.WorkDir
}
hostName := containerName
if b.HostName != "" {
hostName = b.HostName
}
domainName := containerName
if b.DomainName != "" {
domainName = b.DomainName
}
// set configuration and check if container creation successful
if err = c.conf(&containerConfig{
WorkDir: workDir,
HostName: hostName,
DomainName: domainName,
ContainerRoot: root,
Mounts: mounts,
Cred: b.CredGenerator != nil,
ContainerUID: b.ContainerUID,
ContainerGID: b.ContainerGID,
UnshareCgroup: b.CloneFlags&unix.CLONE_NEWCGROUP == unix.CLONE_NEWCGROUP,
}); err != nil {
c.Destroy()
return nil, err
}
return c, nil
}
func (b *Builder) startContainer() (*container, error) {
var (
err error
cred syscall.Credential
uidMap, gidMap []syscall.SysProcIDMap
)
// prepare host <-> container unix socket
ins, outs, err := newPassCredSocketPair()
if err != nil {
return nil, fmt.Errorf("container: failed to create socket: %v", err)
}
defer outs.Close()
outf, err := outs.File()
if err != nil {
ins.Close()
return nil, fmt.Errorf("container: failed to dup container socket fd %v", err)
}
defer outf.Close()
// prepare container running credential
if b.CredGenerator != nil {
cred = b.CredGenerator.Get()
uidMap, gidMap = b.getIDMapping(&cred)
} else {
uidMap = []syscall.SysProcIDMap{{HostID: os.Geteuid(), Size: 1}}
gidMap = []syscall.SysProcIDMap{{HostID: os.Getegid(), Size: 1}}
}
var cloneFlag uintptr
if b.CloneFlags == 0 {
cloneFlag = forkexec.UnshareFlags
} else {
cloneFlag = b.CloneFlags & forkexec.UnshareFlags
}
exe := "/proc/self/exe"
if b.ExecFile != "" {
exe = b.ExecFile
}
args := []string{exe, initArg}
r := exec.Cmd{
Path: exe,
Args: args,
Env: []string{PathEnv},
Stderr: b.Stderr,
ExtraFiles: []*os.File{outf},
SysProcAttr: &syscall.SysProcAttr{
Cloneflags: cloneFlag,
UidMappings: uidMap,
GidMappings: gidMap,
AmbientCaps: []uintptr{
unix.CAP_SYS_ADMIN,
},
Pdeathsig: syscall.SIGTERM,
},
}
if err = r.Start(); err != nil {
ins.Close()
return nil, fmt.Errorf("container: failed to start container %v", err)
}
c := &container{
process: r.Process,
socket: newSocket(ins),
recvCh: make(chan recvReply, 1),
sendCh: make(chan sendCmd, 1),
done: make(chan struct{}),
execveWaitCh: make(chan execveWait, 1),
}
go c.sendLoop()
go c.recvLoop()
go c.execveWaitLoop()
return c, nil
}
func (c *container) sendLoop() {
for {
select {
case <-c.done:
return
case cmd, ok := <-c.sendCh:
if !ok {
return
}
if err := c.socket.SendMsg(cmd.Cmd, cmd.Msg); err != nil {
c.socketError(err)
return
}
}
}
}
func (c *container) recvLoop() {
for {
var reply reply
msg, err := c.socket.RecvMsg(&reply)
if err != nil {
c.socketError(err)
return
}
c.recvCh <- recvReply{
Reply: reply,
Msg: msg,
}
}
}
func (c *container) socketError(err error) {
c.doneOnce.Do(func() {
c.err = err
close(c.done)
})
}
// Destroy kill the container process (with its children)
// if stderr enabled, collect the output as error
func (c *container) Destroy() error {
// close socket (abort any ongoing command)
c.socket.Close()
// wait commands terminates
c.mu.Lock()
defer c.mu.Unlock()
// kill process
c.process.Kill()
_, err := c.process.Wait()
return err
}
// newPassCredSocketPair creates socket pair and let the first socket to receive credential information
func newPassCredSocketPair() (*unixsocket.Socket, *unixsocket.Socket, error) {
ins, outs, err := unixsocket.NewSocketPair()
if err != nil {
return nil, nil, err
}
if err = ins.SetPassCred(1); err != nil {
ins.Close()
outs.Close()
return nil, nil, err
}
return ins, outs, nil
}
func (b *Builder) getIDMapping(cred *syscall.Credential) ([]syscall.SysProcIDMap, []syscall.SysProcIDMap) {
cUID := b.ContainerUID
if cUID == 0 {
cUID = containerUID
}
cGID := b.ContainerGID
if cGID == 0 {
cGID = containerGID
}
uidMap := []syscall.SysProcIDMap{
{
ContainerID: 0,
HostID: os.Geteuid(),
Size: 1,
},
{
ContainerID: cUID,
HostID: int(cred.Uid),
Size: 1,
},
}
gidMap := []syscall.SysProcIDMap{
{
ContainerID: 0,
HostID: os.Getegid(),
Size: 1,
},
{
ContainerID: cGID,
HostID: int(cred.Gid),
Size: 1,
},
}
return uidMap, gidMap
}
func (c *container) recvAckReply(name string) error {
reply, _, err := c.recvReply()
if err != nil {
return fmt.Errorf("%v: recvAck %v", name, err)
}
if reply.Error != nil {
return fmt.Errorf("%v: container error %v", name, reply.Error)
}
return nil
}
func (c *container) recvReply() (reply, unixsocket.Msg, error) {
select {
case <-c.done:
return reply{}, unixsocket.Msg{}, c.err
case recv := <-c.recvCh:
return recv.Reply, recv.Msg, nil
}
}
func (c *container) sendCmd(cmd cmd, msg unixsocket.Msg) error {
select {
case <-c.done:
return c.err
case c.sendCh <- sendCmd{Cmd: cmd, Msg: msg}:
return nil
}
}