-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
411 lines (344 loc) · 11.2 KB
/
main.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
// Erase your computer if you call this API.
//
// Based on the Tailscale tshello.
package main
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"html"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
"tailscale.com/client/tailscale"
"tailscale.com/client/tailscale/apitype"
"tailscale.com/tsnet"
)
var (
addr = flag.String("addr", ":80", "address to listen on")
jwt string = ""
)
type DeviceListResponse struct {
Response []DeviceList `json:response`
}
type DeviceList struct {
Devices []Device `json:devices`
Rows int `json:rows`
PageSize int `json:page_size`
Page int `json:page`
}
type Device struct {
DeviceUDID string `json:deviceudid`
LocalHostName string `json:LocalHostname`
}
var tsclient *tailscale.LocalClient
func main() {
flag.Parse()
log.Println("Logging in to Mosyle ...")
err := mosyleLogin()
if err != nil {
log.Fatalf("failed to login to mosyle: %v", err)
}
go func() {
DailyRefresh:
for {
time.Sleep(20 * time.Hour)
err := mosyleLogin()
if err == nil {
continue DailyRefresh
}
log.Printf("failed to login to mosyle, trying again several more times: %v\n", err)
for i := 0; i <= 60; i += 1 {
time.Sleep(220 * time.Second)
err := mosyleLogin()
if err == nil {
continue DailyRefresh
}
log.Printf("Failure #%d/60: %v\n", i, err)
}
log.Fatalf("No luck after a bunch of attempts")
}
}()
log.Println("Verifying we can fetch machines from Mosyle...")
m, err := enumerateMachines()
if err != nil {
log.Fatal(err)
}
log.Println("Current machines:", m)
s := &tsnet.Server{
AuthKey: os.Getenv("TS_AUTHKEY"),
Ephemeral: true,
Hostname: "bonk",
}
tsclient_, err := s.LocalClient()
if err != nil {
log.Fatal(err)
}
tsclient = tsclient_
defer s.Close()
ln, err := s.Listen("tcp", *addr)
if err != nil {
log.Println(err)
}
defer ln.Close()
if *addr == ":443" {
ln = tls.NewListener(ln, &tls.Config{
GetCertificate: tsclient.GetCertificate,
})
}
http.HandleFunc("/erase/", withEraseContext(erase))
http.HandleFunc("/erase-self", withEraseContext(eraseSelf))
http.HandleFunc("/erase-all", withEraseContext(eraseAll))
http.HandleFunc("/", notFound)
log.Fatal(http.Serve(ln, nil))
}
type ctxKey struct{}
type eraseContext struct {
client *apitype.WhoIsResponse
devices []Device
}
func withEraseContext(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
client, err := tsclient.WhoIs(r.Context(), r.RemoteAddr)
if err != nil {
log.Printf("Could not identify client: %v", err)
http.Error(w, "Unauthorized", 401)
return
}
if r.Method != "POST" {
http.Error(w, "Method not allowed, only POSTs can erase", 405)
return
}
devices, err := enumerateMachines()
if err != nil {
log.Fatal(err)
}
ctx := eraseContext{client, devices}
fn(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, ctx)))
}
}
func eraseSelf(w http.ResponseWriter, r *http.Request) {
bonk(w, r, r.Context().Value(ctxKey{}).(eraseContext).client.Node.ComputedName)
}
var nameRegex = regexp.MustCompile("/erase/([^/]+)")
func erase(w http.ResponseWriter, r *http.Request) {
name := nameRegex.FindStringSubmatch(r.URL.Path)[1]
bonk(w, r, name)
}
// This sends the erase requests one-by-one synchronously. It would be
// nicer to submit them in parallel and return a job ID or something
// which can later be queried for progress, but at the current scale (4
// machines) I think waiting a few seconds per machine is still
// acceptable.
func eraseAll(w http.ResponseWriter, r *http.Request) {
context := r.Context().Value(ctxKey{}).(eraseContext)
anyFailed := false
messages := make([]string, 0, len(context.devices))
for _, device := range context.devices {
if err := sendErase(device); err != nil {
anyFailed = true
messages = append(messages, fmt.Sprintf("could not bonk %s: %s\n", device.LocalHostName, err))
} else {
messages = append(messages, fmt.Sprintf("bonking %s!\n", device.LocalHostName))
}
}
if anyFailed {
w.WriteHeader(500)
}
for _, msg := range messages {
w.Write([]byte("IT'S A BONK PARTY!"))
w.Write([]byte(msg))
}
}
func bonk(w http.ResponseWriter, r *http.Request, name string) {
context := r.Context().Value(ctxKey{}).(eraseContext)
device, err := getDeviceFromName(context.devices, name)
if err != nil {
log.Fatal(err)
}
if device == nil {
// REVIEW: is this actually a thing that mosyle does?
device, err = getDeviceFromName(context.devices, strings.TrimSuffix(name, "-1"))
if err != nil {
log.Fatal(err)
}
}
if device == nil {
fmt.Fprintf(w, "I don't know who %s is, %s!\n",
html.EscapeString(name),
html.EscapeString(firstLabel(context.client.Node.ComputedName)),
)
log.Printf("no known device by name %s", name)
} else {
if err = sendErase(*device); err != nil {
log.Printf("Failed to erase %s:", name, err)
}
fmt.Fprintf(w, `
⠀⠀⠀⠀⠀⠀⢀⣁⣤⣶⣶⡒⠒⠲⠾⣭⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⣿⡀⣸⠟⠛⠃⠀⣀⣀⠈⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⡠⠂⢠⠏⠀⠉⠀⠀⠀⠰⣿⠟⠀⠙⢧⡀⠀⠀⠀⠀⠀⠀⢀⠀⠀⢀⢀⡀⣼⣧⡾⠃⠀⠀⠀⠀⠀
⢀⠔⠀⣠⠔⠁⠀⠀⠀⠀⠀⠀⠀⠰⢄⡠⣶⢾⣽⡆⠀⠀⠀⠀⠄⢡⡀⢰⣾⣿⡀⠈⠵⠟⠛⠀⠀⠀⠀⠀
⠀⣠⠊⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⡟⠋⠉⠀⠀⠀⠀⣰⢦⣼⡷⣼⡏⢯⢉⣡⠖⠋⣩⡇⠀⠀⠀⠀
⣰⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⢺⣿⡄⣿⡄⣿⢿⠈⢁⡴⠋⠀⢀⣴⣋⡀⠀⠀⠀⠀
⡇⠀⠀⢰⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⠒⢛⣡⣸⡏⢹⡟⠻⠏⢀⡴⠋⠀⣠⣖⠻⠿⠿⣤⡀⠀⠀⠀
⡇⠀⠀⠈⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡟⠀⠛⢡⡞⠻⠟⠁⢀⡴⠋⢀⣤⣞⣛⣻⡆⠀⠀⠉⢇⠀⠀⠀
⣇⠀⠀⠀⠈⢦⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠇⠀⠠⠏⠀⠀⢀⠴⠋⣀⠴⣿⠛⠛⠁⠈⠁⠀⠀⠀⠈⢧⠀⡄
⠸⡄⠀⠀⠀⠀⡇⠀⠀⢰⠃⠀⠈⣇⠀⠸⣦⡀⠀⠀⢀⡔⠁⣠⠞⠁⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡀⠀
⠀⠙⣄⠀⠀⠀⣿⠀⠀⢸⠒⠒⠒⠻⡀⠀⣷⠬⣉⡶⠋⣠⠞⠁⠀⠀⠀⡇⠀⠀⠀⡀⠀⢠⠀⠀⠀⠘⡇⠀
⠀⠀⠈⠑⠦⠤⣽⣄⠀⢸⠤⠤⠤⠤⢷⡀⠸⣷⠋⣠⢾⡁⠀⠀⠀⠀⠀⡇⢠⠇⠀⢹⠀⢸⠃⠀⠀⣸⠃⠀
⠀⠀⠀⠀⠀⠀⠀⢹⠀⢸⠀⠀⠀⠀⠀⢈⠦⣀⣙⣻⡞⠃⠀⠀⠀⢀⡼⢡⠧⠤⠤⢸⠀⣾⠤⠤⠚⠁⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢸⡀⠸⡄⠀⠀⠀⠀⣧⠴⠃⠉⠉⠁⠀⠀⠰⣾⡭⠔⠁⠀⠀⠀⡜⠀⡇⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠳⢤⣼⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠂⠄⠀⠀⠀⠀⠀⢰⣥⣴⠃⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠐⠀⠤⠐⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
`+"%s is getting bonked! See you soon!\n",
html.EscapeString(name),
)
}
}
func notFound(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Not found. Try /erase-self or /erase/<node-name>", 404)
return
}
func firstLabel(s string) string {
if i := strings.Index(s, "."); i != -1 {
return s[:i]
}
return s
}
func getDeviceFromName(devices []Device, name string) (*Device, error) {
matching_udids := []Device{}
for _, dev := range devices {
if dev.LocalHostName == name {
matching_udids = append(matching_udids, dev)
}
}
if len(matching_udids) == 0 {
return nil, nil
}
if len(matching_udids) > 1 {
return nil, errors.New("Multiple machines with matching names")
}
return &matching_udids[0], nil
}
func mosyleLogin() error {
data, err := json.Marshal(map[string]string{
"email": os.Getenv("MOSYLE_EMAIL"),
"password": os.Getenv("MOSYLE_PASSWORD"),
})
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, "https://businessapi.mosyle.com/v1/login", bytes.NewBuffer(data))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
// !!!: We don't use `Set` here because Mosyle is sensitive to the case of the
// `accesstoken` header -- http will canonicalize `accesstoken` to
// `Accesstoken`, and Mosyle won't accept that.
// https://stackoverflow.com/a/26352765
req.Header["accessToken"] = []string{os.Getenv("MOSYLE_ACCESS_TOKEN")}
client := http.Client{
Timeout: 30 * time.Second,
}
res, err := client.Do(req)
if err != nil {
return err
}
if res.StatusCode == 200 {
if len(res.Header["Authorization"]) == 1 {
jwt = res.Header["Authorization"][0]
fmt.Println("Refreshed the Mosyle JWT")
return nil
} else {
return fmt.Errorf("no jwt with the body")
}
} else {
body, _ := ioutil.ReadAll(res.Body)
fmt.Printf("logging in failed\n response: %v\nbody: %v\n", res, string(body))
return fmt.Errorf("non-200 response while logging in")
}
}
func enumerateMachines() ([]Device, error) {
data := url.Values{
"operation": {"list"},
"options[os]": {"mac"},
}
req, err := http.NewRequest(http.MethodPost, "https://businessapi.mosyle.com/v1/devices", strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", jwt)
// !!!: We don't use `Set` here because Mosyle is sensitive to the case of the
// `accesstoken` header -- http will canonicalize `accesstoken` to
// `Accesstoken`, and Mosyle won't accept that.
// https://stackoverflow.com/a/26352765
req.Header["accesstoken"] = []string{os.Getenv("MOSYLE_ACCESS_TOKEN")}
client := http.Client{
Timeout: 5 * time.Second,
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
fmt.Printf("enumerating machines: %v\n", res)
body, _ := ioutil.ReadAll(res.Body)
obj := &DeviceListResponse{}
if err := json.Unmarshal(body, &obj); err != nil {
fmt.Println("error unmarshaling body:", string(body))
return nil, err
}
if obj.Response == nil {
return nil, fmt.Errorf("nil Response in Device list")
}
if len(obj.Response) != 1 {
return nil, fmt.Errorf("Too many Responses in Device list")
}
if obj.Response[0].Devices == nil {
return nil, fmt.Errorf("Response's Devices list is nil")
}
devices_response := obj.Response[0]
if devices_response.PageSize == devices_response.Rows {
fmt.Println("Number of devices returend matches the page size! Could be losing devices, since we don't paginate.")
}
if devices_response.Devices == nil {
return nil, fmt.Errorf("Response's Devices list is nil")
}
return devices_response.Devices, nil
}
func sendErase(device Device) error {
data := url.Values{
"operation": {"wipe_devices"},
"devices[]": {device.DeviceUDID},
"options[pin_code]": {"123456"},
"options[ObliterationBehavior]": {"DoNotObliterate"},
}
req, err := http.NewRequest(http.MethodPost, "https://businessapi.mosyle.com/v1/devices", strings.NewReader(data.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Authorization", jwt)
req.Header.Set("accesstoken", os.Getenv("MOSYLE_ACCESS_TOKEN"))
client := http.Client{
Timeout: 5 * time.Second,
}
res, err := client.Do(req)
if err != nil {
return err
}
log.Printf("sending wipe: %v\n", res)
body, _ := ioutil.ReadAll(res.Body)
log.Printf("reply: %v\n", body)
return nil
}