-
Notifications
You must be signed in to change notification settings - Fork 8
/
cli_action.go
executable file
·471 lines (401 loc) · 10.4 KB
/
cli_action.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package main
import (
"crypto/dsa"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"math/big"
"reflect"
"golang.org/x/crypto/ed25519"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
const (
//https://github.com/openssh/openssh-portable/blob/315d2a4e674d0b7115574645cb51f968420ebb34/cipher.c#L98
CipherNoneBlockSize = 8
)
type ErrorJson struct {
Error bool `json:"error"`
ErrorMessage string `json:"error_message,omitempty"`
}
func createJsonError(e bool, m string) string {
j := ErrorJson{
Error: e,
ErrorMessage: m,
}
js, _ := json.Marshal(j)
return string(js)
}
type ErrorCollector []error
func (c *ErrorCollector) Collect(e error) {
*c = append(*c, e)
}
func (c *ErrorCollector) Error() (err string) {
for _, e := range *c {
err += fmt.Sprintf("%s\n", e.Error())
}
return err
}
func doCliAction(action string, keyNum int, filename []string) {
log.Println("CLI Action:", action)
var err error
var jsonData string
var jarray []JsonKey
if action == "list" {
jarray, err = doList()
if err != nil {
log.Println("Error:", err)
jsonData = createJsonError(true, fmt.Sprintf("Failed to list: %v", err))
} else {
j, _ := json.Marshal(jarray)
jsonData = string(j)
}
}
if action == "delete" {
if a, err := delKeys(keyNum); err != nil {
jsonData = createJsonError(true, fmt.Sprintf("Failed to delete key: %v", err))
} else {
jarray, err := doListJson(a)
if err != nil {
jsonData = createJsonError(true, fmt.Sprintf("Failed to parse key: %v", err))
} else {
j, _ := json.Marshal(jarray)
jsonData = string(j)
}
}
}
if action == "add" {
if a, err := addKeys(filename); err != nil {
jsonData = createJsonError(true, fmt.Sprintf("Failed to add key:\n%v", err.Error()))
} else {
jarray, err := doListJson(a)
if err != nil {
jsonData = createJsonError(true, fmt.Sprintf("Failed to parse key: %v", err))
} else {
j, _ := json.Marshal(jarray)
jsonData = string(j)
}
}
}
fmt.Println(jsonData)
}
type JsonKey struct {
PublicKey string
PrivateKey string
Fingerprint string
}
func doList() (jarray []JsonKey, err error) {
a := NewSshAgent()
jarray = make([]JsonKey, 0)
k, err := McLoadKeys()
if err == nil {
if err = a.addKeysToKeychain(k); err != nil {
return jarray, fmt.Errorf("Failed to load keys from Moolticute: %v", err)
} else {
if len(*k) > 0 { //only set keys loaded if keys are present
a.keysLoaded = true
}
log.Println(len(*k), "keys loaded from MP")
}
}
return doListJson(a)
}
func doListJson(a *SshAgent) (jarray []JsonKey, err error) {
jarray = make([]JsonKey, 0)
for i, mck := range a.Keys {
pubKey, err := getPubKeyRaw(mck.PrivateKey, mck.Comment)
if err != nil {
return jarray, fmt.Errorf("Failed to get pub key for key #%d: %v", i, err)
}
jkey := JsonKey{
PublicKey: pubKey.String(),
Fingerprint: fingerprintSHA256(pubKey) + " " + pubKey.Comment + " (" + pubKey.Format + ")",
}
pemblock := pemBlockForKey(mck.PrivateKey, pubKey)
if pemblock != nil {
jkey.PrivateKey = string(pem.EncodeToMemory(pemblock))
} else {
log.Println("Error, nil key!!")
continue
}
jarray = append(jarray, jkey)
}
return
}
type DSAKeyFormat struct {
Version int
P, Q, G, Y, X *big.Int
}
func pemBlockForKey(priv interface{}, agentPubKey *agent.Key) *pem.Block {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
case *dsa.PrivateKey:
val := DSAKeyFormat{
P: k.P, Q: k.Q, G: k.G,
Y: k.Y, X: k.X,
}
bytes, _ := asn1.Marshal(val)
return &pem.Block{Type: "DSA PRIVATE KEY", Bytes: bytes}
case *ecdsa.PrivateKey:
b, _ := x509.MarshalECPrivateKey(k)
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
case *ed25519.PrivateKey:
pub := k.Public().(ed25519.PublicKey)
//ED25519 key
edkey := struct {
Check1 uint32
Check2 uint32
Keytype string
Pub ed25519.PublicKey
Priv []byte
Comment string
Pad []byte `ssh:"rest"`
}{
Check1: 324328077, //random int should match
Check2: 324328077,
Keytype: ssh.KeyAlgoED25519,
Pub: pub,
Priv: *k,
Comment: agentPubKey.Comment,
}
//padding
i := 1
for (len(ssh.Marshal(edkey)) % CipherNoneBlockSize) != 0 {
edkey.Pad = append(edkey.Pad, byte(i&0xff))
i++
}
//openssh container
w := struct {
CipherName string
KdfName string
KdfOpts string
NumKeys uint32
PubKey []byte
PrivKeyBlock []byte
}{
CipherName: "none",
KdfName: "none",
NumKeys: 1,
PubKey: []byte(pub),
PrivKeyBlock: ssh.Marshal(edkey),
}
var b []byte
magic := append([]byte("openssh-key-v1"), 0)
b = append(b, magic...)
b = append(b, ssh.Marshal(w)...)
return &pem.Block{Type: "OPENSSH PRIVATE KEY", Bytes: b}
default:
fmt.Println("Unknown key type:", reflect.TypeOf(priv))
return nil
}
}
type ListKeyAction int
const (
ListPublicKeys ListKeyAction = iota
ListPubFinger
ListPrivKey
)
func listKeysCommand(action ListKeyAction, keyNum int) {
jarray, err := doList()
if err != nil {
fmt.Println("Error:", err)
return
}
if keyNum >= len(jarray) {
fmt.Println("Error:", keyNum, "is out of range. Only", len(jarray), "keys available.")
return
}
if len(jarray) == 0 {
fmt.Println("No keys.")
return
}
switch action {
case ListPublicKeys:
if keyNum < 0 {
for i, k := range jarray {
fmt.Printf("[%d]: %s\n", i, k.PublicKey)
}
} else {
fmt.Printf("%s\n", jarray[keyNum].PublicKey)
}
case ListPubFinger:
if keyNum < 0 {
for i, k := range jarray {
fmt.Printf("[%d]: %s\n", i, k.Fingerprint)
}
} else {
fmt.Printf("%s\n", jarray[keyNum].Fingerprint)
}
case ListPrivKey:
if keyNum < 0 {
for i, k := range jarray {
fmt.Printf("Private key %d:\n%s\n", i, k.PrivateKey)
}
} else {
fmt.Printf("%s\n", jarray[keyNum].PrivateKey)
}
}
}
func delKeysCommand(keyNum int) {
if _, err := delKeys(keyNum); err != nil {
fmt.Println("Failed to delete key:", err)
} else {
fmt.Println("Key deleted successfully")
}
}
func delKeys(keyNum int) (a *SshAgent, err error) {
a = NewSshAgent()
if keyNum < 0 {
if err := a.removeAllKeys(true); err != nil {
return a, fmt.Errorf("Failed to remove all keys: %v", err)
}
} else {
k, err := McLoadKeys()
if err == nil {
if err = a.addKeysToKeychain(k); err != nil {
return a, fmt.Errorf("Failed to load keys from Moolticute: %v\n", err)
} else {
if len(*k) > 0 { //only set keys loaded if keys are present
a.keysLoaded = true
}
log.Println(len(*k), "keys loaded from MP")
}
}
if keyNum >= len(*k) {
return a, fmt.Errorf("Error: %d is out of range. Only %d keys available.", keyNum, len(*k))
}
//found the key, delete it
copy(a.Keys[keyNum:], a.Keys[keyNum+1:])
a.Keys = a.Keys[:len(a.Keys)-1]
//Send keys to moolticute
if err := McSetKeys(a.ToMcKeys()); err != nil {
return a, fmt.Errorf("Failed to remove key from moolticute: %v", err)
}
}
return a, err
}
func addKeysCommand(filename []string) {
if _, err := addKeys(filename); err != nil {
fmt.Printf("Errors collected:\n%s", err.Error())
} else {
fmt.Println("Key added successfully")
}
}
type AddKey struct {
AddedKey *agent.AddedKey
PubKey *agent.Key
Filename string
}
func addKeys(filename []string) (a *SshAgent, loadErrors ErrorCollector) {
var newKeys []AddKey
for _, f := range filename {
fileData, err := ioutil.ReadFile(f)
if err != nil {
loadErrors.Collect(fmt.Errorf("[%s] Failed to read file, %v", f, err))
continue
}
key, err := ssh.ParseRawPrivateKey(fileData)
if err != nil {
loadErrors.Collect(fmt.Errorf("[%s] Failed to parse, %v", f, err))
continue
}
//Reparse the file and try to read the comment. The Golang api does
// not export the comment field
var comment string
block, _ := pem.Decode(fileData)
if block == nil {
loadErrors.Collect(fmt.Errorf("[%s] No SSH keys found, %v", f, err))
continue
}
switch block.Type {
case "OPENSSH PRIVATE KEY":
//In openssh format the comment is included inside the data block
comment = readOpensshComment(block.Bytes)
}
if comment == "" {
//try reading the comment from the .pub file
comment = readPubComment(f + ".pub")
}
addedKey := &agent.AddedKey{
PrivateKey: key,
Comment: comment,
}
//Get public key
pubKey, err := getPubKey(addedKey)
if err != nil {
loadErrors.Collect(fmt.Errorf("Failed to get public key, %v", err))
continue
}
//Check duplicated keys
isDup := false
for _, k := range newKeys {
if fingerprintSHA256(pubKey) == fingerprintSHA256(k.PubKey) {
loadErrors.Collect(fmt.Errorf("[%s] Key with fingerprint %v is a duplicate. Not adding this one", f, fingerprintSHA256(k.PubKey)))
isDup = true
}
}
if !isDup {
newKeys = append(newKeys, AddKey{
AddedKey: addedKey,
PubKey: pubKey,
Filename: f,
})
}
}
if len(newKeys) == 0 {
loadErrors.Collect(fmt.Errorf("No keys to add"))
return
}
a = NewSshAgent()
//Load keys from MC
k, err := McLoadKeys()
if err == nil {
if err = a.addKeysToKeychain(k); err != nil {
loadErrors.Collect(fmt.Errorf("Failed to load keys from Moolticute: %v\n", err))
return
} else {
if len(*k) > 0 { //only set keys loaded if keys are present
a.keysLoaded = true
}
log.Println(len(*k), "keys loaded from MP")
}
}
l, err := a.keyring.List()
if err != nil {
loadErrors.Collect(fmt.Errorf("Failed to list keychain, %v", err))
return
}
//check if the key was not already added by comparing pub keys
aKeyWasAdded := false
for _, ak := range newKeys {
isAlreadyAdded := false
for _, k := range l {
log.Println("Comparing fingerprint", fingerprintSHA256(ak.PubKey), "==", fingerprintSHA256(k))
if fingerprintSHA256(ak.PubKey) == fingerprintSHA256(k) {
loadErrors.Collect(fmt.Errorf("[%s] This key with fingerprint %v is already in the keychain. Skipping.", ak.Filename, fingerprintSHA256(k)))
isAlreadyAdded = true
}
}
if !isAlreadyAdded {
mck := AddedKeyToMcKey(ak.AddedKey)
a.Keys = append(a.Keys, mck)
aKeyWasAdded = true
}
}
if !aKeyWasAdded {
loadErrors.Collect(fmt.Errorf("Nothing to add. Aborting."))
return
}
//Send keys to moolticute
if err := McSetKeys(a.ToMcKeys()); err != nil {
loadErrors.Collect(fmt.Errorf("Failed to send keys to device, %v", err))
}
return a, loadErrors
}