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.

signature.go 21KB

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