forked from SignTools/SignTools
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
441 lines (410 loc) · 11.5 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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
package main
import (
"bytes"
"flag"
"fmt"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/pkg/errors"
htmlTemplate "html/template"
"io"
"ios-signer-service/src/assets"
"ios-signer-service/src/config"
"ios-signer-service/src/ngrok"
"ios-signer-service/src/storage"
"ios-signer-service/src/util"
"log"
"mime"
"net/http"
"os"
textTemplate "text/template"
"time"
)
var formNames = assets.FormNames{
FormFile: "file",
FormProfileId: "profile_id",
FormAppDebug: "all_devices",
FormAllDevices: "app_debug",
FormFileShare: "file_share",
FormToken: "align_app_id",
FormId: "id",
FormIdOriginal: "id_original",
FormIdProv: "id_prov",
FormIdCustom: "id_custom",
FormIdCustomText: "id_custom_text",
FormBundleId: "bundle_id",
}
func cleanupApps() error {
apps, err := storage.Apps.GetAll()
if err != nil {
return err
}
now := time.Now()
for _, app := range apps {
modTime, err := app.GetModTime()
if err != nil {
return err
}
if modTime.Add(time.Duration(config.Current.CleanupMins) * time.Minute).Before(now) {
if err := storage.Apps.Delete(app.GetId()); err != nil {
return err
}
}
}
return nil
}
func main() {
host := flag.String("host", "", "Listen host, empty for all")
port := flag.Uint64("port", 8080, "Listen port")
configFile := flag.String("config", "signer-cfg.yml", "Configuration file")
ngrokPort := flag.Uint64("ngrok-port", 0, "Ngrok web interface port. "+
"Used to automatically parse the server_url")
flag.Parse()
config.Load(*configFile)
storage.Load()
if *ngrokPort != 0 {
publicUrl, err := ngrok.GetPublicUrl(*ngrokPort, "https", 10*time.Second)
if err != nil {
log.Fatalln(err)
}
log.Println("ngrok public URL: " + publicUrl)
config.Current.ServerUrl = publicUrl
}
serve(*host, *port)
}
func serve(host string, port uint64) {
if err := os.MkdirAll(config.Current.SaveDir, 0777); err != nil {
log.Fatalln(err)
}
if config.Current.CleanupIntervalMins > 0 && config.Current.CleanupMins > 0 {
go func() {
for {
if err := cleanupApps(); err != nil {
log.Println(errors.WithMessage(err, "cleanup apps"))
}
time.Sleep(time.Duration(config.Current.CleanupIntervalMins) * time.Minute)
}
}()
}
if err := setBuilderSecrets(); err != nil {
log.Fatalln(err)
}
e := echo.New()
e.HideBanner = true
e.Use(middleware.Logger())
forcedBasicAuth := middleware.BasicAuth(func(username string, password string, c echo.Context) (bool, error) {
return username == config.Current.BasicAuth.Username && password == config.Current.BasicAuth.Password, nil
})
basicAuth := func(f echo.HandlerFunc) echo.HandlerFunc {
if config.Current.BasicAuth.Enable {
return forcedBasicAuth(f)
} else {
return f
}
}
workflowKeyAuth := middleware.KeyAuth(func(s string, c echo.Context) (bool, error) {
return s == config.Current.BuilderKey, nil
})
e.GET("/", renderIndex, basicAuth)
e.GET("/favicon.png", getFavIcon, basicAuth)
e.POST("/apps", uploadUnsignedApp, basicAuth)
e.GET("/apps/:id/signed", appResolver(getSignedApp))
e.GET("/apps/:id/manifest", appResolver(getManifest))
e.GET("/apps/:id/restart", appResolver(restartSign), basicAuth)
e.GET("/apps/:id/delete", appResolver(deleteApp), basicAuth)
e.GET("/apps/:id/2fa", appResolver(render2FAPage), basicAuth)
e.POST("/apps/:id/2fa", appResolver(set2FA), basicAuth)
e.GET("/jobs", getLastJob, workflowKeyAuth)
e.GET("/jobs/:id/2fa", jobResolver(get2FA), workflowKeyAuth)
e.POST("/jobs/:id/signed", jobResolver(uploadSignedApp), workflowKeyAuth)
e.Logger.Fatal(e.Start(fmt.Sprintf("%s:%d", host, port)))
}
func setBuilderSecrets() error {
return config.Current.Builder.SetSecrets(map[string]string{
"SECRET_KEY": config.Current.BuilderKey,
"SECRET_URL": config.Current.ServerUrl,
})
}
func getFavIcon(c echo.Context) error {
http.ServeContent(c.Response(), c.Request(), assets.FavIconStat.Name(), assets.FavIconStat.ModTime(), bytes.NewReader(assets.FavIconBytes))
return nil
}
func uploadSignedApp(c echo.Context, job *storage.ReturnJob) error {
if !storage.Jobs.DeleteById(job.Id) {
return errors.New("unable to delete return job " + job.Id)
}
app, ok := storage.Apps.Get(job.AppId)
if !ok {
return errors.New(fmt.Sprintf("return job %s appid %s not resolved", job.Id, job.AppId))
}
header, err := c.FormFile(formNames.FormFile)
if err != nil {
return err
}
file, err := header.Open()
if err != nil {
return err
}
defer file.Close()
if err := app.SetSigned(file, c.FormValue(formNames.FormBundleId)); err != nil {
return err
}
return c.NoContent(200)
}
func get2FA(c echo.Context, job *storage.ReturnJob) error {
code := job.TwoFactorCode.Load()
if code == "" {
return c.NoContent(404)
} else {
return c.String(200, code)
}
}
func appResolver(handler func(echo.Context, storage.App) error) func(c echo.Context) error {
return func(c echo.Context) error {
id := c.Param("id")
app, ok := storage.Apps.Get(id)
if !ok {
return c.NoContent(404)
}
return handler(c, app)
}
}
func jobResolver(handler func(echo.Context, *storage.ReturnJob) error) func(c echo.Context) error {
return func(c echo.Context) error {
id := c.Param("id")
job, ok := storage.Jobs.GetById(id)
if !ok {
return c.NoContent(404)
}
return handler(c, job)
}
}
func getLastJob(c echo.Context) error {
if err := storage.Jobs.TakeLastJob(c.Response()); errors.Is(err, storage.ErrNotFound) {
return c.NoContent(404)
} else if err != nil {
return err
}
c.Response().Header().Set("Content-Type", mime.TypeByExtension(".tar"))
return c.NoContent(200)
}
func render2FAPage(c echo.Context, _ storage.App) error {
return c.HTML(200, assets.TwoFactorHtml)
}
func set2FA(c echo.Context, app storage.App) error {
job, ok := storage.Jobs.GetByAppId(app.GetId())
if !ok {
return errors.New("no job found for app " + app.GetId())
}
job.TwoFactorCode.Store(c.FormValue("formToken"))
return c.Redirect(302, "/")
}
func deleteApp(c echo.Context, app storage.App) error {
if err := storage.Apps.Delete(app.GetId()); err != nil {
return err
}
return c.Redirect(302, "/")
}
func getManifest(c echo.Context, app storage.App) error {
t, err := textTemplate.New("").Parse(assets.ManifestPlist)
if err != nil {
return err
}
appName, err := app.GetName()
if err != nil {
return err
}
data := assets.ManifestData{
DownloadUrl: util.JoinUrlsPanic(config.Current.ServerUrl, "apps", c.Param("id"), "signed"),
BundleId: "com.foo.bar",
Title: appName,
}
var result bytes.Buffer
if err := t.Execute(&result, data); err != nil {
return err
}
return c.Blob(200, "text/plain", result.Bytes())
}
func getSignedApp(c echo.Context, app storage.App) error {
file, err := app.GetSigned()
if err != nil {
return err
}
defer file.Close()
if err := writeFileResponse(c, file, app); err != nil {
return err
}
return nil
}
func writeFileResponse(c echo.Context, file io.ReadSeeker, app storage.App) error {
name, err := app.GetName()
if err != nil {
return err
}
//TODO: Should use the file's mod time, otherwise may tell client to use cached file even though it has changed
modTime, err := app.GetModTime()
if err != nil {
return err
}
c.Response().Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
http.ServeContent(c.Response(), c.Request(), name, modTime, file)
return nil
}
func uploadUnsignedApp(c echo.Context) error {
profileId := c.FormValue(formNames.FormProfileId)
profile, ok := storage.Profiles.GetById(profileId)
if !ok {
return errors.New("no profile with id " + profileId)
}
header, err := c.FormFile(formNames.FormFile)
if err != nil {
return err
}
file, err := header.Open()
if err != nil {
return err
}
defer file.Close()
signArgs := ""
if c.FormValue(formNames.FormAllDevices) != "" {
signArgs += " -a"
}
if c.FormValue(formNames.FormAppDebug) != "" {
signArgs += " -d"
}
if c.FormValue(formNames.FormFileShare) != "" {
signArgs += " -s"
}
idType := c.FormValue(formNames.FormId)
userBundleId := c.FormValue(formNames.FormIdCustomText)
if idType == formNames.FormIdProv {
signArgs += " -n"
} else if idType == formNames.FormIdCustom {
signArgs += " -b " + userBundleId
}
app, err := storage.Apps.New(file, header.Filename, profile, signArgs, userBundleId)
if err != nil {
return err
}
if err := startSign(app); err != nil {
return err
}
return c.Redirect(302, "/")
}
func restartSign(c echo.Context, app storage.App) error {
if err := startSign(app); err != nil {
return err
}
return c.Redirect(302, "/")
}
func startSign(app storage.App) error {
if err := app.ResetModTime(); err != nil {
return err
}
profileId, err := app.GetProfileId()
if err != nil {
return err
}
storage.Jobs.MakeSignJob(app.GetId(), profileId)
if err := setBuilderSecrets(); err != nil {
return err
}
if err := config.Current.Builder.Trigger(); err != nil {
return err
}
if err := app.SetWorkflowUrl(config.Current.Builder.GetStatusUrl()); err != nil {
return err
}
return nil
}
func renderIndex(c echo.Context) error {
apps, err := storage.Apps.GetAll()
if err != nil {
return err
}
data := assets.IndexData{
FormNames: formNames,
}
for _, app := range apps {
isSigned, err := app.IsSigned()
if err != nil {
return err
}
modTime, err := app.GetModTime()
if err != nil {
return err
}
name, err := app.GetName()
if err != nil {
log.Println(errors.WithMessage(err, "get name"))
}
workflowUrl, err := app.GetWorkflowUrl()
if err != nil {
log.Println(errors.WithMessage(err, "get workflow url"))
}
bundleId, _ := app.GetBundleId()
profileId, err := app.GetProfileId()
if err != nil {
log.Println(errors.WithMessage(err, "get profile id"))
}
var profileName string
if profile, ok := storage.Profiles.GetById(profileId); ok {
profileName, err = profile.GetName()
if err != nil {
log.Println(errors.WithMessage(err, "get profile name"))
}
} else {
log.Println(errors.WithMessage(err, "get profile"))
profileName = "unknown"
}
appTimeoutTime := modTime.Add(time.Duration(config.Current.SignTimeoutMins) * time.Minute)
status := assets.AppStatusFailed
if isSigned {
status = assets.AppStatusSigned
} else if time.Now().Before(appTimeoutTime) {
status = assets.AppStatusProcessing
}
data.Apps = append(data.Apps, assets.App{
Id: app.GetId(),
Status: status,
Name: name,
ModTime: modTime.Format(time.RFC822),
WorkflowUrl: workflowUrl,
ProfileName: profileName,
BundleId: bundleId,
ManifestUrl: util.JoinUrlsPanic(config.Current.ServerUrl, "apps", app.GetId(), "manifest"),
DownloadUrl: util.JoinUrlsPanic(config.Current.ServerUrl, "apps", app.GetId(), "signed"),
TwoFactorUrl: util.JoinUrlsPanic(config.Current.ServerUrl, "apps", app.GetId(), "2fa"),
RestartUrl: util.JoinUrlsPanic(config.Current.ServerUrl, "apps", app.GetId(), "restart"),
DeleteUrl: util.JoinUrlsPanic(config.Current.ServerUrl, "apps", app.GetId(), "delete"),
})
}
profiles, err := storage.Profiles.GetAll()
if err != nil {
return err
}
for _, profile := range profiles {
name, err := profile.GetName()
if err != nil {
return err
}
isAccount, err := profile.IsAccount()
if err != nil {
return err
}
data.Profiles = append(data.Profiles, assets.Profile{
Id: profile.GetId(),
Name: name,
IsAccount: isAccount,
})
}
t, err := htmlTemplate.New("").Parse(assets.IndexHtml)
if err != nil {
return err
}
var result bytes.Buffer
if err := t.Execute(&result, data); err != nil {
return err
}
return c.HTMLBlob(200, result.Bytes())
}