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.
 
 
 

443 lines
13 KiB

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