signature.go 20 KB

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