forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgp_key.go
692 lines (594 loc) · 16.3 KB
/
pgp_key.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package libkb
import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"regexp"
"strings"
keybase1 "github.com/keybase/client/go/protocol"
"github.com/keybase/go-crypto/openpgp"
"github.com/keybase/go-crypto/openpgp/armor"
"github.com/keybase/go-crypto/openpgp/packet"
jsonw "github.com/keybase/go-jsonw"
)
type PGPKeyBundle struct {
*openpgp.Entity
// We make the (fairly dangerous) assumption that the key will never be
// modified. This avoids the issue that encoding an openpgp.Entity is
// nondeterministic due to Go's randomized iteration order (so different
// exports of the same key may hash differently).
//
// If you're *sure* that you're creating a PGPKeyBundle from an armored
// *public* key, you can prefill this field and Export() will use it.
ArmoredPublicKey string
}
func NewPGPKeyBundle(entity *openpgp.Entity) *PGPKeyBundle {
return &PGPKeyBundle{Entity: entity}
}
const (
PGPFingerprintLen = 20
)
type PGPFingerprint [PGPFingerprintLen]byte
func PGPFingerprintFromHex(s string) (*PGPFingerprint, error) {
var fp PGPFingerprint
n, err := hex.Decode([]byte(fp[:]), []byte(s))
var ret *PGPFingerprint
if err != nil {
// Noop
} else if n != PGPFingerprintLen {
err = fmt.Errorf("Bad fingerprint; wrong length: %d", n)
} else {
ret = &fp
}
return ret, err
}
func PGPFingerprintFromSlice(b []byte) (*PGPFingerprint, error) {
if len(b) != PGPFingerprintLen {
return nil, fmt.Errorf("Bad fingerprint; wrong length: %d", PGPFingerprintLen)
}
var fp PGPFingerprint
copy(fp[:], b)
return &fp, nil
}
func PGPFingerprintFromHexNoError(s string) *PGPFingerprint {
if len(s) == 0 {
return nil
} else if f, e := PGPFingerprintFromHex(s); e == nil {
return f
} else {
return nil
}
}
func (p PGPFingerprint) String() string {
return hex.EncodeToString(p[:])
}
func (p PGPFingerprint) ToQuads() string {
x := []byte(strings.ToUpper(p.String()))
totlen := len(x)*5/4 - 1
ret := make([]byte, totlen)
j := 0
for i, b := range x {
ret[j] = b
j++
if (i%4) == 3 && j < totlen {
ret[j] = ' '
j++
}
}
return string(ret)
}
func (p PGPFingerprint) ToKeyID() string {
return strings.ToUpper(hex.EncodeToString(p[12:20]))
}
func (p PGPFingerprint) ToDisplayString(verbose bool) string {
if verbose {
return p.String()
}
return p.ToKeyID()
}
func (p *PGPFingerprint) Match(q string, exact bool) bool {
if p == nil {
return false
}
if exact {
return strings.ToLower(p.String()) == strings.ToLower(q)
}
return strings.HasSuffix(strings.ToLower(p.String()), strings.ToLower(q))
}
func (k *PGPKeyBundle) FullHash() (string, error) {
keyBlob, err := k.Encode()
if err != nil {
return "", err
}
keySum := sha256.Sum256([]byte(strings.TrimSpace(keyBlob)))
return hex.EncodeToString(keySum[:]), nil
}
// StripRevocations returns a copy of the key with revocations removed
func (k *PGPKeyBundle) StripRevocations() (strippedKey *PGPKeyBundle) {
entityCopy := *k.Entity
strippedKey = &PGPKeyBundle{Entity: &entityCopy}
strippedKey.Revocations = nil
oldSubkeys := strippedKey.Subkeys
strippedKey.Subkeys = nil
for _, subkey := range oldSubkeys {
// Skip revoked subkeys
if subkey.Sig.SigType == packet.SigTypeSubkeyBinding {
strippedKey.Subkeys = append(strippedKey.Subkeys, subkey)
}
}
return
}
func (k *PGPKeyBundle) StoreToLocalDb(g *GlobalContext) error {
s, err := k.Encode()
if err != nil {
return err
}
val := jsonw.NewString(s)
g.Log.Debug("| Storing Key (kid=%s) to Local DB", k.GetKID())
return g.LocalDb.Put(DbKey{Typ: DBPGPKey, Key: k.GetKID().String()}, []DbKey{}, val)
}
func (p PGPFingerprint) Eq(p2 PGPFingerprint) bool {
return FastByteArrayEq(p[:], p2[:])
}
func GetPGPFingerprint(w *jsonw.Wrapper) (*PGPFingerprint, error) {
s, err := w.GetString()
if err != nil {
return nil, err
}
return PGPFingerprintFromHex(s)
}
func GetPGPFingerprintVoid(w *jsonw.Wrapper, p *PGPFingerprint, e *error) {
ret, err := GetPGPFingerprint(w)
if err != nil {
*e = err
} else {
*p = *ret
}
}
func (k PGPKeyBundle) toList() openpgp.EntityList {
list := make(openpgp.EntityList, 1, 1)
list[0] = k.Entity
return list
}
func (k PGPKeyBundle) GetFingerprint() PGPFingerprint {
return PGPFingerprint(k.PrimaryKey.Fingerprint)
}
func (k PGPKeyBundle) GetFingerprintP() *PGPFingerprint {
fp := k.GetFingerprint()
return &fp
}
func (k PGPKeyBundle) KeysById(id uint64) []openpgp.Key {
return k.toList().KeysById(id)
}
func (k PGPKeyBundle) KeysByIdUsage(id uint64, usage byte) []openpgp.Key {
return k.toList().KeysByIdUsage(id, usage)
}
func (k PGPKeyBundle) DecryptionKeys() []openpgp.Key {
return k.toList().DecryptionKeys()
}
func (k PGPKeyBundle) MatchesKey(key *openpgp.Key) bool {
return FastByteArrayEq(k.PrimaryKey.Fingerprint[:],
key.Entity.PrimaryKey.Fingerprint[:])
}
func (k *PGPKeyBundle) Encode() (ret string, err error) {
if k.ArmoredPublicKey != "" {
return k.ArmoredPublicKey, nil
}
buf := bytes.Buffer{}
err = k.EncodeToStream(NopWriteCloser{&buf})
if err == nil {
ret = string(buf.Bytes())
k.ArmoredPublicKey = ret
}
return
}
func PGPKeyRawToArmored(raw []byte, priv bool) (ret string, err error) {
var writer io.WriteCloser
var out bytes.Buffer
var which string
if priv {
which = "PRIVATE"
} else {
which = "PUBLIC"
}
hdr := fmt.Sprintf("PGP %s KEY BLOCK", which)
writer, err = armor.Encode(&out, hdr, PGPArmorHeaders)
if err != nil {
return
}
if _, err = writer.Write(raw); err != nil {
return
}
writer.Close()
ret = out.String()
return
}
func (k *PGPKeyBundle) EncodeToStream(wc io.WriteCloser) (err error) {
// See Issue #32
var writer io.WriteCloser
writer, err = armor.Encode(wc, "PGP PUBLIC KEY BLOCK", PGPArmorHeaders)
if err != nil {
return
}
if err = k.Entity.Serialize(writer); err != nil {
return
}
if err = writer.Close(); err != nil {
return
}
return
}
func cleanPGPInput(s string) string {
rxx := regexp.MustCompile(`[ \t\r]*\n[ \t\r]*`)
s = strings.TrimSpace(s)
v := rxx.Split(s, -1)
ret := strings.Join(v, "\n")
return ret
}
// note: openpgp.ReadArmoredKeyRing only returns the first block.
// It will never return multiple entities.
func ReadOneKeyFromString(s string) (*PGPKeyBundle, error) {
s = cleanPGPInput(s)
reader := strings.NewReader(s)
el, err := openpgp.ReadArmoredKeyRing(reader)
return finishReadOne(el, s, err)
}
// firstPrivateKey scans s for a private key block.
func firstPrivateKey(s string) (string, error) {
scanner := bufio.NewScanner(strings.NewReader(s))
var lines []string
looking := true
complete := false
for scanner.Scan() {
line := scanner.Text()
if looking && strings.HasPrefix(line, "-----BEGIN PGP PRIVATE KEY BLOCK-----") {
looking = false
}
if looking {
continue
}
lines = append(lines, line)
if strings.HasPrefix(line, "-----END PGP PRIVATE KEY BLOCK-----") {
complete = true
break
}
}
if err := scanner.Err(); err != nil {
return "", err
}
if looking {
// never found a private key block
return "", NoSecretKeyError{}
}
if !complete {
// string ended without the end tag
return "", errors.New("never found end block line")
}
return strings.Join(lines, "\n"), nil
}
// ReadPrivateKeyFromString finds the first private key block in s
// and decodes it into a PGPKeyBundle. It is useful in the case
// where s contains multiple key blocks and you want the private
// key block. For example, the result of gpg export.
func ReadPrivateKeyFromString(s string) (*PGPKeyBundle, error) {
priv, err := firstPrivateKey(s)
if err != nil {
return nil, err
}
return ReadOneKeyFromString(priv)
}
func finishReadOne(el []*openpgp.Entity, armored string, err error) (*PGPKeyBundle, error) {
if err != nil {
return nil, err
}
if len(el) == 0 {
return nil, NoKeyError{"No keys found in primary bundle"}
} else if len(el) != 1 {
return nil, TooManyKeysError{len(el)}
} else {
e := el[0]
var maybeArmored string
if e.PrivateKey == nil {
maybeArmored = armored
}
return &PGPKeyBundle{e, maybeArmored}, nil
}
}
func ReadOneKeyFromBytes(b []byte) (*PGPKeyBundle, error) {
reader := bytes.NewBuffer(b)
el, err := openpgp.ReadKeyRing(reader)
return finishReadOne(el, "", err)
}
func GetOneKey(jw *jsonw.Wrapper) (*PGPKeyBundle, error) {
s, err := jw.GetString()
if err != nil {
return nil, err
}
return ReadOneKeyFromString(s)
}
// XXX for now this is OK but probably we need a PGP uid parser
// as in pgp-utils
func (k *PGPKeyBundle) FindKeybaseUsername(un string) bool {
rxx := regexp.MustCompile("(?i)< " + un + "@keybase.io>$")
for _, id := range k.Identities {
if rxx.MatchString(id.Name) {
return true
}
}
return false
}
func (k PGPKeyBundle) VerboseDescription() string {
lines := k.UsersDescription()
lines = append(lines, k.KeyDescription())
return strings.Join(lines, "\n")
}
func (k PGPKeyBundle) HumanDescription() string {
user := k.GetPrimaryUID()
keyID := k.GetFingerprint().ToKeyID()
return fmt.Sprintf("PGP key %s %s", user, keyID)
}
func (k PGPKeyBundle) UsersDescription() []string {
id := k.GetPrimaryUID()
if len(id) == 0 {
return nil
}
return []string{"user: " + id}
}
// GetPrimaryUID gets the primary UID in the given key bundle, returned
// in the 'Max K (foo) <bar@baz.com>' convention.
func (k PGPKeyBundle) GetPrimaryUID() string {
var pri *openpgp.Identity
var s string
if len(k.Identities) == 0 {
return ""
}
var first *openpgp.Identity
for _, id := range k.Identities {
if first == nil {
first = id
}
if id.SelfSignature != nil && id.SelfSignature.IsPrimaryId != nil && *id.SelfSignature.IsPrimaryId {
pri = id
break
}
}
if pri == nil {
pri = first
}
if pri.UserId != nil {
s = pri.UserId.Id
} else {
s = pri.Name
}
return s
}
func (k *PGPKeyBundle) HasSecretKey() bool {
return k.PrivateKey != nil
}
func (k *PGPKeyBundle) CheckSecretKey() (err error) {
if k.PrivateKey == nil {
err = NoSecretKeyError{}
} else if k.PrivateKey.Encrypted {
err = BadKeyError{"PGP key material should be unencrypted"}
}
return
}
func (k *PGPKeyBundle) CanSign() bool {
return k.PrivateKey != nil && !k.PrivateKey.Encrypted
}
func (k *PGPKeyBundle) GetKID() keybase1.KID {
prefix := []byte{
byte(KeybaseKIDV1),
byte(k.PrimaryKey.PubKeyAlgo),
}
// XXX Hack; Because PublicKey.serializeWithoutHeaders is off-limits
// to us, we need to do a full serialize and then strip off the header.
// The further annoyance is that the size of the header varies with the
// bitlen of the key. Small keys (<191 bytes total) yield 8 bytes of header
// material --- for instance, 1024-bit test keys. For longer keys, we
// have 9 bytes of header material, to encode a 2-byte frame, rather than
// a 1-byte frame.
buf := bytes.Buffer{}
k.PrimaryKey.Serialize(&buf)
byts := buf.Bytes()
hdrBytes := 8
if len(byts) >= 193 {
hdrBytes++
}
sum := sha256.Sum256(buf.Bytes()[hdrBytes:])
out := append(prefix, sum[:]...)
out = append(out, byte(IDSuffixKID))
return keybase1.KIDFromSlice(out)
}
func (k PGPKeyBundle) GetAlgoType() AlgoType {
return AlgoType(k.PrimaryKey.PubKeyAlgo)
}
func (k PGPKeyBundle) KeyDescription() string {
algo, kid, creation := k.KeyInfo()
return fmt.Sprintf("%s, ID %s, created %s", algo, kid, creation)
}
func (k PGPKeyBundle) KeyInfo() (algorithm, kid, creation string) {
pubkey := k.PrimaryKey
var typ string
switch pubkey.PubKeyAlgo {
case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoRSASignOnly:
typ = "RSA"
case packet.PubKeyAlgoDSA:
typ = "DSA"
case packet.PubKeyAlgoECDSA:
typ = "ECDSA"
default:
typ = "<UNKONWN TYPE>"
}
bl, err := pubkey.BitLength()
if err != nil {
bl = 0
}
algorithm = fmt.Sprintf("%d-bit %s key", bl, typ)
kid = pubkey.KeyIdString()
creation = pubkey.CreationTime.Format("2006-01-02")
return
}
func unlockPrivateKey(k *packet.PrivateKey, pw string) error {
if !k.Encrypted {
return nil
}
err := k.Decrypt([]byte(pw))
if err != nil && strings.HasSuffix(err.Error(), "private key checksum failure") {
// XXX this is gross, the openpgp library should return a better
// error if the PW was incorrectly specified
err = PassphraseError{}
}
return err
}
func (k *PGPKeyBundle) unlockAllPrivateKeys(pw string) error {
if err := unlockPrivateKey(k.PrivateKey, pw); err != nil {
return err
}
for _, subkey := range k.Subkeys {
if err := unlockPrivateKey(subkey.PrivateKey, pw); err != nil {
return err
}
}
return nil
}
func (k *PGPKeyBundle) Unlock(reason string, secretUI SecretUI) error {
unlocker := func(pw string, _ bool) (ret GenericKey, err error) {
if err = k.unlockAllPrivateKeys(pw); err != nil {
return nil, err
}
return k, nil
}
_, err := KeyUnlocker{
Tries: 5,
Reason: reason,
KeyDesc: k.VerboseDescription(),
Unlocker: unlocker,
UI: secretUI,
}.Run()
return err
}
func (k *PGPKeyBundle) CheckFingerprint(fp *PGPFingerprint) error {
if k == nil {
return UnexpectedKeyError{}
}
if fp == nil {
return UnexpectedKeyError{}
}
fp2 := k.GetFingerprint()
if !fp2.Eq(*fp) {
return BadFingerprintError{fp2, *fp}
}
return nil
}
func (k *PGPKeyBundle) SignToString(msg []byte) (sig string, id keybase1.SigID, err error) {
return SimpleSign(msg, *k)
}
func (k PGPKeyBundle) VerifyStringAndExtract(sig string) (msg []byte, id keybase1.SigID, err error) {
var ps *ParsedSig
if ps, err = PGPOpenSig(sig); err != nil {
return
} else if err = ps.Verify(k); err != nil {
return
}
msg = ps.LiteralData
id = ps.ID()
return
}
func (k PGPKeyBundle) VerifyString(sig string, msg []byte) (id keybase1.SigID, err error) {
extractedMsg, resID, err := k.VerifyStringAndExtract(sig)
if err != nil {
return
}
if !FastByteArrayEq(extractedMsg, msg) {
err = BadSigError{"wrong payload"}
return
}
id = resID
return
}
func IsPGPAlgo(algo AlgoType) bool {
switch algo {
case KIDPGPRsa, KIDPGPElgamal, KIDPGPDsa, KIDPGPEcdh, KIDPGPEcdsa, KIDPGPBase:
return true
}
return false
}
func (k *PGPKeyBundle) FindEmail(em string) bool {
for _, ident := range k.Identities {
if i, e := ParseIdentity(ident.Name); e == nil && i.Email == em {
return true
}
}
return false
}
func (k *PGPKeyBundle) IdentityNames() []string {
var names []string
for _, ident := range k.Identities {
names = append(names, ident.Name)
}
return names
}
func (k *PGPKeyBundle) GetPGPIdentities() []keybase1.PGPIdentity {
ret := make([]keybase1.PGPIdentity, len(k.Identities))
for _, pgpIdentity := range k.Identities {
ret = append(ret, ExportPGPIdentity(pgpIdentity))
}
return ret
}
func (k *PGPKeyBundle) CheckIdentity(kbid Identity) (match bool, ctime int64, etime int64) {
ctime, etime = -1, -1
for _, pgpIdentity := range k.Identities {
if Cicmp(pgpIdentity.UserId.Email, kbid.Email) {
match = true
ctime = pgpIdentity.SelfSignature.CreationTime.Unix()
// This is a special case in OpenPGP, so we used KeyLifetimeSecs
lifeSeconds := pgpIdentity.SelfSignature.KeyLifetimeSecs
if lifeSeconds == nil {
// No expiration time is OK, it just means it never expires.
etime = 0
} else {
etime = ctime + int64(*lifeSeconds)
}
break
}
}
return
}
// EncryptToString fails for this type of key, since we haven't implemented it yet
func (k *PGPKeyBundle) EncryptToString(plaintext []byte, sender GenericKey) (ciphertext string, err error) {
err = KeyCannotEncryptError{}
return
}
// DecryptFromString fails for this type of key, since we haven't implemented it yet
func (k *PGPKeyBundle) DecryptFromString(ciphertext string) (msg []byte, sender keybase1.KID, err error) {
err = KeyCannotDecryptError{}
return
}
// CanEncrypt returns false for now, since we haven't implemented PGP encryption of packets
// for metadata operations
func (k *PGPKeyBundle) CanEncrypt() bool { return false }
// CanDecrypt returns false for now, since we haven't implemented PGP encryption of packets
// for metadata operations
func (k *PGPKeyBundle) CanDecrypt() bool { return false }
//===================================================
// Fulfill the TrackIdComponent interface
func (p PGPFingerprint) ToIDString() string {
return p.String()
}
func (p PGPFingerprint) ToKeyValuePair() (string, string) {
return "fingerprint", p.ToIDString()
}
func (p PGPFingerprint) GetProofState() keybase1.ProofState {
return keybase1.ProofState_OK
}
func (p PGPFingerprint) LastWriterWins() bool {
return false
}
//===================================================