-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
419 lines (351 loc) · 10.7 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
// Copyright 2018 Adam Shannon
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"errors"
"flag"
"fmt"
"net/url"
"os"
"runtime"
"strings"
"github.com/adamdecaf/cert-manage/pkg/cmd"
"github.com/adamdecaf/cert-manage/pkg/store"
"github.com/adamdecaf/cert-manage/pkg/ui"
)
const Version = "0.1.1-dev"
var (
fs = flag.NewFlagSet("flags", flag.ExitOnError)
// incantations of "--help"
flagHelp1 = fs.Bool("h", false, "")
flagHelp2 = fs.Bool("help", false, "")
// -file is used to specify an input file path
flagFile = fs.String("file", "", "")
// -url is used to specify an input URL
flagURL = fs.String("url", "", "")
// -app is used for operating on an installed application
flagApp = fs.String("app", "", "")
// -ui is used for choosing a different ui
flagUI = fs.String("ui", ui.DefaultUI(), "")
// -from is used by 'gen-whitelist' to specify url sources
flagFrom = fs.String("from", "", "")
// -out is used by 'gen-whitelist' to specify output file location
flagOutFile = fs.String("out", "", "")
// Output
flagCount = fs.Bool("count", false, "")
flagFormat = fs.String("format", ui.DefaultFormat(), "")
// internal override to show help text
callForHelp = false
)
func init() {
fs.Usage = func() {
fmt.Printf(`Usage of cert-manage version %s
SUB-COMMANDS
add Add certificate(s) to a store
backup Take a backup of the specified certificate store
connect Attempt to load a remote URL with the platform (or app) store
gen-whitelist Create a whitelist from various sources
list List the currently installed and trusted certificates
restore Revert the certificate trust back to, optionally takes -file <path>
version Show the version of cert-manage
whitelist Remove trust from certificates which do not match the whitelist in <path>
APPS
Supported apps: %s
FLAGS
-app <name> The name of an application which to perform the given command on.
-file <path> Local file path
-from <type(s)> Which sources to capture urls from. Comma separated list. (Options: browser, chrome, firefox, file)
-help Show this help dialog
-ui <type> Method of adjusting certificates to be removed/untrusted. (default: %s, options: %s)
-url <where> Remote URL to download and use in a command
OUTPUT
-count Output the count of certificates instead of each certificate
-format <format> Change the output format for a given command (default: %s, options: %s)
DEBUGGING
Alongside command line flags are two environmental varialbes read by cert-manage:
- DEBUG=1 Enabled debug logging, GODEBUG=x509roots=1 also works and enabled Go's debugging
- TRACE=<where> Saves a binary trace file at <where> of the execution
`,
getVersion(),
strings.Join(store.GetApps(), ", "),
ui.DefaultUI(),
strings.Join(ui.GetUIs(), ", "),
ui.DefaultFormat(),
strings.Join(ui.GetFormats(), ", "),
)
}
}
func calledHelp() bool {
return callForHelp || *flagHelp1 || *flagHelp2
}
type command struct {
fn func() error
appfn func(string) error
help string
}
func trace() *cmd.Trace {
trace, err := cmd.NewTrace(os.Getenv("TRACE"))
if err != nil {
fmt.Printf("ERROR: setting up tracing: %v", err)
os.Exit(1)
}
err = trace.Start()
if err != nil {
fmt.Printf("ERROR: starting trace: %v", err)
os.Exit(1)
}
return trace
}
func main() {
t := trace()
defer func() {
err := t.Stop()
if err != nil {
fmt.Printf("ERROR: stopping trace: %v", err)
os.Exit(1)
}
}()
// Just show help if there aren't enough arguments to do anything
if len(os.Args) < 2 {
fs.Usage()
return
}
fs.Parse(os.Args[1:])
if len(os.Args) == 2 && calledHelp() {
fs.Usage()
return
}
fs.Parse(os.Args[2:]) // reparse
// Lift config options into a higher-level
cfg := &ui.Config{
Count: *flagCount,
Format: *flagFormat,
Outfile: *flagOutFile,
UI: *flagUI,
}
// Build up sub-commands
commands := make(map[string]*command)
commands["add"] = &command{
fn: func() error {
if *flagFile == "" {
callForHelp = true
return nil
}
return cmd.AddCertsFromFile(*flagFile)
},
appfn: func(a string) error {
if *flagFile == "" {
callForHelp = true
return nil
}
return cmd.AddCertsToAppFromFile(a, *flagFile)
},
help: fmt.Sprintf(`Usage: cert-manage add -file <path> [-app <name>]
Add a certificate to the platform store
cert-manage add -file <path>
Add a certificate to an application's store
cert-manage add -file <path> -app <name>
APPS
Supported apps: %s`, strings.Join(store.GetApps(), ", ")),
}
commands["backup"] = &command{
fn: func() error {
return cmd.BackupForPlatform()
},
appfn: func(a string) error {
return cmd.BackupForApp(a)
},
help: fmt.Sprintf(`Usage: cert-manage backup [-app <name>]
Backup a certificate store. This can be done for the platform or a given app.
APPS
Supported apps: %s`, strings.Join(store.GetApps(), ", ")),
}
commands["connect"] = &command{
fn: func() error {
u, err := parseConnectUrl(fs)
if err != nil {
return err
}
return cmd.ConnectWithPlatformStore(u)
},
appfn: func(a string) error {
u, err := parseConnectUrl(fs)
if err != nil {
return err
}
return cmd.ConnectWithAppStore(u, *flagApp)
},
help: fmt.Sprintf(`Usage: cert-manage connect [-app <name>] <url>
Attempt an HTTP connect to <url> with the given certificate store. If -app is provided then
the certificates for that application are loaded and used for the connection.
APPS
Supported apps: %s`, strings.Join(store.GetApps(), ", ")),
}
commands["gen-whitelist"] = &command{
fn: func() error {
if *flagOutFile == "" || (*flagFrom == "" && *flagFile == "") {
callForHelp = true
return nil
}
return cmd.GenerateWhitelist(*flagOutFile, *flagFrom, *flagFile)
},
help: fmt.Sprintf(`Usage: cert-manage gen-whitelist -out <where> [-file <file>] [-from <type>]
Generate a whitelist and write it to the filesystem. (At wherever -out points to.)
Also, you can pass -file to read a newline delimited file of URL's.
cert-manage gen-whitelist -file <path> -out whitelist.json
Generate a whitelist from browser history
cert-manage gen-whitelist -from firefox -out whitelist.json
Generate a whitelist from all browsers on a computer
cert-manage gen-whitelist -from browsers -out whitelist.json
APPS
Supported apps: %s`, strings.Join(store.GetApps(), ", ")),
}
commands["list"] = &command{
fn: func() error {
if *flagFile != "" {
return cmd.ListCertsFromFile(*flagFile, cfg)
}
if *flagURL != "" {
return cmd.ListCertsFromURL(*flagURL, cfg)
}
return cmd.ListCertsForPlatform(cfg)
},
appfn: func(a string) error {
return cmd.ListCertsForApp(a, cfg)
},
help: fmt.Sprintf(`Usage: cert-manage list [options]
List certificates currently installed on the platform or application.
List certificates from an application
cert-mange list -app firefox
List certificates from a file
cert-mange list -file <path>
List certificates from a URL
cert-manage list -url <endpoint>
FORMATTING
Change the output format (Default: %s, Options: %s)
cert-manage list -format openssl
Only show the count of certificates found
cert-manage list -count
cert-manage list -app java -count
cert-manage list -file <path> -count
Show the certificates on a local webpage (Default: %s, Options: %s)
cert-manage list -ui web
APPS
Supported apps: %s`,
ui.DefaultFormat(),
strings.Join(ui.GetFormats(), ", "),
ui.DefaultUI(),
strings.Join(ui.GetUIs(), ", "),
strings.Join(store.GetApps(), ", ")),
}
commands["restore"] = &command{
fn: func() error {
return cmd.RestoreForPlatform(*flagFile)
},
appfn: func(a string) error {
return cmd.RestoreForApp(a, *flagFile)
},
help: fmt.Sprintf(`Usage: cert-manage restore [-app <name>] [-file <path>]
Restore certificates from the latest backup
cert-manage restore
Restore certificates for the platform from a file
cert-manage restore -file <path>
Restore certificates for an application from the latest backup
cert-manage restore -app java
APPS
Supported apps: %s`, strings.Join(store.GetApps(), ", ")),
}
commands["whitelist"] = &command{
fn: func() error {
if *flagFile == "" {
callForHelp = true
return nil
}
return cmd.WhitelistForPlatform(*flagFile)
},
appfn: func(a string) error {
if *flagFile == "" {
callForHelp = true
return nil
}
return cmd.WhitelistForApp(a, *flagFile)
},
help: fmt.Sprintf(`Usage: cert-manage whitelist [-app <name>] -file <path>
Remove untrusted certificates from a store for the platform
cert-manage whitelist -file whitelist.json
Remove untrusted certificates in an app
cert-manage whitelist -file whitelist.json -app java
APPS
Supported apps: %s`, strings.Join(store.GetApps(), ", ")),
}
commands["version"] = &command{
fn: func() error {
fmt.Printf("%s\n", getVersion())
return nil
},
appfn: func(_ string) error {
return nil
},
help: getVersion(),
}
// Run whatever function we've got here..
c, ok := commands[strings.ToLower(os.Args[1])]
if (!ok && calledHelp()) || c == nil { // sub-command wasn't found
fs.Usage()
os.Exit(1)
}
if ok && calledHelp() {
fmt.Println(c.help)
os.Exit(1)
}
// sub-command found, try and exec something off it
if flagApp != nil && *flagApp != "" {
err := c.appfn(*flagApp)
if err != nil {
fmt.Printf("ERROR: %v\n", err)
os.Exit(1)
}
os.Exit(0)
}
err := c.fn()
if err != nil {
fmt.Printf("ERROR: %v\n", err)
os.Exit(1)
}
// some flags can set callForHelp, so let's check again
if calledHelp() {
fmt.Println(c.help)
os.Exit(1)
}
}
func getVersion() string {
return fmt.Sprintf("%s (Go: %s)", Version, runtime.Version())
}
func parseConnectUrl(fs *flag.FlagSet) (*url.URL, error) {
if fs.NArg() != 1 {
return nil, fmt.Errorf("unknown arguments: %s", strings.Join(fs.Args(), ", "))
}
raw := fs.Arg(0)
if raw == "" {
return nil, errors.New("no url specified")
}
u, err := url.Parse(raw)
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %v", raw, err)
}
if u.Scheme != "https" {
return nil, fmt.Errorf("non-secure url scheme used: %s", u.String())
}
return u, nil
}