signature.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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. "crypto/rsa"
  11. "encoding/binary"
  12. "hash"
  13. "io"
  14. "strconv"
  15. "time"
  16. "golang.org/x/crypto/openpgp/errors"
  17. "golang.org/x/crypto/openpgp/s2k"
  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. // Signature represents a signature. See RFC 4880, section 5.2.
  27. type Signature struct {
  28. SigType SignatureType
  29. PubKeyAlgo PublicKeyAlgorithm
  30. Hash crypto.Hash
  31. // HashSuffix is extra data that is hashed in after the signed data.
  32. HashSuffix []byte
  33. // HashTag contains the first two bytes of the hash for fast rejection
  34. // of bad signed data.
  35. HashTag [2]byte
  36. CreationTime time.Time
  37. RSASignature parsedMPI
  38. DSASigR, DSASigS parsedMPI
  39. ECDSASigR, ECDSASigS parsedMPI
  40. // rawSubpackets contains the unparsed subpackets, in order.
  41. rawSubpackets []outputSubpacket
  42. // The following are optional so are nil when not included in the
  43. // signature.
  44. SigLifetimeSecs, KeyLifetimeSecs *uint32
  45. PreferredSymmetric, PreferredHash, PreferredCompression []uint8
  46. IssuerKeyId *uint64
  47. IsPrimaryId *bool
  48. // FlagsValid is set if any flags were given. See RFC 4880, section
  49. // 5.2.3.21 for details.
  50. FlagsValid bool
  51. FlagCertify, FlagSign, FlagEncryptCommunications, FlagEncryptStorage bool
  52. // RevocationReason is set if this signature has been revoked.
  53. // See RFC 4880, section 5.2.3.23 for details.
  54. RevocationReason *uint8
  55. RevocationReasonText string
  56. // MDC is set if this signature has a feature packet that indicates
  57. // support for MDC subpackets.
  58. MDC bool
  59. // EmbeddedSignature, if non-nil, is a signature of the parent key, by
  60. // this key. This prevents an attacker from claiming another's signing
  61. // subkey as their own.
  62. EmbeddedSignature *Signature
  63. outSubpackets []outputSubpacket
  64. }
  65. func (sig *Signature) parse(r io.Reader) (err error) {
  66. // RFC 4880, section 5.2.3
  67. var buf [5]byte
  68. _, err = readFull(r, buf[:1])
  69. if err != nil {
  70. return
  71. }
  72. if buf[0] != 4 {
  73. err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0])))
  74. return
  75. }
  76. _, err = readFull(r, buf[:5])
  77. if err != nil {
  78. return
  79. }
  80. sig.SigType = SignatureType(buf[0])
  81. sig.PubKeyAlgo = PublicKeyAlgorithm(buf[1])
  82. switch sig.PubKeyAlgo {
  83. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA:
  84. default:
  85. err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo)))
  86. return
  87. }
  88. var ok bool
  89. sig.Hash, ok = s2k.HashIdToHash(buf[2])
  90. if !ok {
  91. return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2])))
  92. }
  93. hashedSubpacketsLength := int(buf[3])<<8 | int(buf[4])
  94. l := 6 + hashedSubpacketsLength
  95. sig.HashSuffix = make([]byte, l+6)
  96. sig.HashSuffix[0] = 4
  97. copy(sig.HashSuffix[1:], buf[:5])
  98. hashedSubpackets := sig.HashSuffix[6:l]
  99. _, err = readFull(r, hashedSubpackets)
  100. if err != nil {
  101. return
  102. }
  103. // See RFC 4880, section 5.2.4
  104. trailer := sig.HashSuffix[l:]
  105. trailer[0] = 4
  106. trailer[1] = 0xff
  107. trailer[2] = uint8(l >> 24)
  108. trailer[3] = uint8(l >> 16)
  109. trailer[4] = uint8(l >> 8)
  110. trailer[5] = uint8(l)
  111. err = parseSignatureSubpackets(sig, hashedSubpackets, true)
  112. if err != nil {
  113. return
  114. }
  115. _, err = readFull(r, buf[:2])
  116. if err != nil {
  117. return
  118. }
  119. unhashedSubpacketsLength := int(buf[0])<<8 | int(buf[1])
  120. unhashedSubpackets := make([]byte, unhashedSubpacketsLength)
  121. _, err = readFull(r, unhashedSubpackets)
  122. if err != nil {
  123. return
  124. }
  125. err = parseSignatureSubpackets(sig, unhashedSubpackets, false)
  126. if err != nil {
  127. return
  128. }
  129. _, err = readFull(r, sig.HashTag[:2])
  130. if err != nil {
  131. return
  132. }
  133. switch sig.PubKeyAlgo {
  134. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  135. sig.RSASignature.bytes, sig.RSASignature.bitLength, err = readMPI(r)
  136. case PubKeyAlgoDSA:
  137. sig.DSASigR.bytes, sig.DSASigR.bitLength, err = readMPI(r)
  138. if err == nil {
  139. sig.DSASigS.bytes, sig.DSASigS.bitLength, err = readMPI(r)
  140. }
  141. case PubKeyAlgoECDSA:
  142. sig.ECDSASigR.bytes, sig.ECDSASigR.bitLength, err = readMPI(r)
  143. if err == nil {
  144. sig.ECDSASigS.bytes, sig.ECDSASigS.bitLength, err = readMPI(r)
  145. }
  146. default:
  147. panic("unreachable")
  148. }
  149. return
  150. }
  151. // parseSignatureSubpackets parses subpackets of the main signature packet. See
  152. // RFC 4880, section 5.2.3.1.
  153. func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) {
  154. for len(subpackets) > 0 {
  155. subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed)
  156. if err != nil {
  157. return
  158. }
  159. }
  160. if sig.CreationTime.IsZero() {
  161. err = errors.StructuralError("no creation time in signature")
  162. }
  163. return
  164. }
  165. type signatureSubpacketType uint8
  166. const (
  167. creationTimeSubpacket signatureSubpacketType = 2
  168. signatureExpirationSubpacket signatureSubpacketType = 3
  169. keyExpirationSubpacket signatureSubpacketType = 9
  170. prefSymmetricAlgosSubpacket signatureSubpacketType = 11
  171. issuerSubpacket signatureSubpacketType = 16
  172. prefHashAlgosSubpacket signatureSubpacketType = 21
  173. prefCompressionSubpacket signatureSubpacketType = 22
  174. primaryUserIdSubpacket signatureSubpacketType = 25
  175. keyFlagsSubpacket signatureSubpacketType = 27
  176. reasonForRevocationSubpacket signatureSubpacketType = 29
  177. featuresSubpacket signatureSubpacketType = 30
  178. embeddedSignatureSubpacket signatureSubpacketType = 32
  179. )
  180. // parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1.
  181. func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) {
  182. // RFC 4880, section 5.2.3.1
  183. var (
  184. length uint32
  185. packetType signatureSubpacketType
  186. isCritical bool
  187. )
  188. switch {
  189. case subpacket[0] < 192:
  190. length = uint32(subpacket[0])
  191. subpacket = subpacket[1:]
  192. case subpacket[0] < 255:
  193. if len(subpacket) < 2 {
  194. goto Truncated
  195. }
  196. length = uint32(subpacket[0]-192)<<8 + uint32(subpacket[1]) + 192
  197. subpacket = subpacket[2:]
  198. default:
  199. if len(subpacket) < 5 {
  200. goto Truncated
  201. }
  202. length = uint32(subpacket[1])<<24 |
  203. uint32(subpacket[2])<<16 |
  204. uint32(subpacket[3])<<8 |
  205. uint32(subpacket[4])
  206. subpacket = subpacket[5:]
  207. }
  208. if length > uint32(len(subpacket)) {
  209. goto Truncated
  210. }
  211. rest = subpacket[length:]
  212. subpacket = subpacket[:length]
  213. if len(subpacket) == 0 {
  214. err = errors.StructuralError("zero length signature subpacket")
  215. return
  216. }
  217. packetType = signatureSubpacketType(subpacket[0] & 0x7f)
  218. isCritical = subpacket[0]&0x80 == 0x80
  219. subpacket = subpacket[1:]
  220. sig.rawSubpackets = append(sig.rawSubpackets, outputSubpacket{isHashed, packetType, isCritical, subpacket})
  221. switch packetType {
  222. case creationTimeSubpacket:
  223. if !isHashed {
  224. err = errors.StructuralError("signature creation time in non-hashed area")
  225. return
  226. }
  227. if len(subpacket) != 4 {
  228. err = errors.StructuralError("signature creation time not four bytes")
  229. return
  230. }
  231. t := binary.BigEndian.Uint32(subpacket)
  232. sig.CreationTime = time.Unix(int64(t), 0)
  233. case signatureExpirationSubpacket:
  234. // Signature expiration time, section 5.2.3.10
  235. if !isHashed {
  236. return
  237. }
  238. if len(subpacket) != 4 {
  239. err = errors.StructuralError("expiration subpacket with bad length")
  240. return
  241. }
  242. sig.SigLifetimeSecs = new(uint32)
  243. *sig.SigLifetimeSecs = binary.BigEndian.Uint32(subpacket)
  244. case keyExpirationSubpacket:
  245. // Key expiration time, section 5.2.3.6
  246. if !isHashed {
  247. return
  248. }
  249. if len(subpacket) != 4 {
  250. err = errors.StructuralError("key expiration subpacket with bad length")
  251. return
  252. }
  253. sig.KeyLifetimeSecs = new(uint32)
  254. *sig.KeyLifetimeSecs = binary.BigEndian.Uint32(subpacket)
  255. case prefSymmetricAlgosSubpacket:
  256. // Preferred symmetric algorithms, section 5.2.3.7
  257. if !isHashed {
  258. return
  259. }
  260. sig.PreferredSymmetric = make([]byte, len(subpacket))
  261. copy(sig.PreferredSymmetric, subpacket)
  262. case issuerSubpacket:
  263. // Issuer, section 5.2.3.5
  264. if len(subpacket) != 8 {
  265. err = errors.StructuralError("issuer subpacket with bad length")
  266. return
  267. }
  268. sig.IssuerKeyId = new(uint64)
  269. *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket)
  270. case prefHashAlgosSubpacket:
  271. // Preferred hash algorithms, section 5.2.3.8
  272. if !isHashed {
  273. return
  274. }
  275. sig.PreferredHash = make([]byte, len(subpacket))
  276. copy(sig.PreferredHash, subpacket)
  277. case prefCompressionSubpacket:
  278. // Preferred compression algorithms, section 5.2.3.9
  279. if !isHashed {
  280. return
  281. }
  282. sig.PreferredCompression = make([]byte, len(subpacket))
  283. copy(sig.PreferredCompression, subpacket)
  284. case primaryUserIdSubpacket:
  285. // Primary User ID, section 5.2.3.19
  286. if !isHashed {
  287. return
  288. }
  289. if len(subpacket) != 1 {
  290. err = errors.StructuralError("primary user id subpacket with bad length")
  291. return
  292. }
  293. sig.IsPrimaryId = new(bool)
  294. if subpacket[0] > 0 {
  295. *sig.IsPrimaryId = true
  296. }
  297. case keyFlagsSubpacket:
  298. // Key flags, section 5.2.3.21
  299. if !isHashed {
  300. return
  301. }
  302. if len(subpacket) == 0 {
  303. err = errors.StructuralError("empty key flags subpacket")
  304. return
  305. }
  306. sig.FlagsValid = true
  307. if subpacket[0]&KeyFlagCertify != 0 {
  308. sig.FlagCertify = true
  309. }
  310. if subpacket[0]&KeyFlagSign != 0 {
  311. sig.FlagSign = true
  312. }
  313. if subpacket[0]&KeyFlagEncryptCommunications != 0 {
  314. sig.FlagEncryptCommunications = true
  315. }
  316. if subpacket[0]&KeyFlagEncryptStorage != 0 {
  317. sig.FlagEncryptStorage = true
  318. }
  319. case reasonForRevocationSubpacket:
  320. // Reason For Revocation, section 5.2.3.23
  321. if !isHashed {
  322. return
  323. }
  324. if len(subpacket) == 0 {
  325. err = errors.StructuralError("empty revocation reason subpacket")
  326. return
  327. }
  328. sig.RevocationReason = new(uint8)
  329. *sig.RevocationReason = subpacket[0]
  330. sig.RevocationReasonText = string(subpacket[1:])
  331. case featuresSubpacket:
  332. // Features subpacket, section 5.2.3.24 specifies a very general
  333. // mechanism for OpenPGP implementations to signal support for new
  334. // features. In practice, the subpacket is used exclusively to
  335. // indicate support for MDC-protected encryption.
  336. sig.MDC = len(subpacket) >= 1 && subpacket[0]&1 == 1
  337. case embeddedSignatureSubpacket:
  338. // Only usage is in signatures that cross-certify
  339. // signing subkeys. section 5.2.3.26 describes the
  340. // format, with its usage described in section 11.1
  341. if sig.EmbeddedSignature != nil {
  342. err = errors.StructuralError("Cannot have multiple embedded signatures")
  343. return
  344. }
  345. sig.EmbeddedSignature = new(Signature)
  346. // Embedded signatures are required to be v4 signatures see
  347. // section 12.1. However, we only parse v4 signatures in this
  348. // file anyway.
  349. if err := sig.EmbeddedSignature.parse(bytes.NewBuffer(subpacket)); err != nil {
  350. return nil, err
  351. }
  352. if sigType := sig.EmbeddedSignature.SigType; sigType != SigTypePrimaryKeyBinding {
  353. return nil, errors.StructuralError("cross-signature has unexpected type " + strconv.Itoa(int(sigType)))
  354. }
  355. default:
  356. if isCritical {
  357. err = errors.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType)))
  358. return
  359. }
  360. }
  361. return
  362. Truncated:
  363. err = errors.StructuralError("signature subpacket truncated")
  364. return
  365. }
  366. // subpacketLengthLength returns the length, in bytes, of an encoded length value.
  367. func subpacketLengthLength(length int) int {
  368. if length < 192 {
  369. return 1
  370. }
  371. if length < 16320 {
  372. return 2
  373. }
  374. return 5
  375. }
  376. // serializeSubpacketLength marshals the given length into to.
  377. func serializeSubpacketLength(to []byte, length int) int {
  378. // RFC 4880, Section 4.2.2.
  379. if length < 192 {
  380. to[0] = byte(length)
  381. return 1
  382. }
  383. if length < 16320 {
  384. length -= 192
  385. to[0] = byte((length >> 8) + 192)
  386. to[1] = byte(length)
  387. return 2
  388. }
  389. to[0] = 255
  390. to[1] = byte(length >> 24)
  391. to[2] = byte(length >> 16)
  392. to[3] = byte(length >> 8)
  393. to[4] = byte(length)
  394. return 5
  395. }
  396. // subpacketsLength returns the serialized length, in bytes, of the given
  397. // subpackets.
  398. func subpacketsLength(subpackets []outputSubpacket, hashed bool) (length int) {
  399. for _, subpacket := range subpackets {
  400. if subpacket.hashed == hashed {
  401. length += subpacketLengthLength(len(subpacket.contents) + 1)
  402. length += 1 // type byte
  403. length += len(subpacket.contents)
  404. }
  405. }
  406. return
  407. }
  408. // serializeSubpackets marshals the given subpackets into to.
  409. func serializeSubpackets(to []byte, subpackets []outputSubpacket, hashed bool) {
  410. for _, subpacket := range subpackets {
  411. if subpacket.hashed == hashed {
  412. n := serializeSubpacketLength(to, len(subpacket.contents)+1)
  413. to[n] = byte(subpacket.subpacketType)
  414. to = to[1+n:]
  415. n = copy(to, subpacket.contents)
  416. to = to[n:]
  417. }
  418. }
  419. return
  420. }
  421. // KeyExpired returns whether sig is a self-signature of a key that has
  422. // expired.
  423. func (sig *Signature) KeyExpired(currentTime time.Time) bool {
  424. if sig.KeyLifetimeSecs == nil {
  425. return false
  426. }
  427. expiry := sig.CreationTime.Add(time.Duration(*sig.KeyLifetimeSecs) * time.Second)
  428. return currentTime.After(expiry)
  429. }
  430. // buildHashSuffix constructs the HashSuffix member of sig in preparation for signing.
  431. func (sig *Signature) buildHashSuffix() (err error) {
  432. hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true)
  433. var ok bool
  434. l := 6 + hashedSubpacketsLen
  435. sig.HashSuffix = make([]byte, l+6)
  436. sig.HashSuffix[0] = 4
  437. sig.HashSuffix[1] = uint8(sig.SigType)
  438. sig.HashSuffix[2] = uint8(sig.PubKeyAlgo)
  439. sig.HashSuffix[3], ok = s2k.HashToHashId(sig.Hash)
  440. if !ok {
  441. sig.HashSuffix = nil
  442. return errors.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash)))
  443. }
  444. sig.HashSuffix[4] = byte(hashedSubpacketsLen >> 8)
  445. sig.HashSuffix[5] = byte(hashedSubpacketsLen)
  446. serializeSubpackets(sig.HashSuffix[6:l], sig.outSubpackets, true)
  447. trailer := sig.HashSuffix[l:]
  448. trailer[0] = 4
  449. trailer[1] = 0xff
  450. trailer[2] = byte(l >> 24)
  451. trailer[3] = byte(l >> 16)
  452. trailer[4] = byte(l >> 8)
  453. trailer[5] = byte(l)
  454. return
  455. }
  456. func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err error) {
  457. err = sig.buildHashSuffix()
  458. if err != nil {
  459. return
  460. }
  461. h.Write(sig.HashSuffix)
  462. digest = h.Sum(nil)
  463. copy(sig.HashTag[:], digest)
  464. return
  465. }
  466. // Sign signs a message with a private key. The hash, h, must contain
  467. // the hash of the message to be signed and will be mutated by this function.
  468. // On success, the signature is stored in sig. Call Serialize to write it out.
  469. // If config is nil, sensible defaults will be used.
  470. func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err error) {
  471. sig.outSubpackets = sig.buildSubpackets()
  472. digest, err := sig.signPrepareHash(h)
  473. if err != nil {
  474. return
  475. }
  476. switch priv.PubKeyAlgo {
  477. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  478. sig.RSASignature.bytes, err = rsa.SignPKCS1v15(config.Random(), priv.PrivateKey.(*rsa.PrivateKey), sig.Hash, digest)
  479. sig.RSASignature.bitLength = uint16(8 * len(sig.RSASignature.bytes))
  480. case PubKeyAlgoDSA:
  481. dsaPriv := priv.PrivateKey.(*dsa.PrivateKey)
  482. // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
  483. subgroupSize := (dsaPriv.Q.BitLen() + 7) / 8
  484. if len(digest) > subgroupSize {
  485. digest = digest[:subgroupSize]
  486. }
  487. r, s, err := dsa.Sign(config.Random(), dsaPriv, digest)
  488. if err == nil {
  489. sig.DSASigR.bytes = r.Bytes()
  490. sig.DSASigR.bitLength = uint16(8 * len(sig.DSASigR.bytes))
  491. sig.DSASigS.bytes = s.Bytes()
  492. sig.DSASigS.bitLength = uint16(8 * len(sig.DSASigS.bytes))
  493. }
  494. case PubKeyAlgoECDSA:
  495. r, s, err := ecdsa.Sign(config.Random(), priv.PrivateKey.(*ecdsa.PrivateKey), digest)
  496. if err == nil {
  497. sig.ECDSASigR = fromBig(r)
  498. sig.ECDSASigS = fromBig(s)
  499. }
  500. default:
  501. err = errors.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo)))
  502. }
  503. return
  504. }
  505. // SignUserId computes a signature from priv, asserting that pub is a valid
  506. // key for the identity id. On success, the signature is stored in sig. Call
  507. // Serialize to write it out.
  508. // If config is nil, sensible defaults will be used.
  509. func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey, config *Config) error {
  510. h, err := userIdSignatureHash(id, pub, sig.Hash)
  511. if err != nil {
  512. return err
  513. }
  514. return sig.Sign(h, priv, config)
  515. }
  516. // SignKey computes a signature from priv, asserting that pub is a subkey. On
  517. // success, the signature is stored in sig. Call Serialize to write it out.
  518. // If config is nil, sensible defaults will be used.
  519. func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey, config *Config) error {
  520. h, err := keySignatureHash(&priv.PublicKey, pub, sig.Hash)
  521. if err != nil {
  522. return err
  523. }
  524. return sig.Sign(h, priv, config)
  525. }
  526. // Serialize marshals sig to w. Sign, SignUserId or SignKey must have been
  527. // called first.
  528. func (sig *Signature) Serialize(w io.Writer) (err error) {
  529. if len(sig.outSubpackets) == 0 {
  530. sig.outSubpackets = sig.rawSubpackets
  531. }
  532. if sig.RSASignature.bytes == nil && sig.DSASigR.bytes == nil && sig.ECDSASigR.bytes == nil {
  533. return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize")
  534. }
  535. sigLength := 0
  536. switch sig.PubKeyAlgo {
  537. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  538. sigLength = 2 + len(sig.RSASignature.bytes)
  539. case PubKeyAlgoDSA:
  540. sigLength = 2 + len(sig.DSASigR.bytes)
  541. sigLength += 2 + len(sig.DSASigS.bytes)
  542. case PubKeyAlgoECDSA:
  543. sigLength = 2 + len(sig.ECDSASigR.bytes)
  544. sigLength += 2 + len(sig.ECDSASigS.bytes)
  545. default:
  546. panic("impossible")
  547. }
  548. unhashedSubpacketsLen := subpacketsLength(sig.outSubpackets, false)
  549. length := len(sig.HashSuffix) - 6 /* trailer not included */ +
  550. 2 /* length of unhashed subpackets */ + unhashedSubpacketsLen +
  551. 2 /* hash tag */ + sigLength
  552. err = serializeHeader(w, packetTypeSignature, length)
  553. if err != nil {
  554. return
  555. }
  556. _, err = w.Write(sig.HashSuffix[:len(sig.HashSuffix)-6])
  557. if err != nil {
  558. return
  559. }
  560. unhashedSubpackets := make([]byte, 2+unhashedSubpacketsLen)
  561. unhashedSubpackets[0] = byte(unhashedSubpacketsLen >> 8)
  562. unhashedSubpackets[1] = byte(unhashedSubpacketsLen)
  563. serializeSubpackets(unhashedSubpackets[2:], sig.outSubpackets, false)
  564. _, err = w.Write(unhashedSubpackets)
  565. if err != nil {
  566. return
  567. }
  568. _, err = w.Write(sig.HashTag[:])
  569. if err != nil {
  570. return
  571. }
  572. switch sig.PubKeyAlgo {
  573. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  574. err = writeMPIs(w, sig.RSASignature)
  575. case PubKeyAlgoDSA:
  576. err = writeMPIs(w, sig.DSASigR, sig.DSASigS)
  577. case PubKeyAlgoECDSA:
  578. err = writeMPIs(w, sig.ECDSASigR, sig.ECDSASigS)
  579. default:
  580. panic("impossible")
  581. }
  582. return
  583. }
  584. // outputSubpacket represents a subpacket to be marshaled.
  585. type outputSubpacket struct {
  586. hashed bool // true if this subpacket is in the hashed area.
  587. subpacketType signatureSubpacketType
  588. isCritical bool
  589. contents []byte
  590. }
  591. func (sig *Signature) buildSubpackets() (subpackets []outputSubpacket) {
  592. creationTime := make([]byte, 4)
  593. binary.BigEndian.PutUint32(creationTime, uint32(sig.CreationTime.Unix()))
  594. subpackets = append(subpackets, outputSubpacket{true, creationTimeSubpacket, false, creationTime})
  595. if sig.IssuerKeyId != nil {
  596. keyId := make([]byte, 8)
  597. binary.BigEndian.PutUint64(keyId, *sig.IssuerKeyId)
  598. subpackets = append(subpackets, outputSubpacket{true, issuerSubpacket, false, keyId})
  599. }
  600. if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 {
  601. sigLifetime := make([]byte, 4)
  602. binary.BigEndian.PutUint32(sigLifetime, *sig.SigLifetimeSecs)
  603. subpackets = append(subpackets, outputSubpacket{true, signatureExpirationSubpacket, true, sigLifetime})
  604. }
  605. // Key flags may only appear in self-signatures or certification signatures.
  606. if sig.FlagsValid {
  607. var flags byte
  608. if sig.FlagCertify {
  609. flags |= KeyFlagCertify
  610. }
  611. if sig.FlagSign {
  612. flags |= KeyFlagSign
  613. }
  614. if sig.FlagEncryptCommunications {
  615. flags |= KeyFlagEncryptCommunications
  616. }
  617. if sig.FlagEncryptStorage {
  618. flags |= KeyFlagEncryptStorage
  619. }
  620. subpackets = append(subpackets, outputSubpacket{true, keyFlagsSubpacket, false, []byte{flags}})
  621. }
  622. // The following subpackets may only appear in self-signatures
  623. if sig.KeyLifetimeSecs != nil && *sig.KeyLifetimeSecs != 0 {
  624. keyLifetime := make([]byte, 4)
  625. binary.BigEndian.PutUint32(keyLifetime, *sig.KeyLifetimeSecs)
  626. subpackets = append(subpackets, outputSubpacket{true, keyExpirationSubpacket, true, keyLifetime})
  627. }
  628. if sig.IsPrimaryId != nil && *sig.IsPrimaryId {
  629. subpackets = append(subpackets, outputSubpacket{true, primaryUserIdSubpacket, false, []byte{1}})
  630. }
  631. if len(sig.PreferredSymmetric) > 0 {
  632. subpackets = append(subpackets, outputSubpacket{true, prefSymmetricAlgosSubpacket, false, sig.PreferredSymmetric})
  633. }
  634. if len(sig.PreferredHash) > 0 {
  635. subpackets = append(subpackets, outputSubpacket{true, prefHashAlgosSubpacket, false, sig.PreferredHash})
  636. }
  637. if len(sig.PreferredCompression) > 0 {
  638. subpackets = append(subpackets, outputSubpacket{true, prefCompressionSubpacket, false, sig.PreferredCompression})
  639. }
  640. return
  641. }