forked from cozy/cozy-stack
/
config.go
415 lines (357 loc) · 10.7 KB
/
config.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
package cmd
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"github.com/cozy/cozy-stack/client/request"
"github.com/cozy/cozy-stack/model/account"
"github.com/cozy/cozy-stack/pkg/config/config"
"github.com/cozy/cozy-stack/pkg/crypto"
"github.com/cozy/cozy-stack/pkg/keymgmt"
"github.com/cozy/cozy-stack/pkg/utils"
"github.com/howeyc/gopass"
"github.com/spf13/cobra"
)
var configCmdGroup = &cobra.Command{
Use: "config <command>",
Short: "Show and manage configuration elements",
Long: `cozy-stack config allows to print and generate some parts of the configuration`,
}
var adminPasswdCmd = &cobra.Command{
Use: "passwd <filepath>",
Aliases: []string{"password", "passphrase", "pass"},
Short: "Generate an admin passphrase",
Long: `
cozy-stack instances passphrase generate a passphrase hash and save it to the specified file. If no file is specified, it is directly printed in standard output. This passphrase is the one used to authenticate accesses to the administration API.
The environment variable 'COZY_ADMIN_PASSPHRASE' can be used to pass the passphrase if needed.
`,
Example: "$ cozy-stack config passwd ~/.cozy/cozy-admin-passphrase",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 1 {
return cmd.Usage()
}
var filename string
if len(args) == 1 {
filename = filepath.Join(utils.AbsPath(args[0]))
ok, err := utils.DirExists(filename)
if err == nil && ok {
filename = path.Join(filename, config.GetConfig().AdminSecretFileName)
}
}
if filename != "" {
errPrintfln("Hashed passphrase will be written in %s", filename)
}
passphrase := []byte(os.Getenv("COZY_ADMIN_PASSPHRASE"))
if len(passphrase) == 0 {
errPrintf("Passphrase: ")
pass1, err := gopass.GetPasswdPrompt("", false, os.Stdin, os.Stderr)
if err != nil {
return err
}
errPrintf("Confirmation: ")
pass2, err := gopass.GetPasswdPrompt("", false, os.Stdin, os.Stderr)
if err != nil {
return err
}
if !bytes.Equal(pass1, pass2) {
return fmt.Errorf("Passphrase missmatch")
}
passphrase = pass1
}
b, err := crypto.GenerateFromPassphrase(passphrase)
if err != nil {
return err
}
var out io.Writer
if filename != "" {
var f *os.File
f, err = os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0440)
if err != nil {
return err
}
defer f.Close()
if err = os.Chmod(filename, 0440); err != nil {
return err
}
out = f
} else {
out = os.Stdout
}
_, err = fmt.Fprintln(out, string(b))
return err
},
}
var genKeysCmd = &cobra.Command{
Use: "gen-keys <filepath>",
Short: "Generate an key pair for encryption and decryption of credentials",
Long: `
cozy-stack config gen-keys generate a key-pair and save them in the specified path.
The decryptor key filename is given the ".dec" extension suffix.
The encryptor key filename is given the ".enc" extension suffix.
The files permissions are 0400.`,
Example: `$ cozy-stack config gen-keys ~/credentials-key
keyfiles written in:
~/credentials-key.enc
~/credentials-key.dec
`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return cmd.Usage()
}
filename := filepath.Join(utils.AbsPath(args[0]))
encryptorFilename := filename + ".enc"
decryptorFilename := filename + ".dec"
marshaledEncryptorKey, marshaledDecryptorKey, err := keymgmt.GenerateEncodedNACLKeyPair()
if err != nil {
return nil
}
if err = writeFile(encryptorFilename, marshaledEncryptorKey, 0400); err != nil {
return err
}
if err = writeFile(decryptorFilename, marshaledDecryptorKey, 0400); err != nil {
return err
}
errPrintfln("keyfiles written in:\n %s\n %s", encryptorFilename, decryptorFilename)
return nil
},
}
var encryptCredentialsDataCmd = &cobra.Command{
Use: "encrypt-data <encoding keyfile> <text>",
Short: "Encrypt data with the specified encryption keyfile.",
Long: `cozy-stack config encrypt-data encrypts any valid JSON data`,
Example: `
$ ./cozy-stack config encrypt-data ~/.cozy/key.enc "{\"foo\": \"bar\"}"
$ bmFjbNFjY+XZkS26YtVPUIKKm/JdnAGwG30n6A4ypS1p1dHev8hOtaRbW+lGneoO7PS9JCW8U5GSXhASu+c3UkaZ
`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return cmd.Usage()
}
// Check if we have good-formatted JSON
var result map[string]interface{}
err := json.Unmarshal([]byte(args[1]), &result)
if err != nil {
return err
}
encKeyStruct, err := readKeyFromFile(args[0])
if err != nil {
return err
}
dataEncrypted, err := account.EncryptBufferWithKey(encKeyStruct, []byte(args[1]))
if err != nil {
return err
}
data := base64.StdEncoding.EncodeToString(dataEncrypted)
fmt.Printf("%s\n", data)
return nil
},
}
var decryptCredentialsDataCmd = &cobra.Command{
Use: "decrypt-data <decoding keyfile> <ciphertext>",
Short: "Decrypt data with the specified decryption keyfile.",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return cmd.Usage()
}
decKeyStruct, err := readKeyFromFile(args[0])
if err != nil {
return err
}
dataEncrypted, err := base64.StdEncoding.DecodeString(args[1])
if err != nil {
return err
}
decrypted, err := account.DecryptBufferWithKey(decKeyStruct, dataEncrypted)
if err != nil {
return err
}
fmt.Printf("%s\n", decrypted)
return nil
},
}
var encryptCredentialsCmd = &cobra.Command{
Use: "encrypt-creds <keyfile> <login> <password>",
Aliases: []string{"encrypt-credentials"},
Short: "Encrypt the given credentials with the specified decryption keyfile.",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 3 {
return cmd.Usage()
}
credsEncryptor, err := readKeyFromFile(args[0])
if err != nil {
return err
}
encryptedCreds, err := account.EncryptCredentialsWithKey(credsEncryptor, args[1], args[2])
if err != nil {
return err
}
fmt.Printf("Encrypted credentials: %s\n", encryptedCreds)
return nil
},
}
var decryptCredentialsCmd = &cobra.Command{
Use: "decrypt-creds <keyfile> <ciphertext>",
Aliases: []string{"decrypt-credentials"},
Short: "Decrypt the given credentials cipher text with the specified decryption keyfile.",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return cmd.Usage()
}
credsDecryptor, err := readKeyFromFile(args[0])
if err != nil {
return err
}
credentialsEncrypted, err := base64.StdEncoding.DecodeString(args[1])
if err != nil {
return fmt.Errorf("Cipher text is not properly base64 encoded: %s", err)
}
login, password, err := account.DecryptCredentialsWithKey(credsDecryptor, credentialsEncrypted)
if err != nil {
return fmt.Errorf("Could not decrypt cipher text: %s", err)
}
fmt.Printf(`Decrypted credentials:
login: %q
password: %q
`, login, password)
return nil
},
}
func writeFile(filename string, data []byte, perm os.FileMode) error {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
if err != nil {
return err
}
n, err := f.Write(data)
if err == nil && n < len(data) {
err = io.ErrShortWrite
}
if err1 := f.Close(); err == nil {
err = err1
}
return err
}
func readKeyFromFile(filepath string) (*keymgmt.NACLKey, error) {
keyBytes, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, err
}
return keymgmt.UnmarshalNACLKey(keyBytes)
}
var insertAssetCmd = &cobra.Command{
Use: "insert-asset --url <url> --name <name> --shasum <shasum> --context <context>",
Short: "Inserts an asset",
Long: `Inserts a custom asset in a specific context
Deprecated: please use the command cozy-stack assets add.
`,
RunE: func(cmd *cobra.Command, args []string) error {
errPrintfln("Please use cozy-stack assets add, this command has been deprecated")
return addAsset(cmd, args)
},
}
var removeAssetCmd = &cobra.Command{
Use: "rm-asset [context] [name]",
Short: "Removes an asset",
Long: `Removes a custom asset in a specific context
Deprecated: please use the command cozy-stack assets rm.
`,
RunE: func(cmd *cobra.Command, args []string) error {
errPrintfln("Please use cozy-stack assets rm, this command has been deprecated")
return rmAsset(cmd, args)
},
}
var listAssetCmd = &cobra.Command{
Use: "ls-assets",
Short: "List assets",
Long: `List assets currently served by the stack
Deprecated: please use the command cozy-stack assets ls.
`,
RunE: func(cmd *cobra.Command, args []string) error {
errPrintfln("Please use cozy-stack assets ls, this command has been deprecated")
return lsAssets(cmd, args)
},
}
var showContextCmd = &cobra.Command{
Use: "show-context",
Short: "Show a context",
Example: "$ cozy-stack config show-context cozy_demo",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return cmd.Usage()
}
c := newAdminClient()
req := &request.Options{
Method: "GET",
Path: "instances/contexts/" + args[0],
}
res, err := c.Req(req)
if err != nil {
return err
}
defer res.Body.Close()
var v interface{}
err = json.NewDecoder(res.Body).Decode(&v)
if err != nil {
return err
}
json, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
fmt.Println(string(json))
return nil
},
}
var listContextsCmd = &cobra.Command{
Use: "ls-contexts",
Aliases: []string{"list-contexts"},
Short: "List contexts",
Long: "List contexts currently used by the stack",
Example: "$ cozy-stack config ls-contexts",
RunE: func(cmd *cobra.Command, args []string) error {
c := newAdminClient()
req := &request.Options{
Method: "GET",
Path: "instances/contexts",
}
res, err := c.Req(req)
if err != nil {
return err
}
defer res.Body.Close()
var v interface{}
err = json.NewDecoder(res.Body).Decode(&v)
if err != nil {
return err
}
json, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
fmt.Println(string(json))
return nil
},
}
func init() {
configCmdGroup.AddCommand(adminPasswdCmd)
configCmdGroup.AddCommand(genKeysCmd)
configCmdGroup.AddCommand(encryptCredentialsDataCmd)
configCmdGroup.AddCommand(decryptCredentialsDataCmd)
configCmdGroup.AddCommand(encryptCredentialsCmd)
configCmdGroup.AddCommand(decryptCredentialsCmd)
configCmdGroup.AddCommand(insertAssetCmd)
configCmdGroup.AddCommand(listAssetCmd)
configCmdGroup.AddCommand(removeAssetCmd)
configCmdGroup.AddCommand(showContextCmd)
configCmdGroup.AddCommand(listContextsCmd)
RootCmd.AddCommand(configCmdGroup)
insertAssetCmd.Flags().StringVar(&flagURL, "url", "", "The URL of the asset")
insertAssetCmd.Flags().StringVar(&flagName, "name", "", "The name of the asset")
insertAssetCmd.Flags().StringVar(&flagShasum, "shasum", "", "The shasum of the asset")
insertAssetCmd.Flags().StringVar(&flagContext, "context", "", "The context of the asset")
}