Repository navigation
Expand file tree
/
Copy pathgpgkeys.go
More file actions
352 lines (287 loc) · 6.21 KB
/
Copy pathgpgkeys.go
File metadata and controls
352 lines (287 loc) · 6.21 KB
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
package main
import (
"bufio"
"bytes"
"fmt"
"os/exec"
"strconv"
"strings"
"time"
)
type UID struct {
Name string
Comment string
Email string
}
type SubKey struct {
KeyID string
Fingerprint string
Algo string
Created time.Time
Expires time.Time
Caps string
Secret bool
CardSerial string
Revoked bool
Expired bool
Invalid bool
Disabled bool
}
type secretInfo struct {
cardSerial string
}
type Key struct {
Primary SubKey
PrimaryUID UID
Validity string
SubKeys []SubKey
}
func LoadKeys() ([]Key, error) {
secret, err := loadSecretInfo()
if err != nil {
return nil, err
}
out, err := runGPG("--with-colons", "--list-keys")
if err != nil {
return nil, err
}
return parseKeyList(out, secret), nil
}
func loadSecretInfo() (map[string]secretInfo, error) {
out, err := runGPG("--with-colons", "--list-secret-keys")
if err != nil {
return nil, err
}
return parseSecretInfo(out), nil
}
func parseSecretInfo(out []byte) map[string]secretInfo {
set := map[string]secretInfo{}
sc := bufio.NewScanner(bytes.NewReader(out))
var pending *secretInfo
for sc.Scan() {
fields := strings.Split(sc.Text(), ":")
if len(fields) == 0 {
continue
}
switch fields[0] {
case "sec", "ssb":
info := secretInfo{}
if colonField(fields, 14) == ">" {
info.cardSerial = colonField(fields, 15)
}
pending = &info
case "fpr":
if pending != nil && len(fields) >= 10 {
set[fields[9]] = *pending
pending = nil
}
}
}
return set
}
func parseKeyList(out []byte, secret map[string]secretInfo) []Key {
var keys []Key
var cur *Key
var pendingSub *SubKey
pendingPrimaryFpr, pendingUID := false, false
flush := func() {
if cur != nil && cur.Primary.Fingerprint != "" {
keys = append(keys, *cur)
}
cur = nil
pendingSub = nil
pendingPrimaryFpr = false
pendingUID = false
}
sc := bufio.NewScanner(bytes.NewReader(out))
for sc.Scan() {
fields := strings.Split(sc.Text(), ":")
if len(fields) < 2 {
continue
}
switch fields[0] {
case "pub":
flush()
if len(fields) < 12 {
continue
}
cur = &Key{
Primary: SubKey{
KeyID: fields[4],
Created: parseTimestamp(fields[5]),
Expires: parseTimestamp(fields[6]),
Algo: algoDisplay(atoi(fields[3]), atoi(fields[2]), colonField(fields, 16)),
Caps: extractCaps(fields[11]),
Revoked: fields[1] == "r",
Expired: fields[1] == "e",
Invalid: fields[1] == "i",
Disabled: strings.ContainsRune(fields[11], 'D'),
},
}
pendingPrimaryFpr = true
pendingUID = true
case "sub":
if cur == nil || len(fields) < 12 {
continue
}
cur.SubKeys = append(cur.SubKeys, SubKey{
KeyID: fields[4],
Created: parseTimestamp(fields[5]),
Expires: parseTimestamp(fields[6]),
Algo: algoDisplay(atoi(fields[3]), atoi(fields[2]), colonField(fields, 16)),
Caps: extractCaps(fields[11]),
Revoked: fields[1] == "r",
Expired: fields[1] == "e",
Invalid: fields[1] == "i",
Disabled: strings.ContainsRune(fields[11], 'D'),
})
pendingSub = &cur.SubKeys[len(cur.SubKeys)-1]
case "fpr":
if cur == nil || len(fields) < 10 {
continue
}
fpr := fields[9]
info, hasSecret := secret[fpr]
if pendingPrimaryFpr {
cur.Primary.Fingerprint = fpr
cur.Primary.Secret = hasSecret
cur.Primary.CardSerial = info.cardSerial
pendingPrimaryFpr = false
} else if pendingSub != nil {
pendingSub.Fingerprint = fpr
pendingSub.Secret = hasSecret
pendingSub.CardSerial = info.cardSerial
pendingSub = nil
}
case "uid":
if cur == nil || !pendingUID || len(fields) < 10 {
continue
}
cur.PrimaryUID = parseUID(fields[9])
cur.Validity = validityName(fields[1])
pendingUID = false
}
}
flush()
return keys
}
func colonField(fields []string, idx int) string {
if idx >= len(fields) {
return ""
}
return fields[idx]
}
func atoi(s string) int {
n, _ := strconv.Atoi(s)
return n
}
func algoDisplay(algoNum, bits int, curve string) string {
if curve != "" {
return curve
}
switch algoNum {
case 1, 2, 3:
return fmt.Sprintf("rsa%d", bits)
case 16:
return fmt.Sprintf("elg%d", bits)
case 17:
return fmt.Sprintf("dsa%d", bits)
case 18:
return "ecdh"
case 19:
return "ecdsa"
case 22:
return "eddsa"
default:
return fmt.Sprintf("algo%d", algoNum)
}
}
func extractCaps(field string) string {
var b strings.Builder
for _, c := range field {
if c >= 'a' && c <= 'z' {
b.WriteRune(c - 'a' + 'A')
}
}
return b.String()
}
func validityName(letter string) string {
switch letter {
case "u":
return "ultimate"
case "f":
return "full"
case "m":
return "marginal"
case "n":
return "never"
case "r":
return "revoked"
case "e":
return "expired"
case "i":
return "invalid"
case "d":
return "disabled"
case "q", "o":
return "unknown"
}
return ""
}
func runGPG(args ...string) ([]byte, error) {
out, err := exec.Command("gpg", args...).Output()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok && len(ee.Stderr) > 0 {
return nil, fmt.Errorf("gpg: %s", strings.TrimSpace(string(ee.Stderr)))
}
return nil, err
}
return out, nil
}
func parseTimestamp(s string) time.Time {
if s == "" {
return time.Time{}
}
if n, err := strconv.ParseInt(s, 10, 64); err == nil && n > 0 {
return time.Unix(n, 0)
}
if t, err := time.Parse("2006-01-02", s); err == nil {
return t
}
return time.Time{}
}
func parseUID(raw string) UID {
s := unescapeColonField(raw)
var uid UID
if i := strings.LastIndex(s, "<"); i >= 0 {
if j := strings.LastIndex(s, ">"); j > i {
uid.Email = s[i+1 : j]
s = strings.TrimSpace(s[:i])
}
}
if i := strings.LastIndex(s, "("); i >= 0 {
if j := strings.LastIndex(s, ")"); j > i {
uid.Comment = s[i+1 : j]
s = strings.TrimSpace(s[:i])
}
}
uid.Name = s
return uid
}
func unescapeColonField(s string) string {
if !strings.Contains(s, `\x`) {
return s
}
var b strings.Builder
for i := 0; i < len(s); i++ {
if i+3 < len(s) && s[i] == '\\' && s[i+1] == 'x' {
if v, err := strconv.ParseUint(s[i+2:i+4], 16, 8); err == nil {
b.WriteByte(byte(v))
i += 3
continue
}
}
b.WriteByte(s[i])
}
return b.String()
}