read.go 13 KB

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