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.

880 lines
26 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 packet
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/dsa"
  9. "crypto/ecdsa"
  10. "encoding/binary"
  11. "hash"
  12. "io"
  13. "strconv"
  14. "time"
  15. "github.com/keybase/go-crypto/openpgp/errors"
  16. "github.com/keybase/go-crypto/openpgp/s2k"
  17. "github.com/keybase/go-crypto/rsa"
  18. )
  19. const (
  20. // See RFC 4880, section 5.2.3.21 for details.
  21. KeyFlagCertify = 1 << iota
  22. KeyFlagSign
  23. KeyFlagEncryptCommunications
  24. KeyFlagEncryptStorage
  25. )
  26. // Signer can be implemented by application code to do actual signing.
  27. type Signer interface {
  28. hash.Hash
  29. Sign(sig *Signature) error
  30. KeyId() uint64
  31. PublicKeyAlgo() PublicKeyAlgorithm
  32. }
  33. // RevocationKey represents designated revoker packet. See RFC 4880
  34. // section 5.2.3.15 for details.
  35. type RevocationKey struct {
  36. Class byte
  37. PublicKeyAlgo PublicKeyAlgorithm
  38. Fingerprint []byte
  39. }
  40. // KeyFlagBits holds boolean whether any usage flags were provided in
  41. // the signature and BitField with KeyFlag* flags.
  42. type KeyFlagBits struct {
  43. Valid bool
  44. BitField byte
  45. }
  46. // Signature represents a signature. See RFC 4880, section 5.2.
  47. type Signature struct {
  48. SigType SignatureType
  49. PubKeyAlgo PublicKeyAlgorithm
  50. Hash crypto.Hash
  51. // HashSuffix is extra data that is hashed in after the signed data.
  52. HashSuffix []byte
  53. // HashTag contains the first two bytes of the hash for fast rejection
  54. // of bad signed data.
  55. HashTag [2]byte
  56. CreationTime time.Time
  57. RSASignature parsedMPI
  58. DSASigR, DSASigS parsedMPI
  59. ECDSASigR, ECDSASigS parsedMPI
  60. EdDSASigR, EdDSASigS parsedMPI
  61. // rawSubpackets contains the unparsed subpackets, in order.
  62. rawSubpackets []outputSubpacket
  63. // The following are optional so are nil when not included in the
  64. // signature.
  65. SigLifetimeSecs, KeyLifetimeSecs *uint32
  66. PreferredSymmetric, PreferredHash, PreferredCompression []uint8
  67. PreferredKeyServer string
  68. IssuerKeyId *uint64
  69. IsPrimaryId *bool
  70. IssuerFingerprint []byte
  71. // FlagsValid is set if any flags were given. See RFC 4880, section
  72. // 5.2.3.21 for details.
  73. FlagsValid bool
  74. FlagCertify, FlagSign, FlagEncryptCommunications, FlagEncryptStorage bool
  75. // RevocationReason is set if this signature has been revoked.
  76. // See RFC 4880, section 5.2.3.23 for details.
  77. RevocationReason *uint8
  78. RevocationReasonText string
  79. // PolicyURI is optional. See RFC 4880, Section 5.2.3.20 for details
  80. PolicyURI string
  81. // Regex is a regex that can match a PGP UID. See RFC 4880, 5.2.3.14 for details
  82. Regex string
  83. // MDC is set if this signature has a feature packet that indicates
  84. // support for MDC subpackets.
  85. MDC bool
  86. // EmbeddedSignature, if non-nil, is a signature of the parent key, by
  87. // this key. This prevents an attacker from claiming another's signing
  88. // subkey as their own.
  89. EmbeddedSignature *Signature
  90. // StubbedOutCriticalError is not fail-stop, since it shouldn't break key parsing
  91. // when appearing in WoT-style cross signatures. But it should prevent a signature
  92. // from being applied to a primary or subkey.
  93. StubbedOutCriticalError error
  94. // DesignaterRevoker will be present if this signature certifies a
  95. // designated revoking key id (3rd party key that can sign
  96. // revocation for this key).
  97. DesignatedRevoker *RevocationKey
  98. outSubpackets []outputSubpacket
  99. }
  100. func (sig *Signature) parse(r io.Reader) (err error) {
  101. // RFC 4880, section 5.2.3
  102. var buf [5]byte
  103. _, err = readFull(r, buf[:1])
  104. if err != nil {
  105. return
  106. }
  107. if buf[0] != 4 {
  108. err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0])))
  109. return
  110. }
  111. _, err = readFull(r, buf[:5])
  112. if err != nil {
  113. return
  114. }
  115. sig.SigType = SignatureType(buf[0])
  116. sig.PubKeyAlgo = PublicKeyAlgorithm(buf[1])
  117. switch sig.PubKeyAlgo {
  118. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA, PubKeyAlgoEdDSA:
  119. default:
  120. err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo)))
  121. return
  122. }
  123. var ok bool
  124. sig.Hash, ok = s2k.HashIdToHash(buf[2])
  125. if !ok {
  126. return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2])))
  127. }
  128. hashedSubpacketsLength := int(buf[3])<<8 | int(buf[4])
  129. l := 6 + hashedSubpacketsLength
  130. sig.HashSuffix = make([]byte, l+6)
  131. sig.HashSuffix[0] = 4
  132. copy(sig.HashSuffix[1:], buf[:5])
  133. hashedSubpackets := sig.HashSuffix[6:l]
  134. _, err = readFull(r, hashedSubpackets)
  135. if err != nil {
  136. return
  137. }
  138. // See RFC 4880, section 5.2.4
  139. trailer := sig.HashSuffix[l:]
  140. trailer[0] = 4
  141. trailer[1] = 0xff
  142. trailer[2] = uint8(l >> 24)
  143. trailer[3] = uint8(l >> 16)
  144. trailer[4] = uint8(l >> 8)
  145. trailer[5] = uint8(l)
  146. err = parseSignatureSubpackets(sig, hashedSubpackets, true)
  147. if err != nil {
  148. return
  149. }
  150. _, err = readFull(r, buf[:2])
  151. if err != nil {
  152. return
  153. }
  154. unhashedSubpacketsLength := int(buf[0])<<8 | int(buf[1])
  155. unhashedSubpackets := make([]byte, unhashedSubpacketsLength)
  156. _, err = readFull(r, unhashedSubpackets)
  157. if err != nil {
  158. return
  159. }
  160. err = parseSignatureSubpackets(sig, unhashedSubpackets, false)
  161. if err != nil {
  162. return
  163. }
  164. _, err = readFull(r, sig.HashTag[:2])
  165. if err != nil {
  166. return
  167. }
  168. switch sig.PubKeyAlgo {
  169. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  170. sig.RSASignature.bytes, sig.RSASignature.bitLength, err = readMPI(r)
  171. case PubKeyAlgoDSA:
  172. sig.DSASigR.bytes, sig.DSASigR.bitLength, err = readMPI(r)
  173. if err == nil {
  174. sig.DSASigS.bytes, sig.DSASigS.bitLength, err = readMPI(r)
  175. }
  176. case PubKeyAlgoEdDSA:
  177. sig.EdDSASigR.bytes, sig.EdDSASigR.bitLength, err = readMPI(r)
  178. if err == nil {
  179. sig.EdDSASigS.bytes, sig.EdDSASigS.bitLength, err = readMPI(r)
  180. }
  181. case PubKeyAlgoECDSA:
  182. sig.ECDSASigR.bytes, sig.ECDSASigR.bitLength, err = readMPI(r)
  183. if err == nil {
  184. sig.ECDSASigS.bytes, sig.ECDSASigS.bitLength, err = readMPI(r)
  185. }
  186. default:
  187. panic("unreachable")
  188. }
  189. return
  190. }
  191. // parseSignatureSubpackets parses subpackets of the main signature packet. See
  192. // RFC 4880, section 5.2.3.1.
  193. func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) {
  194. for len(subpackets) > 0 {
  195. subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed)
  196. if err != nil {
  197. return
  198. }
  199. }
  200. if sig.CreationTime.IsZero() {
  201. err = errors.StructuralError("no creation time in signature")
  202. }
  203. return
  204. }
  205. type signatureSubpacketType uint8
  206. const (
  207. creationTimeSubpacket signatureSubpacketType = 2
  208. signatureExpirationSubpacket signatureSubpacketType = 3
  209. regularExpressionSubpacket signatureSubpacketType = 6
  210. keyExpirationSubpacket signatureSubpacketType = 9
  211. prefSymmetricAlgosSubpacket signatureSubpacketType = 11
  212. revocationKey signatureSubpacketType = 12
  213. issuerSubpacket signatureSubpacketType = 16
  214. prefHashAlgosSubpacket signatureSubpacketType = 21
  215. prefCompressionSubpacket signatureSubpacketType = 22
  216. prefKeyServerSubpacket signatureSubpacketType = 24
  217. primaryUserIdSubpacket signatureSubpacketType = 25
  218. policyURISubpacket signatureSubpacketType = 26
  219. keyFlagsSubpacket signatureSubpacketType = 27
  220. reasonForRevocationSubpacket signatureSubpacketType = 29
  221. featuresSubpacket signatureSubpacketType = 30
  222. embeddedSignatureSubpacket signatureSubpacketType = 32
  223. issuerFingerprint signatureSubpacketType = 33
  224. )
  225. // parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1.
  226. func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) {
  227. // RFC 4880, section 5.2.3.1
  228. var (
  229. length uint32
  230. packetType signatureSubpacketType
  231. isCritical bool
  232. )
  233. switch {
  234. case subpacket[0] < 192:
  235. length = uint32(subpacket[0])
  236. subpacket = subpacket[1:]
  237. case subpacket[0] < 255:
  238. if len(subpacket) < 2 {
  239. goto Truncated
  240. }
  241. length = uint32(subpacket[0]-192)<<8 + uint32(subpacket[1]) + 192
  242. subpacket = subpacket[2:]
  243. default:
  244. if len(subpacket) < 5 {
  245. goto Truncated
  246. }
  247. length = uint32(subpacket[1])<<24 |
  248. uint32(subpacket[2])<<16 |
  249. uint32(subpacket[3])<<8 |
  250. uint32(subpacket[4])
  251. subpacket = subpacket[5:]
  252. }
  253. if length > uint32(len(subpacket)) {
  254. goto Truncated
  255. }
  256. rest = subpacket[length:]
  257. subpacket = subpacket[:length]
  258. if len(subpacket) == 0 {
  259. err = errors.StructuralError("zero length signature subpacket")
  260. return
  261. }
  262. packetType = signatureSubpacketType(subpacket[0] & 0x7f)
  263. isCritical = subpacket[0]&0x80 == 0x80
  264. subpacket = subpacket[1:]
  265. sig.rawSubpackets = append(sig.rawSubpackets, outputSubpacket{isHashed, packetType, isCritical, subpacket})
  266. switch packetType {
  267. case creationTimeSubpacket:
  268. if !isHashed {
  269. err = errors.StructuralError("signature creation time in non-hashed area")
  270. return
  271. }
  272. if len(subpacket) != 4 {
  273. err = errors.StructuralError("signature creation time not four bytes")
  274. return
  275. }
  276. t := binary.BigEndian.Uint32(subpacket)
  277. sig.CreationTime = time.Unix(int64(t), 0)
  278. case signatureExpirationSubpacket:
  279. // Signature expiration time, section 5.2.3.10
  280. if !isHashed {
  281. return
  282. }
  283. if len(subpacket) != 4 {
  284. err = errors.StructuralError("expiration subpacket with bad length")
  285. return
  286. }
  287. sig.SigLifetimeSecs = new(uint32)
  288. *sig.SigLifetimeSecs = binary.BigEndian.Uint32(subpacket)
  289. case keyExpirationSubpacket:
  290. // Key expiration time, section 5.2.3.6
  291. if !isHashed {
  292. return
  293. }
  294. if len(subpacket) != 4 {
  295. err = errors.StructuralError("key expiration subpacket with bad length")
  296. return
  297. }
  298. sig.KeyLifetimeSecs = new(uint32)
  299. *sig.KeyLifetimeSecs = binary.BigEndian.Uint32(subpacket)
  300. case prefSymmetricAlgosSubpacket:
  301. // Preferred symmetric algorithms, section 5.2.3.7
  302. if !isHashed {
  303. return
  304. }
  305. sig.PreferredSymmetric = make([]byte, len(subpacket))
  306. copy(sig.PreferredSymmetric, subpacket)
  307. case issuerSubpacket:
  308. // Issuer, section 5.2.3.5
  309. if len(subpacket) != 8 {
  310. err = errors.StructuralError("issuer subpacket with bad length")
  311. return
  312. }
  313. sig.IssuerKeyId = new(uint64)
  314. *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket)
  315. case prefHashAlgosSubpacket:
  316. // Preferred hash algorithms, section 5.2.3.8
  317. if !isHashed {
  318. return
  319. }
  320. sig.PreferredHash = make([]byte, len(subpacket))
  321. copy(sig.PreferredHash, subpacket)
  322. case prefCompressionSubpacket:
  323. // Preferred compression algorithms, section 5.2.3.9
  324. if !isHashed {
  325. return
  326. }
  327. sig.PreferredCompression = make([]byte, len(subpacket))
  328. copy(sig.PreferredCompression, subpacket)
  329. case primaryUserIdSubpacket:
  330. // Primary User ID, section 5.2.3.19
  331. if !isHashed {
  332. return
  333. }
  334. if len(subpacket) != 1 {
  335. err = errors.StructuralError("primary user id subpacket with bad length")
  336. return
  337. }
  338. sig.IsPrimaryId = new(bool)
  339. if subpacket[0] > 0 {
  340. *sig.IsPrimaryId = true
  341. }
  342. case keyFlagsSubpacket:
  343. // Key flags, section 5.2.3.21
  344. if !isHashed {
  345. return
  346. }
  347. if len(subpacket) == 0 {
  348. err = errors.StructuralError("empty key flags subpacket")
  349. return
  350. }
  351. sig.FlagsValid = true
  352. if subpacket[0]&KeyFlagCertify != 0 {
  353. sig.FlagCertify = true
  354. }
  355. if subpacket[0]&KeyFlagSign != 0 {
  356. sig.FlagSign = true
  357. }
  358. if subpacket[0]&KeyFlagEncryptCommunications != 0 {
  359. sig.FlagEncryptCommunications = true
  360. }
  361. if subpacket[0]&KeyFlagEncryptStorage != 0 {
  362. sig.FlagEncryptStorage = true
  363. }
  364. case reasonForRevocationSubpacket:
  365. // Reason For Revocation, section 5.2.3.23
  366. if !isHashed {
  367. return
  368. }
  369. if len(subpacket) == 0 {
  370. err = errors.StructuralError("empty revocation reason subpacket")
  371. return
  372. }
  373. sig.RevocationReason = new(uint8)
  374. *sig.RevocationReason = subpacket[0]
  375. sig.RevocationReasonText = string(subpacket[1:])
  376. case featuresSubpacket:
  377. // Features subpacket, section 5.2.3.24 specifies a very general
  378. // mechanism for OpenPGP implementations to signal support for new
  379. // features. In practice, the subpacket is used exclusively to
  380. // indicate support for MDC-protected encryption.
  381. sig.MDC = len(subpacket) >= 1 && subpacket[0]&1 == 1
  382. case embeddedSignatureSubpacket:
  383. // Only usage is in signatures that cross-certify
  384. // signing subkeys. section 5.2.3.26 describes the
  385. // format, with its usage described in section 11.1
  386. if sig.EmbeddedSignature != nil {
  387. err = errors.StructuralError("Cannot have multiple embedded signatures")
  388. return
  389. }
  390. sig.EmbeddedSignature = new(Signature)
  391. // Embedded signatures are required to be v4 signatures see
  392. // section 12.1. However, we only parse v4 signatures in this
  393. // file anyway.
  394. if err := sig.EmbeddedSignature.parse(bytes.NewBuffer(subpacket)); err != nil {
  395. return nil, err
  396. }
  397. if sigType := sig.EmbeddedSignature.SigType; sigType != SigTypePrimaryKeyBinding {
  398. return nil, errors.StructuralError("cross-signature has unexpected type " + strconv.Itoa(int(sigType)))
  399. }
  400. case policyURISubpacket:
  401. // See RFC 4880, Section 5.2.3.20
  402. sig.PolicyURI = string(subpacket[:])
  403. case regularExpressionSubpacket:
  404. sig.Regex = string(subpacket[:])
  405. if isCritical {
  406. sig.StubbedOutCriticalError = errors.UnsupportedError("regex support is stubbed out")
  407. }
  408. case prefKeyServerSubpacket:
  409. sig.PreferredKeyServer = string(subpacket[:])
  410. case issuerFingerprint:
  411. // The first byte is how many bytes the fingerprint is, but we'll just
  412. // read until the end of the subpacket, so we'll ignore it.
  413. sig.IssuerFingerprint = append([]byte{}, subpacket[1:]...)
  414. case revocationKey:
  415. // Authorizes the specified key to issue revocation signatures
  416. // for a key.
  417. // TODO: Class octet must have bit 0x80 set. If the bit 0x40
  418. // is set, then this means that the revocation information is
  419. // sensitive.
  420. sig.DesignatedRevoker = &RevocationKey{
  421. Class: subpacket[0],
  422. PublicKeyAlgo: PublicKeyAlgorithm(subpacket[1]),
  423. Fingerprint: append([]byte{}, subpacket[2:]...),
  424. }
  425. default:
  426. if isCritical {
  427. err = errors.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType)))
  428. return
  429. }
  430. }
  431. return
  432. Truncated:
  433. err = errors.StructuralError("signature subpacket truncated")
  434. return
  435. }
  436. // subpacketLengthLength returns the length, in bytes, of an encoded length value.
  437. func subpacketLengthLength(length int) int {
  438. if length < 192 {
  439. return 1
  440. }
  441. if length < 16320 {
  442. return 2
  443. }
  444. return 5
  445. }
  446. // serializeSubpacketLength marshals the given length into to.
  447. func serializeSubpacketLength(to []byte, length int) int {
  448. // RFC 4880, Section 4.2.2.
  449. if length < 192 {
  450. to[0] = byte(length)
  451. return 1
  452. }
  453. if length < 16320 {
  454. length -= 192
  455. to[0] = byte((length >> 8) + 192)
  456. to[1] = byte(length)
  457. return 2
  458. }
  459. to[0] = 255
  460. to[1] = byte(length >> 24)
  461. to[2] = byte(length >> 16)
  462. to[3] = byte(length >> 8)
  463. to[4] = byte(length)
  464. return 5
  465. }
  466. // subpacketsLength returns the serialized length, in bytes, of the given
  467. // subpackets.
  468. func subpacketsLength(subpackets []outputSubpacket, hashed bool) (length int) {
  469. for _, subpacket := range subpackets {
  470. if subpacket.hashed == hashed {
  471. length += subpacketLengthLength(len(subpacket.contents) + 1)
  472. length += 1 // type byte
  473. length += len(subpacket.contents)
  474. }
  475. }
  476. return
  477. }
  478. // serializeSubpackets marshals the given subpackets into to.
  479. func serializeSubpackets(to []byte, subpackets []outputSubpacket, hashed bool) {
  480. for _, subpacket := range subpackets {
  481. if subpacket.hashed == hashed {
  482. n := serializeSubpacketLength(to, len(subpacket.contents)+1)
  483. to[n] = byte(subpacket.subpacketType)
  484. to = to[1+n:]
  485. n = copy(to, subpacket.contents)
  486. to = to[n:]
  487. }
  488. }
  489. return
  490. }
  491. // KeyExpired returns whether sig is a self-signature of a key that has
  492. // expired.
  493. func (sig *Signature) KeyExpired(currentTime time.Time) bool {
  494. if sig.KeyLifetimeSecs == nil {
  495. return false
  496. }
  497. expiry := sig.CreationTime.Add(time.Duration(*sig.KeyLifetimeSecs) * time.Second)
  498. return currentTime.After(expiry)
  499. }
  500. // ExpiresBeforeOther checks if other signature has expiration at
  501. // later date than sig.
  502. func (sig *Signature) ExpiresBeforeOther(other *Signature) bool {
  503. if sig.KeyLifetimeSecs == nil {
  504. // This sig never expires, or has infinitely long expiration
  505. // time.
  506. return false
  507. } else if other.KeyLifetimeSecs == nil {
  508. // This sig expires at some non-infinite point, but the other
  509. // sig never expires.
  510. return true
  511. }
  512. getExpiryDate := func(s *Signature) time.Time {
  513. return s.CreationTime.Add(time.Duration(*s.KeyLifetimeSecs) * time.Second)
  514. }
  515. return getExpiryDate(other).After(getExpiryDate(sig))
  516. }
  517. // buildHashSuffix constructs the HashSuffix member of sig in preparation for signing.
  518. func (sig *Signature) buildHashSuffix() (err error) {
  519. hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true)
  520. var ok bool
  521. l := 6 + hashedSubpacketsLen
  522. sig.HashSuffix = make([]byte, l+6)
  523. sig.HashSuffix[0] = 4
  524. sig.HashSuffix[1] = uint8(sig.SigType)
  525. sig.HashSuffix[2] = uint8(sig.PubKeyAlgo)
  526. sig.HashSuffix[3], ok = s2k.HashToHashId(sig.Hash)
  527. if !ok {
  528. sig.HashSuffix = nil
  529. return errors.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash)))
  530. }
  531. sig.HashSuffix[4] = byte(hashedSubpacketsLen >> 8)
  532. sig.HashSuffix[5] = byte(hashedSubpacketsLen)
  533. serializeSubpackets(sig.HashSuffix[6:l], sig.outSubpackets, true)
  534. trailer := sig.HashSuffix[l:]
  535. trailer[0] = 4
  536. trailer[1] = 0xff
  537. trailer[2] = byte(l >> 24)
  538. trailer[3] = byte(l >> 16)
  539. trailer[4] = byte(l >> 8)
  540. trailer[5] = byte(l)
  541. return
  542. }
  543. func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err error) {
  544. err = sig.buildHashSuffix()
  545. if err != nil {
  546. return
  547. }
  548. h.Write(sig.HashSuffix)
  549. digest = h.Sum(nil)
  550. copy(sig.HashTag[:], digest)
  551. return
  552. }
  553. // Sign signs a message with a private key. The hash, h, must contain
  554. // the hash of the message to be signed and will be mutated by this function.
  555. // On success, the signature is stored in sig. Call Serialize to write it out.
  556. // If config is nil, sensible defaults will be used.
  557. func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err error) {
  558. signer, hashIsSigner := h.(Signer)
  559. if !hashIsSigner && (priv == nil || priv.PrivateKey == nil) {
  560. err = errors.InvalidArgumentError("attempting to sign with nil PrivateKey")
  561. return
  562. }
  563. sig.outSubpackets = sig.buildSubpackets()
  564. digest, err := sig.signPrepareHash(h)
  565. if err != nil {
  566. return
  567. }
  568. if hashIsSigner {
  569. err = signer.Sign(sig)
  570. return
  571. }
  572. switch priv.PubKeyAlgo {
  573. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  574. sig.RSASignature.bytes, err = rsa.SignPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), sig.Hash, digest)
  575. sig.RSASignature.bitLength = uint16(8 * len(sig.RSASignature.bytes))
  576. case PubKeyAlgoDSA:
  577. dsaPriv := priv.PrivateKey.(*dsa.PrivateKey)
  578. // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
  579. subgroupSize := (dsaPriv.Q.BitLen() + 7) / 8
  580. if len(digest) > subgroupSize {
  581. digest = digest[:subgroupSize]
  582. }
  583. r, s, err := dsa.Sign(config.Random(), dsaPriv, digest)
  584. if err == nil {
  585. sig.DSASigR.bytes = r.Bytes()
  586. sig.DSASigR.bitLength = uint16(8 * len(sig.DSASigR.bytes))
  587. sig.DSASigS.bytes = s.Bytes()
  588. sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes))
  589. }
  590. case PubKeyAlgoECDSA:
  591. r, s, err := ecdsa.Sign(config.Random(), priv.PrivateKey.(*ecdsa.PrivateKey), digest)
  592. if err == nil {
  593. sig.ECDSASigR = FromBig(r)
  594. sig.ECDSASigS = FromBig(s)
  595. }
  596. case PubKeyAlgoEdDSA:
  597. r, s, err := priv.PrivateKey.(*EdDSAPrivateKey).Sign(digest)
  598. if err == nil {
  599. sig.EdDSASigR = FromBytes(r)
  600. sig.EdDSASigS = FromBytes(s)
  601. }
  602. default:
  603. err = errors.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo)))
  604. }
  605. return
  606. }
  607. // SignUserId computes a signature from priv, asserting that pub is a valid
  608. // key for the identity id. On success, the signature is stored in sig. Call
  609. // Serialize to write it out.
  610. // If config is nil, sensible defaults will be used.
  611. func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey, config *Config) error {
  612. h, err := userIdSignatureHash(id, pub, sig.Hash)
  613. if err != nil {
  614. return err
  615. }
  616. return sig.Sign(h, priv, config)
  617. }
  618. // SignUserIdWithSigner computes a signature from priv, asserting that pub is a
  619. // valid key for the identity id. On success, the signature is stored in sig.
  620. // Call Serialize to write it out.
  621. // If config is nil, sensible defaults will be used.
  622. func (sig *Signature) SignUserIdWithSigner(id string, pub *PublicKey, s Signer, config *Config) error {
  623. updateUserIdSignatureHash(id, pub, s)
  624. return sig.Sign(s, nil, config)
  625. }
  626. // SignKey computes a signature from priv, asserting that pub is a subkey. On
  627. // success, the signature is stored in sig. Call Serialize to write it out.
  628. // If config is nil, sensible defaults will be used.
  629. func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey, config *Config) error {
  630. h, err := keySignatureHash(&priv.PublicKey, pub, sig.Hash)
  631. if err != nil {
  632. return err
  633. }
  634. return sig.Sign(h, priv, config)
  635. }
  636. // SignKeyWithSigner computes a signature using s, asserting that
  637. // signeePubKey is a subkey. On success, the signature is stored in sig. Call
  638. // Serialize to write it out. If config is nil, sensible defaults will be used.
  639. func (sig *Signature) SignKeyWithSigner(signeePubKey *PublicKey, signerPubKey *PublicKey, s Signer, config *Config) error {
  640. updateKeySignatureHash(signerPubKey, signeePubKey, s)
  641. return sig.Sign(s, nil, config)
  642. }
  643. // Serialize marshals sig to w. Sign, SignUserId or SignKey must have been
  644. // called first.
  645. func (sig *Signature) Serialize(w io.Writer) (err error) {
  646. if len(sig.outSubpackets) == 0 {
  647. sig.outSubpackets = sig.rawSubpackets
  648. }
  649. if sig.RSASignature.bytes == nil &&
  650. sig.DSASigR.bytes == nil &&
  651. sig.ECDSASigR.bytes == nil &&
  652. sig.EdDSASigR.bytes == nil {
  653. return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize")
  654. }
  655. sigLength := 0
  656. switch sig.PubKeyAlgo {
  657. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  658. sigLength = 2 + len(sig.RSASignature.bytes)
  659. case PubKeyAlgoDSA:
  660. sigLength = 2 + len(sig.DSASigR.bytes)
  661. sigLength += 2 + len(sig.DSASigS.bytes)
  662. case PubKeyAlgoEdDSA:
  663. sigLength = 2 + len(sig.EdDSASigR.bytes)
  664. sigLength += 2 + len(sig.EdDSASigS.bytes)
  665. case PubKeyAlgoECDSA:
  666. sigLength = 2 + len(sig.ECDSASigR.bytes)
  667. sigLength += 2 + len(sig.ECDSASigS.bytes)
  668. default:
  669. panic("impossible")
  670. }
  671. unhashedSubpacketsLen := subpacketsLength(sig.outSubpackets, false)
  672. length := len(sig.HashSuffix) - 6 /* trailer not included */ +
  673. 2 /* length of unhashed subpackets */ + unhashedSubpacketsLen +
  674. 2 /* hash tag */ + sigLength
  675. err = serializeHeader(w, packetTypeSignature, length)
  676. if err != nil {
  677. return
  678. }
  679. _, err = w.Write(sig.HashSuffix[:len(sig.HashSuffix)-6])
  680. if err != nil {
  681. return
  682. }
  683. unhashedSubpackets := make([]byte, 2+unhashedSubpacketsLen)
  684. unhashedSubpackets[0] = byte(unhashedSubpacketsLen >> 8)
  685. unhashedSubpackets[1] = byte(unhashedSubpacketsLen)
  686. serializeSubpackets(unhashedSubpackets[2:], sig.outSubpackets, false)
  687. _, err = w.Write(unhashedSubpackets)
  688. if err != nil {
  689. return
  690. }
  691. _, err = w.Write(sig.HashTag[:])
  692. if err != nil {
  693. return
  694. }
  695. switch sig.PubKeyAlgo {
  696. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  697. err = writeMPIs(w, sig.RSASignature)
  698. case PubKeyAlgoDSA:
  699. err = writeMPIs(w, sig.DSASigR, sig.DSASigS)
  700. case PubKeyAlgoEdDSA:
  701. err = writeMPIs(w, sig.EdDSASigR, sig.EdDSASigS)
  702. case PubKeyAlgoECDSA:
  703. err = writeMPIs(w, sig.ECDSASigR, sig.ECDSASigS)
  704. default:
  705. panic("impossible")
  706. }
  707. return
  708. }
  709. // outputSubpacket represents a subpacket to be marshaled.
  710. type outputSubpacket struct {
  711. hashed bool // true if this subpacket is in the hashed area.
  712. subpacketType signatureSubpacketType
  713. isCritical bool
  714. contents []byte
  715. }
  716. func (sig *Signature) buildSubpackets() (subpackets []outputSubpacket) {
  717. creationTime := make([]byte, 4)
  718. binary.BigEndian.PutUint32(creationTime, uint32(sig.CreationTime.Unix()))
  719. subpackets = append(subpackets, outputSubpacket{true, creationTimeSubpacket, false, creationTime})
  720. if sig.IssuerKeyId != nil {
  721. keyId := make([]byte, 8)
  722. binary.BigEndian.PutUint64(keyId, *sig.IssuerKeyId)
  723. subpackets = append(subpackets, outputSubpacket{true, issuerSubpacket, false, keyId})
  724. }
  725. if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
  726. sigLifetime := make([]byte, 4)
  727. binary.BigEndian.PutUint32(sigLifetime, *sig.SigLifetimeSecs)
  728. subpackets = append(subpackets, outputSubpacket{true, signatureExpirationSubpacket, true, sigLifetime})
  729. }
  730. // Key flags may only appear in self-signatures or certification signatures.
  731. if sig.FlagsValid {
  732. subpackets = append(subpackets, outputSubpacket{true, keyFlagsSubpacket, false, []byte{sig.GetKeyFlags().BitField}})
  733. }
  734. // The following subpackets may only appear in self-signatures
  735. if sig.KeyLifetimeSecs != nil && *sig.KeyLifetimeSecs != 0 {
  736. keyLifetime := make([]byte, 4)
  737. binary.BigEndian.PutUint32(keyLifetime, *sig.KeyLifetimeSecs)
  738. subpackets = append(subpackets, outputSubpacket{true, keyExpirationSubpacket, true, keyLifetime})
  739. }
  740. if sig.IsPrimaryId != nil && *sig.IsPrimaryId {
  741. subpackets = append(subpackets, outputSubpacket{true, primaryUserIdSubpacket, false, []byte{1}})
  742. }
  743. if len(sig.PreferredSymmetric) > 0 {
  744. subpackets = append(subpackets, outputSubpacket{true, prefSymmetricAlgosSubpacket, false, sig.PreferredSymmetric})
  745. }
  746. if len(sig.PreferredHash) > 0 {
  747. subpackets = append(subpackets, outputSubpacket{true, prefHashAlgosSubpacket, false, sig.PreferredHash})
  748. }
  749. if len(sig.PreferredCompression) > 0 {
  750. subpackets = append(subpackets, outputSubpacket{true, prefCompressionSubpacket, false, sig.PreferredCompression})
  751. }
  752. return
  753. }
  754. func (sig *Signature) GetKeyFlags() (ret KeyFlagBits) {
  755. if !sig.FlagsValid {
  756. return ret
  757. }
  758. ret.Valid = true
  759. if sig.FlagCertify {
  760. ret.BitField |= KeyFlagCertify
  761. }
  762. if sig.FlagSign {
  763. ret.BitField |= KeyFlagSign
  764. }
  765. if sig.FlagEncryptCommunications {
  766. ret.BitField |= KeyFlagEncryptCommunications
  767. }
  768. if sig.FlagEncryptStorage {
  769. ret.BitField |= KeyFlagEncryptStorage
  770. }
  771. return ret
  772. }
  773. func (f *KeyFlagBits) HasFlagCertify() bool {
  774. return f.BitField&KeyFlagCertify != 0
  775. }
  776. func (f *KeyFlagBits) HasFlagSign() bool {
  777. return f.BitField&KeyFlagSign != 0
  778. }
  779. func (f *KeyFlagBits) HasFlagEncryptCommunications() bool {
  780. return f.BitField&KeyFlagEncryptCommunications != 0
  781. }
  782. func (f *KeyFlagBits) HasFlagEncryptStorage() bool {
  783. return f.BitField&KeyFlagEncryptStorage != 0
  784. }
  785. func (f *KeyFlagBits) Merge(other KeyFlagBits) {
  786. if other.Valid {
  787. f.Valid = true
  788. f.BitField |= other.BitField
  789. }
  790. }