本站源代码
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.

464 lines
14KB

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