This repository has been archived by the owner on Apr 21, 2021. It is now read-only.
forked from genuinetools/contained.af
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker.go
339 lines (295 loc) · 8.28 KB
/
docker.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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/term"
"github.com/docker/go-connections/nat"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
)
// dockerProfile is an abstraction to support different configuration sets for running
// containers. More information is available here about the supported profiles and their meanings:
// https://github.com/kinvolk/container-escape-bounty/blob/master/Documentation/profiles.md
type dockerProfile string
var (
defaultDockerProfile dockerProfile = "default-docker"
weakDockerProfile dockerProfile = "weak-docker"
)
var dockerProfiles = map[dockerProfile]struct{}{
defaultDockerProfile: struct{}{},
weakDockerProfile: struct{}{},
}
type containerInfo struct {
dockerImage string
port string
userns bool
containerid string
selinux bool
apparmor bool
dockerProfile dockerProfile
}
func validatePort(portStr string) (nat.Port, error) {
if portStr == "" {
return "", nil
}
port, err := nat.NewPort("tcp", portStr)
if err != nil {
return "", err
}
portInt := port.Int()
if portInt < 36100 || portInt > 36110 {
// this is the allowed range of open ports defined in terraform config
// https://github.com/kinvolk/container-escape-bounty/pull/19
return "", fmt.Errorf("port not in range [36100, 36110], given: %d", portInt)
}
return port, nil
}
type containerOptions func(cfg *container.Config)
func withPort(port nat.Port) containerOptions {
return func(ctrCfg *container.Config) {
if port == "" {
return
}
ctrCfg.ExposedPorts = nat.PortSet{
port: struct{}{},
}
}
}
func withDockerImage(image string) containerOptions {
return func(cfg *container.Config) {
cfg.Image = image
if image == "" {
// Use default docker image when user does not provide any
cfg.Image = defaultDockerImage
}
}
}
func withDockerUser(profile dockerProfile) containerOptions {
return func(cfg *container.Config) {
// By default, use the defaultDockerProfile.
user := "nobody"
if profile == weakDockerProfile {
user = ""
}
cfg.User = user
}
}
type hostOptions func(cfg *container.HostConfig) error
func withExposedPort(port nat.Port) hostOptions {
return func(cfg *container.HostConfig) error {
if port == "" {
return nil
}
cfg.PortBindings = map[nat.Port][]nat.PortBinding{
port: []nat.PortBinding{
{
HostIP: "0.0.0.0",
HostPort: string(port),
},
},
}
return nil
}
}
func withSecurityOptions(profile dockerProfile, selinux bool, apparmor bool) hostOptions {
return func(cfg *container.HostConfig) error {
seccompConfig, ok := seccompConfigs[profile]
if !ok {
return fmt.Errorf("seccomp config not found for profile: %q", profile)
}
b := bytes.NewBuffer(nil)
if err := json.Compact(b, []byte(seccompConfig)); err != nil {
// this should be caught while development itself and not during runtime
panic(fmt.Sprintf("compacting json for seccomp profile failed: %v", err))
}
cfg.SecurityOpt = []string{
"no-new-privileges",
fmt.Sprintf("seccomp=%s", b.Bytes()),
}
// SELinux is enabled by default if user asks to disable it only then we
// do it
if !selinux {
cfg.SecurityOpt = append(cfg.SecurityOpt, "label=disable")
}
// Apparmor is enabled by default if user asks to disable it only then we
// do it
if !apparmor {
cfg.SecurityOpt = append(cfg.SecurityOpt, "apparmor=unconfined")
}
return nil
}
}
func withHostVolumes(profile dockerProfile) hostOptions {
return func(cfg *container.HostConfig) error {
if profile == weakDockerProfile {
cfg.Mounts = []mount.Mount{
{
Type: mount.TypeBind,
Source: "/var/tmp/shared",
Target: "/var/tmp/shared",
ReadOnly: false,
Consistency: mount.ConsistencyDefault,
},
}
}
return nil
}
}
func withCapabilities(profile dockerProfile) hostOptions {
return func(cfg *container.HostConfig) error {
if profile == weakDockerProfile {
cfg.CapAdd = []string{"NET_ADMIN", "SYS_PTRACE", "SYS_CHROOT"}
}
return nil
}
}
func NewContainerConfig(opts ...containerOptions) *container.Config {
cfg := &container.Config{
Cmd: []string{"sh"},
Tty: true,
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
OpenStdin: true,
StdinOnce: true,
}
for _, opt := range opts {
opt(cfg)
}
return cfg
}
func NewContainerHostConfig(opts ...hostOptions) (*container.HostConfig, error) {
cfg := &container.HostConfig{
NetworkMode: "default",
LogConfig: container.LogConfig{
Type: "none",
},
Resources: container.Resources{
PidsLimit: 5,
},
}
for _, opt := range opts {
if err := opt(cfg); err != nil {
return nil, err
}
}
return cfg, nil
}
// startContainer starts a docker container and returns the container ID
// as well as a websocket connection to the attach endpoint.
func (h *handler) startContainer(ctrInfo *containerInfo) (*websocket.Conn, error) {
port, err := validatePort(ctrInfo.port)
if err != nil {
return nil, err
}
ctrCfg := NewContainerConfig(
withPort(port),
withDockerImage(ctrInfo.dockerImage),
withDockerUser(ctrInfo.dockerProfile),
)
ctrHostCfg, err := NewContainerHostConfig(
withExposedPort(port),
withSecurityOptions(ctrInfo.dockerProfile, ctrInfo.selinux, ctrInfo.apparmor),
withHostVolumes(ctrInfo.dockerProfile),
withCapabilities(ctrInfo.dockerProfile),
)
if err != nil {
return nil, fmt.Errorf("creating container host config: %v", err)
}
// using ctrCfg.Image because it is updated to be default/user given
ctrInfo.dockerImage = ctrCfg.Image
// pull container image if we don't already have it
if err := h.pullImage(ctrInfo); err != nil {
return nil, fmt.Errorf("pulling %s failed: %v", ctrCfg.Image, err)
}
// create the container
r, err := h.client(ctrInfo.userns).ContainerCreate(context.Background(), ctrCfg,
ctrHostCfg, nil, "")
if err != nil {
return nil, err
}
ctrInfo.containerid = r.ID
// connect to the attach websocket endpoint
header := http.Header(make(map[string][]string))
header.Add("Origin", h.url(ctrInfo.userns).String())
v := url.Values{
"stdin": []string{"1"},
"stdout": []string{"1"},
"stderr": []string{"1"},
"stream": []string{"1"},
}
proto := "ws"
if h.tls_ws {
proto = "wss"
}
wsURL := fmt.Sprintf("%s://%s/%s/containers/%s/attach/ws?%s",
proto, h.url(ctrInfo.userns).Host, dockerAPIVersion, r.ID, v.Encode())
var dialer = &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: h.tlsConfig,
}
conn, _, err := dialer.Dial(wsURL, header)
if err != nil {
return nil, fmt.Errorf("dialing %s with header %#v failed: %v",
wsURL, header, err)
}
// start the container
if err := h.client(ctrInfo.userns).ContainerStart(context.Background(),
r.ID, types.ContainerStartOptions{}); err != nil {
return conn, err
}
return conn, nil
}
// removeContainer removes with force a container by it's container ID.
func (h *handler) removeContainer(ctrInfo *containerInfo) error {
if err := h.client(ctrInfo.userns).ContainerRemove(
context.Background(),
ctrInfo.containerid,
types.ContainerRemoveOptions{
RemoveVolumes: true,
Force: true,
}); err != nil {
return err
}
logrus.Debugf("removed container: %s", ctrInfo.containerid)
return nil
}
// pullImage requests a docker image if it doesn't exist already.
func (h *handler) pullImage(ctrInfo *containerInfo) error {
exists, err := h.imageExists(ctrInfo)
if err != nil {
return err
}
if exists {
return nil
}
resp, err := h.client(ctrInfo.userns).ImagePull(context.Background(),
ctrInfo.dockerImage, types.ImagePullOptions{})
if err != nil {
return err
}
fd, isTerm := term.GetFdInfo(os.Stdout)
return jsonmessage.DisplayJSONMessagesStream(resp, os.Stdout, fd, isTerm, nil)
}
// imageExists checks if a docker image exists.
func (h *handler) imageExists(ctrInfo *containerInfo) (bool, error) {
_, _, err := h.client(ctrInfo.userns).ImageInspectWithRaw(
context.Background(), ctrInfo.dockerImage)
if err == nil {
return true, nil
}
if client.IsErrNotFound(err) {
return false, nil
}
return false, err
}