read.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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
  6. import (
  7. "code.google.com/p/go.crypto/openpgp/armor"
  8. "code.google.com/p/go.crypto/openpgp/errors"
  9. "code.google.com/p/go.crypto/openpgp/packet"
  10. "crypto"
  11. _ "crypto/sha256"
  12. "hash"
  13. "io"
  14. "strconv"
  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. err = s.Decrypt(passphrase)
  177. if err == nil && !s.Encrypted {
  178. decrypted, err = se.Decrypt(s.CipherFunc, s.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. packets.Push(decrypted)
  191. return readSignedMessage(packets, md, keyring)
  192. }
  193. // readSignedMessage reads a possibly signed message if mdin is non-zero then
  194. // that structure is updated and returned. Otherwise a fresh MessageDetails is
  195. // used.
  196. func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err error) {
  197. if mdin == nil {
  198. mdin = new(MessageDetails)
  199. }
  200. md = mdin
  201. var p packet.Packet
  202. var h hash.Hash
  203. var wrappedHash hash.Hash
  204. FindLiteralData:
  205. for {
  206. p, err = packets.Next()
  207. if err != nil {
  208. return nil, err
  209. }
  210. switch p := p.(type) {
  211. case *packet.Compressed:
  212. packets.Push(p.Body)
  213. case *packet.OnePassSignature:
  214. if !p.IsLast {
  215. return nil, errors.UnsupportedError("nested signatures")
  216. }
  217. h, wrappedHash, err = hashForSignature(p.Hash, p.SigType)
  218. if err != nil {
  219. md = nil
  220. return
  221. }
  222. md.IsSigned = true
  223. md.SignedByKeyId = p.KeyId
  224. keys := keyring.KeysByIdUsage(p.KeyId, packet.KeyFlagSign)
  225. if len(keys) > 0 {
  226. md.SignedBy = &keys[0]
  227. }
  228. case *packet.LiteralData:
  229. md.LiteralData = p
  230. break FindLiteralData
  231. }
  232. }
  233. if md.SignedBy != nil {
  234. md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md}
  235. } else if md.decrypted != nil {
  236. md.UnverifiedBody = checkReader{md}
  237. } else {
  238. md.UnverifiedBody = md.LiteralData.Body
  239. }
  240. return md, nil
  241. }
  242. // hashForSignature returns a pair of hashes that can be used to verify a
  243. // signature. The signature may specify that the contents of the signed message
  244. // should be preprocessed (i.e. to normalize line endings). Thus this function
  245. // returns two hashes. The second should be used to hash the message itself and
  246. // performs any needed preprocessing.
  247. func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) {
  248. h := hashId.New()
  249. if h == nil {
  250. return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId)))
  251. }
  252. switch sigType {
  253. case packet.SigTypeBinary:
  254. return h, h, nil
  255. case packet.SigTypeText:
  256. return h, NewCanonicalTextHash(h), nil
  257. }
  258. return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType)))
  259. }
  260. // checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF
  261. // it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger
  262. // MDC checks.
  263. type checkReader struct {
  264. md *MessageDetails
  265. }
  266. func (cr checkReader) Read(buf []byte) (n int, err error) {
  267. n, err = cr.md.LiteralData.Body.Read(buf)
  268. if err == io.EOF {
  269. mdcErr := cr.md.decrypted.Close()
  270. if mdcErr != nil {
  271. err = mdcErr
  272. }
  273. }
  274. return
  275. }
  276. // signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes
  277. // the data as it is read. When it sees an EOF from the underlying io.Reader
  278. // it parses and checks a trailing Signature packet and triggers any MDC checks.
  279. type signatureCheckReader struct {
  280. packets *packet.Reader
  281. h, wrappedHash hash.Hash
  282. md *MessageDetails
  283. }
  284. func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) {
  285. n, err = scr.md.LiteralData.Body.Read(buf)
  286. scr.wrappedHash.Write(buf[:n])
  287. if err == io.EOF {
  288. var p packet.Packet
  289. p, scr.md.SignatureError = scr.packets.Next()
  290. if scr.md.SignatureError != nil {
  291. return
  292. }
  293. var ok bool
  294. if scr.md.Signature, ok = p.(*packet.Signature); !ok {
  295. scr.md.SignatureError = errors.StructuralError("LiteralData not followed by Signature")
  296. return
  297. }
  298. scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature)
  299. // The SymmetricallyEncrypted packet, if any, might have an
  300. // unsigned hash of its own. In order to check this we need to
  301. // close that Reader.
  302. if scr.md.decrypted != nil {
  303. mdcErr := scr.md.decrypted.Close()
  304. if mdcErr != nil {
  305. err = mdcErr
  306. }
  307. }
  308. }
  309. return
  310. }
  311. // CheckDetachedSignature takes a signed file and a detached signature and
  312. // returns the signer if the signature is valid. If the signer isn't known,
  313. // ErrUnknownIssuer is returned.
  314. func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) {
  315. p, err := packet.Read(signature)
  316. if err != nil {
  317. return
  318. }
  319. var issuerKeyId uint64
  320. var hashFunc crypto.Hash
  321. var sigType packet.SignatureType
  322. switch sig := p.(type) {
  323. case *packet.Signature:
  324. if sig.IssuerKeyId == nil {
  325. return nil, errors.StructuralError("signature doesn't have an issuer")
  326. }
  327. issuerKeyId = *sig.IssuerKeyId
  328. hashFunc = sig.Hash
  329. sigType = sig.SigType
  330. case *packet.SignatureV3:
  331. issuerKeyId = sig.IssuerKeyId
  332. hashFunc = sig.Hash
  333. sigType = sig.SigType
  334. default:
  335. return nil, errors.StructuralError("non signature packet found")
  336. }
  337. h, wrappedHash, err := hashForSignature(hashFunc, sigType)
  338. if err != nil {
  339. return
  340. }
  341. _, err = io.Copy(wrappedHash, signed)
  342. if err != nil && err != io.EOF {
  343. return
  344. }
  345. keys := keyring.KeysByIdUsage(issuerKeyId, packet.KeyFlagSign)
  346. if len(keys) == 0 {
  347. return nil, errors.ErrUnknownIssuer
  348. }
  349. for _, key := range keys {
  350. switch sig := p.(type) {
  351. case *packet.Signature:
  352. err = key.PublicKey.VerifySignature(h, sig)
  353. case *packet.SignatureV3:
  354. err = key.PublicKey.VerifySignatureV3(h, sig)
  355. }
  356. if err == nil {
  357. return key.Entity, nil
  358. }
  359. }
  360. return nil, errors.ErrUnknownIssuer
  361. }
  362. // CheckArmoredDetachedSignature performs the same actions as
  363. // CheckDetachedSignature but expects the signature to be armored.
  364. func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) {
  365. body, err := readArmored(signature, SignatureType)
  366. if err != nil {
  367. return
  368. }
  369. return CheckDetachedSignature(keyring, signed, body)
  370. }