-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathmain.go
More file actions
389 lines (356 loc) · 9.18 KB
/
Copy pathmain.go
File metadata and controls
389 lines (356 loc) · 9.18 KB
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 (
"bytes"
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
)
const agentUID = 1000
const agentGID = 1000
const challengeBin = "/challenge/bin"
const challengeRunDir = "/run/challenge"
const challengeRunBin = "/run/challenge/bin"
const workspaceRunDir = "/run/workspace"
const workspaceProfile = "/run/workspace/profile"
const workspaceUserRunDir = "/run/workspace/user"
const workspaceServicesDir = "/run/workspace/user/services"
type controlMessage struct {
Type string `json:"type"`
Message string `json:"message,omitempty"`
}
type workspaceConfig struct {
flag string
user string
home string
}
func main() {
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
config, err := loadWorkspaceConfig()
if err != nil {
logger.Error("invalid workspace configuration", "err", err)
os.Exit(1)
}
if err := prepareWorkspace(config); err != nil {
logger.Error("failed to prepare workspace", "err", err)
os.Exit(1)
}
controlRead, controlWrite, err := os.Pipe()
if err != nil {
logger.Error("failed to create control pipe", "err", err)
os.Exit(1)
}
agent, err := startAgent(controlRead, config)
controlRead.Close()
if err != nil {
logger.Error("failed to start workspace agent", "err", err)
os.Exit(1)
}
setupErr := runChallengeInit()
if setupErr != nil {
logger.Error("workspace setup failed", "err", setupErr)
sendControl(controlWrite, controlMessage{Type: "failed", Message: setupErr.Error()})
} else {
sendControl(controlWrite, controlMessage{Type: "ready"})
}
controlWrite.Close()
execSupervisor(agent.Process.Pid)
}
func startAgent(controlRead *os.File, config workspaceConfig) (*exec.Cmd, error) {
executable, err := os.Executable()
if err != nil {
return nil, err
}
agentPath := filepath.Join(filepath.Dir(executable), "workspace-agent")
command := exec.Command(agentPath)
command.Stdout = os.Stdout
command.Stderr = os.Stderr
command.ExtraFiles = []*os.File{controlRead}
command.Env = append(os.Environ(),
"HOME="+config.home,
"LOGNAME="+config.user,
"SHELL=/bin/bash",
"USER="+config.user,
)
command.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Credential: &syscall.Credential{
Uid: agentUID,
Gid: agentGID,
},
}
return command, command.Start()
}
func execSupervisor(agentPID int) {
executable, err := os.Executable()
if err != nil {
panic(err)
}
supervisorPath := filepath.Join(filepath.Dir(executable), "workspace-supervisor")
environment := append(os.Environ(), "WORKSPACE_AGENT_PID="+fmt.Sprint(agentPID))
if err := syscall.Exec(supervisorPath, []string{supervisorPath}, environment); err != nil {
panic(err)
}
}
func loadWorkspaceConfig() (workspaceConfig, error) {
flag := os.Getenv("PWN_FLAG")
os.Unsetenv("PWN_FLAG")
if flag == "" {
return workspaceConfig{}, errors.New("PWN_FLAG is not set")
}
user := os.Getenv("PWN_USER")
if user == "" {
user = "hacker"
}
if strings.ContainsAny(user, ":/\n\r") || user == "." || user == ".." {
return workspaceConfig{}, fmt.Errorf("invalid PWN_USER %q", user)
}
return workspaceConfig{
flag: flag,
user: user,
home: filepath.Join("/home", user),
}, nil
}
func prepareWorkspace(config workspaceConfig) error {
if err := setupUser(config.user, config.home); err != nil {
return err
}
if err := setupRunDirectories(); err != nil {
return err
}
if err := writeFlag(config.flag); err != nil {
return fmt.Errorf("write flag: %w", err)
}
return nil
}
func setupRunDirectories() error {
for _, directory := range []string{challengeRunDir, workspaceRunDir} {
if err := os.MkdirAll(directory, 0755); err != nil {
return err
}
if err := os.Chmod(directory, 0755); err != nil {
return err
}
}
for _, directory := range []string{workspaceUserRunDir, workspaceServicesDir} {
if err := os.MkdirAll(directory, 0700); err != nil {
return err
}
if err := os.Chown(directory, agentUID, agentGID); err != nil {
return err
}
if err := os.Chmod(directory, 0700); err != nil {
return err
}
}
if err := linkChallengeBin(); err != nil {
return err
}
if err := linkWorkspaceProfile(); err != nil {
return err
}
return linkServiceDefinitions()
}
func linkChallengeBin() error {
if _, err := os.Stat(challengeBin); errors.Is(err, os.ErrNotExist) {
return nil
} else if err != nil {
return err
}
if err := os.Remove(challengeRunBin); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return os.Symlink(challengeBin, challengeRunBin)
}
func linkWorkspaceProfile() error {
target, err := workspaceProfileTarget()
if err != nil {
return err
}
if err := os.Remove(workspaceProfile); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return os.Symlink(target, workspaceProfile)
}
func workspaceProfileTarget() (string, error) {
if len(os.Args) > 0 && filepath.IsAbs(os.Args[0]) {
return filepath.Clean(filepath.Join(filepath.Dir(os.Args[0]), "..")), nil
}
executable, err := os.Executable()
if err != nil {
return "", err
}
return filepath.Clean(filepath.Join(filepath.Dir(executable), "..")), nil
}
func runChallengeInit() error {
if err := runInit(); err != nil {
return fmt.Errorf("run .init: %w", err)
}
return nil
}
func setupUser(user string, home string) error {
if err := upsertPasswdUser(user, home); err != nil {
return err
}
if err := upsertGroup(user); err != nil {
return err
}
if _, err := os.Stat(home); errors.Is(err, os.ErrNotExist) {
if err := os.MkdirAll(home, 0755); err != nil {
return err
}
if err := os.Chown(home, agentUID, agentGID); err != nil {
return err
}
} else if err != nil {
return err
}
return nil
}
func upsertPasswdUser(user string, home string) error {
const passwdPath = "/etc/passwd"
data, err := os.ReadFile(passwdPath)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
lines := make([]string, 0)
found := false
for _, line := range strings.Split(strings.TrimRight(string(data), "\n"), "\n") {
if line == "" {
continue
}
fields := strings.Split(line, ":")
if len(fields) < 7 {
lines = append(lines, line)
continue
}
uid, _ := strconv.Atoi(fields[2])
if fields[0] == user || uid == agentUID {
if found {
continue
}
fields[0] = user
fields[2] = strconv.Itoa(agentUID)
fields[3] = strconv.Itoa(agentGID)
fields[5] = home
fields[6] = "/bin/bash"
lines = append(lines, strings.Join(fields, ":"))
found = true
continue
}
lines = append(lines, line)
}
if !found {
lines = append(lines, fmt.Sprintf("%s:x:%d:%d::%s:/bin/bash", user, agentUID, agentGID, home))
}
return writeLines(passwdPath, lines, 0644)
}
func upsertGroup(user string) error {
const groupPath = "/etc/group"
data, err := os.ReadFile(groupPath)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
lines := make([]string, 0)
found := false
for _, line := range strings.Split(strings.TrimRight(string(data), "\n"), "\n") {
if line == "" {
continue
}
fields := strings.Split(line, ":")
if len(fields) < 4 {
lines = append(lines, line)
continue
}
gid, _ := strconv.Atoi(fields[2])
if fields[0] == user || gid == agentGID {
if found {
continue
}
fields[0] = user
fields[2] = strconv.Itoa(agentGID)
lines = append(lines, strings.Join(fields, ":"))
found = true
continue
}
lines = append(lines, line)
}
if !found {
lines = append(lines, fmt.Sprintf("%s:x:%d:", user, agentGID))
}
return writeLines(groupPath, lines, 0644)
}
func writeLines(path string, lines []string, mode os.FileMode) error {
var buffer bytes.Buffer
for _, line := range lines {
buffer.WriteString(line)
buffer.WriteByte('\n')
}
return os.WriteFile(path, buffer.Bytes(), mode)
}
func linkServiceDefinitions() error {
sourceDir, err := serviceDefinitionsDir()
if err != nil {
return err
}
entries, err := os.ReadDir(sourceDir)
if err != nil {
return err
}
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".toml" {
continue
}
sourcePath := filepath.Join(sourceDir, entry.Name())
targetPath := filepath.Join(workspaceServicesDir, entry.Name())
if err := os.Remove(targetPath); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if err := os.Symlink(sourcePath, targetPath); err != nil {
return err
}
if err := os.Lchown(targetPath, agentUID, agentGID); err != nil {
return err
}
}
return nil
}
func serviceDefinitionsDir() (string, error) {
directory := filepath.Join(workspaceProfile, "share", "workspace", "services")
if _, err := os.Stat(directory); err != nil {
return "", err
}
return directory, nil
}
func writeFlag(flag string) error {
if flag == "" {
return errors.New("flag is empty")
}
if err := os.WriteFile("/flag", []byte(flag+"\n"), 0400); err != nil {
return err
}
if err := os.Chown("/flag", 0, 0); err != nil {
return err
}
return os.Chmod("/flag", 0400)
}
func runInit() error {
if _, err := os.Stat("/challenge/.init"); errors.Is(err, os.ErrNotExist) {
return nil
} else if err != nil {
return err
}
command := exec.Command("/challenge/.init")
command.Stdout = os.Stderr
command.Stderr = os.Stderr
return command.Run()
}
func sendControl(writer *os.File, message controlMessage) {
_ = json.NewEncoder(writer).Encode(message)
}