You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

read.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package openpgp implements high level operations on OpenPGP messages.
  5. package openpgp // import "github.com/keybase/go-crypto/openpgp"
  6. import (
  7. "crypto"
  8. "crypto/hmac"
  9. _ "crypto/sha256"
  10. "hash"
  11. "io"
  12. "strconv"
  13. "github.com/keybase/go-crypto/openpgp/armor"
  14. "github.com/keybase/go-crypto/openpgp/errors"
  15. "github.com/keybase/go-crypto/openpgp/packet"
  16. )
  17. // SignatureType is the armor type for a PGP signature.
  18. var SignatureType = "PGP SIGNATURE"
  19. // readArmored reads an armored block with the given type.
  20. func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) {
  21. block, err := armor.Decode(r)
  22. if err != nil {
  23. return
  24. }
  25. if block.Type != expectedType {
  26. return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type)
  27. }
  28. return block.Body, nil
  29. }
  30. // MessageDetails contains the result of parsing an OpenPGP encrypted and/or
  31. // signed message.
  32. type MessageDetails struct {
  33. IsEncrypted bool // true if the message was encrypted.
  34. EncryptedToKeyIds []uint64 // the list of recipient key ids.
  35. IsSymmetricallyEncrypted bool // true if a passphrase could have decrypted the message.
  36. DecryptedWith Key // the private key used to decrypt the message, if any.
  37. IsSigned bool // true if the message is signed.
  38. SignedByKeyId uint64 // the key id of the signer, if any.
  39. SignedBy *Key // the key of the signer, if available.
  40. LiteralData *packet.LiteralData // the metadata of the contents
  41. UnverifiedBody io.Reader // the contents of the message.
  42. // If IsSigned is true and SignedBy is non-zero then the signature will
  43. // be verified as UnverifiedBody is read. The signature cannot be
  44. // checked until the whole of UnverifiedBody is read so UnverifiedBody
  45. // must be consumed until EOF before the data can trusted. Even if a
  46. // message isn't signed (or the signer is unknown) the data may contain
  47. // an authentication code that is only checked once UnverifiedBody has
  48. // been consumed. Once EOF has been seen, the following fields are
  49. // valid. (An authentication code failure is reported as a
  50. // SignatureError error when reading from UnverifiedBody.)
  51. SignatureError error // nil if the signature is good.
  52. Signature *packet.Signature // the signature packet itself, if v4 (default)
  53. SignatureV3 *packet.SignatureV3 // the signature packet if it is a v2 or v3 signature
  54. // Does the Message include multiple signatures? Also called "nested signatures".
  55. MultiSig bool
  56. decrypted io.ReadCloser
  57. }
  58. // A PromptFunction is used as a callback by functions that may need to decrypt
  59. // a private key, or prompt for a passphrase. It is called with a list of
  60. // acceptable, encrypted private keys and a boolean that indicates whether a
  61. // passphrase is usable. It should either decrypt a private key or return a
  62. // passphrase to try. If the decrypted private key or given passphrase isn't
  63. // correct, the function will be called again, forever. Any error returned will
  64. // be passed up.
  65. type PromptFunction func(keys []Key, symmetric bool) ([]byte, error)
  66. // A keyEnvelopePair is used to store a private key with the envelope that
  67. // contains a symmetric key, encrypted with that key.
  68. type keyEnvelopePair struct {
  69. key Key
  70. encryptedKey *packet.EncryptedKey
  71. }
  72. // ReadMessage parses an OpenPGP message that may be signed and/or encrypted.
  73. // The given KeyRing should contain both public keys (for signature
  74. // verification) and, possibly encrypted, private keys for decrypting.
  75. // If config is nil, sensible defaults will be used.
  76. func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction, config *packet.Config) (md *MessageDetails, err error) {
  77. var p packet.Packet
  78. var symKeys []*packet.SymmetricKeyEncrypted
  79. var pubKeys []keyEnvelopePair
  80. var se *packet.SymmetricallyEncrypted
  81. packets := packet.NewReader(r)
  82. md = new(MessageDetails)
  83. md.IsEncrypted = true
  84. // The message, if encrypted, starts with a number of packets
  85. // containing an encrypted decryption key. The decryption key is either
  86. // encrypted to a public key, or with a passphrase. This loop
  87. // collects these packets.
  88. ParsePackets:
  89. for {
  90. p, err = packets.Next()
  91. if err != nil {
  92. return nil, err
  93. }
  94. switch p := p.(type) {
  95. case *packet.SymmetricKeyEncrypted:
  96. // This packet contains the decryption key encrypted with a passphrase.
  97. md.IsSymmetricallyEncrypted = true
  98. symKeys = append(symKeys, p)
  99. case *packet.EncryptedKey:
  100. // This packet contains the decryption key encrypted to a public key.
  101. md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId)
  102. switch p.Algo {
  103. case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoElGamal, packet.PubKeyAlgoECDH:
  104. break
  105. default:
  106. continue
  107. }
  108. var keys []Key
  109. if p.KeyId == 0 {
  110. keys = keyring.DecryptionKeys()
  111. } else {
  112. keys = keyring.KeysById(p.KeyId, nil)
  113. }
  114. for _, k := range keys {
  115. pubKeys = append(pubKeys, keyEnvelopePair{k, p})
  116. }
  117. case *packet.SymmetricallyEncrypted:
  118. se = p
  119. break ParsePackets
  120. case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature:
  121. // This message isn't encrypted.
  122. if len(symKeys) != 0 || len(pubKeys) != 0 {
  123. return nil, errors.StructuralError("key material not followed by encrypted message")
  124. }
  125. packets.Unread(p)
  126. return readSignedMessage(packets, nil, keyring)
  127. }
  128. }
  129. var candidates []Key
  130. var decrypted io.ReadCloser
  131. // Now that we have the list of encrypted keys we need to decrypt at
  132. // least one of them or, if we cannot, we need to call the prompt
  133. // function so that it can decrypt a key or give us a passphrase.
  134. FindKey:
  135. for {
  136. // See if any of the keys already have a private key available
  137. candidates = candidates[:0]
  138. candidateFingerprints := make(map[string]bool)
  139. for _, pk := range pubKeys {
  140. if pk.key.PrivateKey == nil {
  141. continue
  142. }
  143. if !pk.key.PrivateKey.Encrypted {
  144. if pk.key.PrivateKey.PrivateKey == nil {
  145. // Key is stubbed
  146. continue
  147. }
  148. if len(pk.encryptedKey.Key) == 0 {
  149. err := pk.encryptedKey.Decrypt(pk.key.PrivateKey, config)
  150. if err != nil {
  151. continue
  152. }
  153. }
  154. if len(pk.encryptedKey.Key) == 0 {
  155. continue
  156. }
  157. decrypted, err = se.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key)
  158. if err != nil && err != errors.ErrKeyIncorrect {
  159. return nil, err
  160. }
  161. if decrypted != nil {
  162. md.DecryptedWith = pk.key
  163. break FindKey
  164. }
  165. } else {
  166. fpr := string(pk.key.PublicKey.Fingerprint[:])
  167. if v := candidateFingerprints[fpr]; v {
  168. continue
  169. }
  170. candidates = append(candidates, pk.key)
  171. candidateFingerprints[fpr] = true
  172. }
  173. }
  174. if len(candidates) == 0 && len(symKeys) == 0 {
  175. return nil, errors.ErrKeyIncorrect
  176. }
  177. if prompt == nil {
  178. return nil, errors.ErrKeyIncorrect
  179. }
  180. passphrase, err := prompt(candidates, len(symKeys) != 0)
  181. if err != nil {
  182. return nil, err
  183. }
  184. // Try the symmetric passphrase first
  185. if len(symKeys) != 0 && passphrase != nil {
  186. for _, s := range symKeys {
  187. key, cipherFunc, err := s.Decrypt(passphrase)
  188. if err == nil {
  189. decrypted, err = se.Decrypt(cipherFunc, key)
  190. if err != nil && err != errors.ErrKeyIncorrect {
  191. return nil, err
  192. }
  193. if decrypted != nil {
  194. break FindKey
  195. }
  196. }
  197. }
  198. }
  199. }
  200. md.decrypted = decrypted
  201. if err := packets.Push(decrypted); err != nil {
  202. return nil, err
  203. }
  204. return readSignedMessage(packets, md, keyring)
  205. }
  206. // readSignedMessage reads a possibly signed message if mdin is non-zero then
  207. // that structure is updated and returned. Otherwise a fresh MessageDetails is
  208. // used.
  209. func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err error) {
  210. if mdin == nil {
  211. mdin = new(MessageDetails)
  212. }
  213. md = mdin
  214. var p packet.Packet
  215. var h hash.Hash
  216. var wrappedHash hash.Hash
  217. FindLiteralData:
  218. for {
  219. p, err = packets.Next()
  220. if err != nil {
  221. return nil, err
  222. }
  223. switch p := p.(type) {
  224. case *packet.Compressed:
  225. if err := packets.Push(p.Body); err != nil {
  226. return nil, err
  227. }
  228. case *packet.OnePassSignature:
  229. if md.IsSigned {
  230. // If IsSigned is set, it means we have multiple
  231. // OnePassSignature packets.
  232. md.MultiSig = true
  233. if md.SignedBy != nil {
  234. // We've already found the signature we were looking
  235. // for, made by key that we had in keyring and can
  236. // check signature against. Continue with that instead
  237. // of trying to find another.
  238. continue FindLiteralData
  239. }
  240. }
  241. h, wrappedHash, err = hashForSignature(p.Hash, p.SigType)
  242. if err != nil {
  243. md = nil
  244. return
  245. }
  246. md.IsSigned = true
  247. md.SignedByKeyId = p.KeyId
  248. keys := keyring.KeysByIdUsage(p.KeyId, nil, packet.KeyFlagSign)
  249. if len(keys) > 0 {
  250. md.SignedBy = &keys[0]
  251. }
  252. case *packet.LiteralData:
  253. md.LiteralData = p
  254. break FindLiteralData
  255. }
  256. }
  257. if md.SignedBy != nil {
  258. md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md}
  259. } else if md.decrypted != nil {
  260. md.UnverifiedBody = checkReader{md}
  261. } else {
  262. md.UnverifiedBody = md.LiteralData.Body
  263. }
  264. return md, nil
  265. }
  266. // hashForSignature returns a pair of hashes that can be used to verify a
  267. // signature. The signature may specify that the contents of the signed message
  268. // should be preprocessed (i.e. to normalize line endings). Thus this function
  269. // returns two hashes. The second should be used to hash the message itself and
  270. // performs any needed preprocessing.
  271. func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) {
  272. if !hashId.Available() {
  273. return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId)))
  274. }
  275. h := hashId.New()
  276. switch sigType {
  277. case packet.SigTypeBinary:
  278. return h, h, nil
  279. case packet.SigTypeText:
  280. return h, NewCanonicalTextHash(h), nil
  281. }
  282. return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType)))
  283. }
  284. // checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF
  285. // it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger
  286. // MDC checks.
  287. type checkReader struct {
  288. md *MessageDetails
  289. }
  290. func (cr checkReader) Read(buf []byte) (n int, err error) {
  291. n, err = cr.md.LiteralData.Body.Read(buf)
  292. if err == io.EOF {
  293. mdcErr := cr.md.decrypted.Close()
  294. if mdcErr != nil {
  295. err = mdcErr
  296. }
  297. }
  298. return
  299. }
  300. // signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes
  301. // the data as it is read. When it sees an EOF from the underlying io.Reader
  302. // it parses and checks a trailing Signature packet and triggers any MDC checks.
  303. type signatureCheckReader struct {
  304. packets *packet.Reader
  305. h, wrappedHash hash.Hash
  306. md *MessageDetails
  307. }
  308. func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) {
  309. n, err = scr.md.LiteralData.Body.Read(buf)
  310. scr.wrappedHash.Write(buf[:n])
  311. if err == io.EOF {
  312. for {
  313. var p packet.Packet
  314. p, scr.md.SignatureError = scr.packets.Next()
  315. if scr.md.SignatureError != nil {
  316. if scr.md.MultiSig {
  317. // If we are in MultiSig, we might have found other
  318. // signature that cannot be verified using our key.
  319. // Clear Signature field so it's clear for consumers
  320. // that this message failed to verify.
  321. scr.md.Signature = nil
  322. }
  323. return
  324. }
  325. var ok bool
  326. if scr.md.Signature, ok = p.(*packet.Signature); ok {
  327. var err error
  328. if keyID := scr.md.Signature.IssuerKeyId; keyID != nil {
  329. if *keyID != scr.md.SignedBy.PublicKey.KeyId {
  330. if scr.md.MultiSig {
  331. continue // try again to find a sig we can verify
  332. }
  333. err = errors.StructuralError("bad key id")
  334. }
  335. }
  336. if fingerprint := scr.md.Signature.IssuerFingerprint; fingerprint != nil {
  337. if !hmac.Equal(fingerprint, scr.md.SignedBy.PublicKey.Fingerprint[:]) {
  338. if scr.md.MultiSig {
  339. continue // try again to find a sig we can verify
  340. }
  341. err = errors.StructuralError("bad key fingerprint")
  342. }
  343. }
  344. if err == nil {
  345. err = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature)
  346. }
  347. scr.md.SignatureError = err
  348. } else if scr.md.SignatureV3, ok = p.(*packet.SignatureV3); ok {
  349. scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignatureV3(scr.h, scr.md.SignatureV3)
  350. } else {
  351. scr.md.SignatureError = errors.StructuralError("LiteralData not followed by Signature")
  352. return
  353. }
  354. // Parse only one packet by default, unless message is MultiSig. Then
  355. // we ask for more packets after discovering non-matching signature,
  356. // until we find one that we can verify.
  357. break
  358. }
  359. // The SymmetricallyEncrypted packet, if any, might have an
  360. // unsigned hash of its own. In order to check this we need to
  361. // close that Reader.
  362. if scr.md.decrypted != nil {
  363. mdcErr := scr.md.decrypted.Close()
  364. if mdcErr != nil {
  365. err = mdcErr
  366. }
  367. }
  368. }
  369. return
  370. }
  371. // CheckDetachedSignature takes a signed file and a detached signature and
  372. // returns the signer if the signature is valid. If the signer isn't known,
  373. // ErrUnknownIssuer is returned.
  374. func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) {
  375. signer, _, err = checkDetachedSignature(keyring, signed, signature)
  376. return signer, err
  377. }
  378. func checkDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, issuer *uint64, err error) {
  379. var issuerKeyId uint64
  380. var issuerFingerprint []byte
  381. var hashFunc crypto.Hash
  382. var sigType packet.SignatureType
  383. var keys []Key
  384. var p packet.Packet
  385. packets := packet.NewReader(signature)
  386. for {
  387. p, err = packets.Next()
  388. if err == io.EOF {
  389. return nil, nil, errors.ErrUnknownIssuer
  390. }
  391. if err != nil {
  392. return nil, nil, err
  393. }
  394. switch sig := p.(type) {
  395. case *packet.Signature:
  396. if sig.IssuerKeyId == nil {
  397. return nil, nil, errors.StructuralError("signature doesn't have an issuer")
  398. }
  399. issuerKeyId = *sig.IssuerKeyId
  400. hashFunc = sig.Hash
  401. sigType = sig.SigType
  402. issuerFingerprint = sig.IssuerFingerprint
  403. case *packet.SignatureV3:
  404. issuerKeyId = sig.IssuerKeyId
  405. hashFunc = sig.Hash
  406. sigType = sig.SigType
  407. default:
  408. return nil, nil, errors.StructuralError("non signature packet found")
  409. }
  410. keys = keyring.KeysByIdUsage(issuerKeyId, issuerFingerprint, packet.KeyFlagSign)
  411. if len(keys) > 0 {
  412. break
  413. }
  414. }
  415. if len(keys) == 0 {
  416. panic("unreachable")
  417. }
  418. h, wrappedHash, err := hashForSignature(hashFunc, sigType)
  419. if err != nil {
  420. return nil, nil, err
  421. }
  422. if _, err := io.Copy(wrappedHash, signed); err != nil && err != io.EOF {
  423. return nil, nil, err
  424. }
  425. for _, key := range keys {
  426. switch sig := p.(type) {
  427. case *packet.Signature:
  428. err = key.PublicKey.VerifySignature(h, sig)
  429. case *packet.SignatureV3:
  430. err = key.PublicKey.VerifySignatureV3(h, sig)
  431. default:
  432. panic("unreachable")
  433. }
  434. if err == nil {
  435. return key.Entity, &issuerKeyId, nil
  436. }
  437. }
  438. return nil, nil, err
  439. }
  440. // CheckArmoredDetachedSignature performs the same actions as
  441. // CheckDetachedSignature but expects the signature to be armored.
  442. func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) {
  443. signer, _, err = checkArmoredDetachedSignature(keyring, signed, signature)
  444. return signer, err
  445. }
  446. func checkArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, issuer *uint64, err error) {
  447. body, err := readArmored(signature, SignatureType)
  448. if err != nil {
  449. return
  450. }
  451. return checkDetachedSignature(keyring, signed, body)
  452. }