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

931 lines
27KB

  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/elliptic"
  11. "crypto/sha1"
  12. _ "crypto/sha256"
  13. _ "crypto/sha512"
  14. "encoding/binary"
  15. "fmt"
  16. "hash"
  17. "io"
  18. "math/big"
  19. "strconv"
  20. "time"
  21. "github.com/keybase/go-crypto/brainpool"
  22. "github.com/keybase/go-crypto/curve25519"
  23. "github.com/keybase/go-crypto/ed25519"
  24. "github.com/keybase/go-crypto/openpgp/ecdh"
  25. "github.com/keybase/go-crypto/openpgp/elgamal"
  26. "github.com/keybase/go-crypto/openpgp/errors"
  27. "github.com/keybase/go-crypto/rsa"
  28. )
  29. var (
  30. // NIST curve P-256
  31. oidCurveP256 []byte = []byte{0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07}
  32. // NIST curve P-384
  33. oidCurveP384 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x22}
  34. // NIST curve P-521
  35. oidCurveP521 []byte = []byte{0x2B, 0x81, 0x04, 0x00, 0x23}
  36. // Brainpool curve P-256r1
  37. oidCurveP256r1 []byte = []byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07}
  38. // Brainpool curve P-384r1
  39. oidCurveP384r1 []byte = []byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B}
  40. // Brainpool curve P-512r1
  41. oidCurveP512r1 []byte = []byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D}
  42. // EdDSA
  43. oidEdDSA []byte = []byte{0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01}
  44. // cv25519
  45. oidCurve25519 []byte = []byte{0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01}
  46. )
  47. const maxOIDLength = 10
  48. // ecdsaKey stores the algorithm-specific fields for ECDSA keys.
  49. // as defined in RFC 6637, Section 9.
  50. type ecdsaKey struct {
  51. // oid contains the OID byte sequence identifying the elliptic curve used
  52. oid []byte
  53. // p contains the elliptic curve point that represents the public key
  54. p parsedMPI
  55. }
  56. type edDSAkey struct {
  57. ecdsaKey
  58. }
  59. func copyFrontFill(dst, src []byte, length int) int {
  60. if srcLen := len(src); srcLen < length {
  61. return copy(dst[length-srcLen:], src[:])
  62. } else {
  63. return copy(dst[:], src[:])
  64. }
  65. }
  66. func (e *edDSAkey) Verify(payload []byte, r parsedMPI, s parsedMPI) bool {
  67. const halfSigSize = ed25519.SignatureSize / 2
  68. var sig [ed25519.SignatureSize]byte
  69. // NOTE: The first byte is 0x40 - MPI header
  70. // TODO: Maybe clean the code up and use 0x40 as a header when
  71. // reading and keep only actual number in p field. Find out how
  72. // other MPIs are stored.
  73. key := e.p.bytes[1:]
  74. // Note: it may happen that R + S do not form 64-byte signature buffer that
  75. // ed25519 expects, but because we copy it over to an array of exact size,
  76. // we will always pass correctly sized slice to Verify. Slice too short
  77. // would make ed25519 panic().
  78. copyFrontFill(sig[:halfSigSize], r.bytes, halfSigSize)
  79. copyFrontFill(sig[halfSigSize:], s.bytes, halfSigSize)
  80. return ed25519.Verify(key, payload, sig[:])
  81. }
  82. // parseOID reads the OID for the curve as defined in RFC 6637, Section 9.
  83. func parseOID(r io.Reader) (oid []byte, err error) {
  84. buf := make([]byte, maxOIDLength)
  85. if _, err = readFull(r, buf[:1]); err != nil {
  86. return
  87. }
  88. oidLen := buf[0]
  89. if int(oidLen) > len(buf) {
  90. err = errors.UnsupportedError("invalid oid length: " + strconv.Itoa(int(oidLen)))
  91. return
  92. }
  93. oid = buf[:oidLen]
  94. _, err = readFull(r, oid)
  95. return
  96. }
  97. func (f *ecdsaKey) parse(r io.Reader) (err error) {
  98. if f.oid, err = parseOID(r); err != nil {
  99. return err
  100. }
  101. f.p.bytes, f.p.bitLength, err = readMPI(r)
  102. return err
  103. }
  104. func (f *ecdsaKey) serialize(w io.Writer) (err error) {
  105. buf := make([]byte, maxOIDLength+1)
  106. buf[0] = byte(len(f.oid))
  107. copy(buf[1:], f.oid)
  108. if _, err = w.Write(buf[:len(f.oid)+1]); err != nil {
  109. return
  110. }
  111. return writeMPIs(w, f.p)
  112. }
  113. func getCurveByOid(oid []byte) elliptic.Curve {
  114. switch {
  115. case bytes.Equal(oid, oidCurveP256):
  116. return elliptic.P256()
  117. case bytes.Equal(oid, oidCurveP384):
  118. return elliptic.P384()
  119. case bytes.Equal(oid, oidCurveP521):
  120. return elliptic.P521()
  121. case bytes.Equal(oid, oidCurveP256r1):
  122. return brainpool.P256r1()
  123. case bytes.Equal(oid, oidCurveP384r1):
  124. return brainpool.P384r1()
  125. case bytes.Equal(oid, oidCurveP512r1):
  126. return brainpool.P512r1()
  127. case bytes.Equal(oid, oidCurve25519):
  128. return curve25519.Cv25519()
  129. default:
  130. return nil
  131. }
  132. }
  133. func (f *ecdsaKey) newECDSA() (*ecdsa.PublicKey, error) {
  134. var c = getCurveByOid(f.oid)
  135. // Curve25519 should not be used in ECDSA.
  136. if c == nil || bytes.Equal(f.oid, oidCurve25519) {
  137. return nil, errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", f.oid))
  138. }
  139. // Note: Unmarshal already checks if point is on curve.
  140. x, y := elliptic.Unmarshal(c, f.p.bytes)
  141. if x == nil {
  142. return nil, errors.UnsupportedError("failed to parse EC point")
  143. }
  144. return &ecdsa.PublicKey{Curve: c, X: x, Y: y}, nil
  145. }
  146. func (f *ecdsaKey) newECDH() (*ecdh.PublicKey, error) {
  147. var c = getCurveByOid(f.oid)
  148. if c == nil {
  149. return nil, errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", f.oid))
  150. }
  151. // ecdh.Unmarshal handles unmarshaling for all curve types. It
  152. // also checks if point is on curve.
  153. x, y := ecdh.Unmarshal(c, f.p.bytes)
  154. if x == nil {
  155. return nil, errors.UnsupportedError("failed to parse EC point")
  156. }
  157. return &ecdh.PublicKey{Curve: c, X: x, Y: y}, nil
  158. }
  159. func (f *ecdsaKey) byteLen() int {
  160. return 1 + len(f.oid) + 2 + len(f.p.bytes)
  161. }
  162. type kdfHashFunction byte
  163. type kdfAlgorithm byte
  164. // ecdhKdf stores key derivation function parameters
  165. // used for ECDH encryption. See RFC 6637, Section 9.
  166. type ecdhKdf struct {
  167. KdfHash kdfHashFunction
  168. KdfAlgo kdfAlgorithm
  169. }
  170. func (f *ecdhKdf) parse(r io.Reader) (err error) {
  171. buf := make([]byte, 1)
  172. if _, err = readFull(r, buf); err != nil {
  173. return
  174. }
  175. kdfLen := int(buf[0])
  176. if kdfLen < 3 {
  177. return errors.UnsupportedError("Unsupported ECDH KDF length: " + strconv.Itoa(kdfLen))
  178. }
  179. buf = make([]byte, kdfLen)
  180. if _, err = readFull(r, buf); err != nil {
  181. return
  182. }
  183. reserved := int(buf[0])
  184. f.KdfHash = kdfHashFunction(buf[1])
  185. f.KdfAlgo = kdfAlgorithm(buf[2])
  186. if reserved != 0x01 {
  187. return errors.UnsupportedError("Unsupported KDF reserved field: " + strconv.Itoa(reserved))
  188. }
  189. return
  190. }
  191. func (f *ecdhKdf) serialize(w io.Writer) (err error) {
  192. buf := make([]byte, 4)
  193. // See RFC 6637, Section 9, Algorithm-Specific Fields for ECDH keys.
  194. buf[0] = byte(0x03) // Length of the following fields
  195. buf[1] = byte(0x01) // Reserved for future extensions, must be 1 for now
  196. buf[2] = byte(f.KdfHash)
  197. buf[3] = byte(f.KdfAlgo)
  198. _, err = w.Write(buf[:])
  199. return
  200. }
  201. func (f *ecdhKdf) byteLen() int {
  202. return 4
  203. }
  204. // PublicKey represents an OpenPGP public key. See RFC 4880, section 5.5.2.
  205. type PublicKey struct {
  206. CreationTime time.Time
  207. PubKeyAlgo PublicKeyAlgorithm
  208. PublicKey interface{} // *rsa.PublicKey, *dsa.PublicKey or *ecdsa.PublicKey
  209. Fingerprint [20]byte
  210. KeyId uint64
  211. IsSubkey bool
  212. n, e, p, q, g, y parsedMPI
  213. // RFC 6637 fields
  214. ec *ecdsaKey
  215. ecdh *ecdhKdf
  216. // EdDSA fields (no RFC available), uses ecdsa scaffolding
  217. edk *edDSAkey
  218. }
  219. // signingKey provides a convenient abstraction over signature verification
  220. // for v3 and v4 public keys.
  221. type signingKey interface {
  222. SerializeSignaturePrefix(io.Writer)
  223. serializeWithoutHeaders(io.Writer) error
  224. }
  225. func FromBig(n *big.Int) parsedMPI {
  226. return parsedMPI{
  227. bytes: n.Bytes(),
  228. bitLength: uint16(n.BitLen()),
  229. }
  230. }
  231. func FromBytes(bytes []byte) parsedMPI {
  232. return parsedMPI{
  233. bytes: bytes,
  234. bitLength: uint16(8 * len(bytes)),
  235. }
  236. }
  237. // NewRSAPublicKey returns a PublicKey that wraps the given rsa.PublicKey.
  238. func NewRSAPublicKey(creationTime time.Time, pub *rsa.PublicKey) *PublicKey {
  239. pk := &PublicKey{
  240. CreationTime: creationTime,
  241. PubKeyAlgo: PubKeyAlgoRSA,
  242. PublicKey: pub,
  243. n: FromBig(pub.N),
  244. e: FromBig(big.NewInt(int64(pub.E))),
  245. }
  246. pk.setFingerPrintAndKeyId()
  247. return pk
  248. }
  249. // NewDSAPublicKey returns a PublicKey that wraps the given dsa.PublicKey.
  250. func NewDSAPublicKey(creationTime time.Time, pub *dsa.PublicKey) *PublicKey {
  251. pk := &PublicKey{
  252. CreationTime: creationTime,
  253. PubKeyAlgo: PubKeyAlgoDSA,
  254. PublicKey: pub,
  255. p: FromBig(pub.P),
  256. q: FromBig(pub.Q),
  257. g: FromBig(pub.G),
  258. y: FromBig(pub.Y),
  259. }
  260. pk.setFingerPrintAndKeyId()
  261. return pk
  262. }
  263. // check EdDSA public key material.
  264. // There is currently no RFC for it, but it doesn't mean it's not
  265. // implemented or in use.
  266. func (e *edDSAkey) check() error {
  267. if !bytes.Equal(e.oid, oidEdDSA) {
  268. return errors.UnsupportedError(fmt.Sprintf("Bad OID for EdDSA key: %v", e.oid))
  269. }
  270. if bLen := len(e.p.bytes); bLen != 33 { // 32 bytes for ed25519 key and 1 byte for 0x40 header
  271. return errors.UnsupportedError(fmt.Sprintf("Unexpected EdDSA public key length: %d", bLen))
  272. }
  273. return nil
  274. }
  275. // NewElGamalPublicKey returns a PublicKey that wraps the given elgamal.PublicKey.
  276. func NewElGamalPublicKey(creationTime time.Time, pub *elgamal.PublicKey) *PublicKey {
  277. pk := &PublicKey{
  278. CreationTime: creationTime,
  279. PubKeyAlgo: PubKeyAlgoElGamal,
  280. PublicKey: pub,
  281. p: FromBig(pub.P),
  282. g: FromBig(pub.G),
  283. y: FromBig(pub.Y),
  284. }
  285. pk.setFingerPrintAndKeyId()
  286. return pk
  287. }
  288. func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey {
  289. pk := &PublicKey{
  290. CreationTime: creationTime,
  291. PubKeyAlgo: PubKeyAlgoECDSA,
  292. PublicKey: pub,
  293. ec: new(ecdsaKey),
  294. }
  295. switch pub.Curve {
  296. case elliptic.P256():
  297. pk.ec.oid = oidCurveP256
  298. case elliptic.P384():
  299. pk.ec.oid = oidCurveP384
  300. case elliptic.P521():
  301. pk.ec.oid = oidCurveP521
  302. case brainpool.P256r1():
  303. pk.ec.oid = oidCurveP256r1
  304. case brainpool.P384r1():
  305. pk.ec.oid = oidCurveP384r1
  306. case brainpool.P512r1():
  307. pk.ec.oid = oidCurveP512r1
  308. }
  309. pk.ec.p.bytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  310. pk.ec.p.bitLength = uint16(8 * len(pk.ec.p.bytes))
  311. pk.setFingerPrintAndKeyId()
  312. return pk
  313. }
  314. func (pk *PublicKey) parse(r io.Reader) (err error) {
  315. // RFC 4880, section 5.5.2
  316. var buf [6]byte
  317. _, err = readFull(r, buf[:])
  318. if err != nil {
  319. return
  320. }
  321. if buf[0] != 4 {
  322. return errors.UnsupportedError("public key version")
  323. }
  324. pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0)
  325. pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5])
  326. switch pk.PubKeyAlgo {
  327. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  328. err = pk.parseRSA(r)
  329. case PubKeyAlgoDSA:
  330. err = pk.parseDSA(r)
  331. case PubKeyAlgoElGamal:
  332. err = pk.parseElGamal(r)
  333. case PubKeyAlgoEdDSA:
  334. pk.edk = new(edDSAkey)
  335. if err = pk.edk.parse(r); err != nil {
  336. return err
  337. }
  338. err = pk.edk.check()
  339. case PubKeyAlgoECDSA:
  340. pk.ec = new(ecdsaKey)
  341. if err = pk.ec.parse(r); err != nil {
  342. return err
  343. }
  344. pk.PublicKey, err = pk.ec.newECDSA()
  345. case PubKeyAlgoECDH:
  346. pk.ec = new(ecdsaKey)
  347. if err = pk.ec.parse(r); err != nil {
  348. return
  349. }
  350. pk.ecdh = new(ecdhKdf)
  351. if err = pk.ecdh.parse(r); err != nil {
  352. return
  353. }
  354. pk.PublicKey, err = pk.ec.newECDH()
  355. default:
  356. err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo)))
  357. }
  358. if err != nil {
  359. return
  360. }
  361. pk.setFingerPrintAndKeyId()
  362. return
  363. }
  364. func (pk *PublicKey) setFingerPrintAndKeyId() {
  365. // RFC 4880, section 12.2
  366. fingerPrint := sha1.New()
  367. pk.SerializeSignaturePrefix(fingerPrint)
  368. pk.serializeWithoutHeaders(fingerPrint)
  369. copy(pk.Fingerprint[:], fingerPrint.Sum(nil))
  370. pk.KeyId = binary.BigEndian.Uint64(pk.Fingerprint[12:20])
  371. }
  372. // parseRSA parses RSA public key material from the given Reader. See RFC 4880,
  373. // section 5.5.2.
  374. func (pk *PublicKey) parseRSA(r io.Reader) (err error) {
  375. pk.n.bytes, pk.n.bitLength, err = readMPI(r)
  376. if err != nil {
  377. return
  378. }
  379. pk.e.bytes, pk.e.bitLength, err = readMPI(r)
  380. if err != nil {
  381. return
  382. }
  383. if len(pk.e.bytes) > 7 {
  384. err = errors.UnsupportedError("large public exponent")
  385. return
  386. }
  387. rsa := &rsa.PublicKey{
  388. N: new(big.Int).SetBytes(pk.n.bytes),
  389. E: 0,
  390. }
  391. for i := 0; i < len(pk.e.bytes); i++ {
  392. rsa.E <<= 8
  393. rsa.E |= int64(pk.e.bytes[i])
  394. }
  395. pk.PublicKey = rsa
  396. return
  397. }
  398. // parseDSA parses DSA public key material from the given Reader. See RFC 4880,
  399. // section 5.5.2.
  400. func (pk *PublicKey) parseDSA(r io.Reader) (err error) {
  401. pk.p.bytes, pk.p.bitLength, err = readMPI(r)
  402. if err != nil {
  403. return
  404. }
  405. pk.q.bytes, pk.q.bitLength, err = readMPI(r)
  406. if err != nil {
  407. return
  408. }
  409. pk.g.bytes, pk.g.bitLength, err = readMPI(r)
  410. if err != nil {
  411. return
  412. }
  413. pk.y.bytes, pk.y.bitLength, err = readMPI(r)
  414. if err != nil {
  415. return
  416. }
  417. dsa := new(dsa.PublicKey)
  418. dsa.P = new(big.Int).SetBytes(pk.p.bytes)
  419. dsa.Q = new(big.Int).SetBytes(pk.q.bytes)
  420. dsa.G = new(big.Int).SetBytes(pk.g.bytes)
  421. dsa.Y = new(big.Int).SetBytes(pk.y.bytes)
  422. pk.PublicKey = dsa
  423. return
  424. }
  425. // parseElGamal parses ElGamal public key material from the given Reader. See
  426. // RFC 4880, section 5.5.2.
  427. func (pk *PublicKey) parseElGamal(r io.Reader) (err error) {
  428. pk.p.bytes, pk.p.bitLength, err = readMPI(r)
  429. if err != nil {
  430. return
  431. }
  432. pk.g.bytes, pk.g.bitLength, err = readMPI(r)
  433. if err != nil {
  434. return
  435. }
  436. pk.y.bytes, pk.y.bitLength, err = readMPI(r)
  437. if err != nil {
  438. return
  439. }
  440. elgamal := new(elgamal.PublicKey)
  441. elgamal.P = new(big.Int).SetBytes(pk.p.bytes)
  442. elgamal.G = new(big.Int).SetBytes(pk.g.bytes)
  443. elgamal.Y = new(big.Int).SetBytes(pk.y.bytes)
  444. pk.PublicKey = elgamal
  445. return
  446. }
  447. // SerializeSignaturePrefix writes the prefix for this public key to the given Writer.
  448. // The prefix is used when calculating a signature over this public key. See
  449. // RFC 4880, section 5.2.4.
  450. func (pk *PublicKey) SerializeSignaturePrefix(h io.Writer) {
  451. var pLength uint16
  452. switch pk.PubKeyAlgo {
  453. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  454. pLength += 2 + uint16(len(pk.n.bytes))
  455. pLength += 2 + uint16(len(pk.e.bytes))
  456. case PubKeyAlgoDSA:
  457. pLength += 2 + uint16(len(pk.p.bytes))
  458. pLength += 2 + uint16(len(pk.q.bytes))
  459. pLength += 2 + uint16(len(pk.g.bytes))
  460. pLength += 2 + uint16(len(pk.y.bytes))
  461. case PubKeyAlgoElGamal:
  462. pLength += 2 + uint16(len(pk.p.bytes))
  463. pLength += 2 + uint16(len(pk.g.bytes))
  464. pLength += 2 + uint16(len(pk.y.bytes))
  465. case PubKeyAlgoECDSA:
  466. pLength += uint16(pk.ec.byteLen())
  467. case PubKeyAlgoECDH:
  468. pLength += uint16(pk.ec.byteLen())
  469. pLength += uint16(pk.ecdh.byteLen())
  470. case PubKeyAlgoEdDSA:
  471. pLength += uint16(pk.edk.byteLen())
  472. default:
  473. panic("unknown public key algorithm")
  474. }
  475. pLength += 6
  476. h.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)})
  477. return
  478. }
  479. func (pk *PublicKey) Serialize(w io.Writer) (err error) {
  480. length := 6 // 6 byte header
  481. switch pk.PubKeyAlgo {
  482. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  483. length += 2 + len(pk.n.bytes)
  484. length += 2 + len(pk.e.bytes)
  485. case PubKeyAlgoDSA:
  486. length += 2 + len(pk.p.bytes)
  487. length += 2 + len(pk.q.bytes)
  488. length += 2 + len(pk.g.bytes)
  489. length += 2 + len(pk.y.bytes)
  490. case PubKeyAlgoElGamal:
  491. length += 2 + len(pk.p.bytes)
  492. length += 2 + len(pk.g.bytes)
  493. length += 2 + len(pk.y.bytes)
  494. case PubKeyAlgoECDSA:
  495. length += pk.ec.byteLen()
  496. case PubKeyAlgoECDH:
  497. length += pk.ec.byteLen()
  498. length += pk.ecdh.byteLen()
  499. case PubKeyAlgoEdDSA:
  500. length += pk.edk.byteLen()
  501. default:
  502. panic("unknown public key algorithm")
  503. }
  504. packetType := packetTypePublicKey
  505. if pk.IsSubkey {
  506. packetType = packetTypePublicSubkey
  507. }
  508. err = serializeHeader(w, packetType, length)
  509. if err != nil {
  510. return
  511. }
  512. return pk.serializeWithoutHeaders(w)
  513. }
  514. // serializeWithoutHeaders marshals the PublicKey to w in the form of an
  515. // OpenPGP public key packet, not including the packet header.
  516. func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err error) {
  517. var buf [6]byte
  518. buf[0] = 4
  519. t := uint32(pk.CreationTime.Unix())
  520. buf[1] = byte(t >> 24)
  521. buf[2] = byte(t >> 16)
  522. buf[3] = byte(t >> 8)
  523. buf[4] = byte(t)
  524. buf[5] = byte(pk.PubKeyAlgo)
  525. _, err = w.Write(buf[:])
  526. if err != nil {
  527. return
  528. }
  529. switch pk.PubKeyAlgo {
  530. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  531. return writeMPIs(w, pk.n, pk.e)
  532. case PubKeyAlgoDSA:
  533. return writeMPIs(w, pk.p, pk.q, pk.g, pk.y)
  534. case PubKeyAlgoElGamal:
  535. return writeMPIs(w, pk.p, pk.g, pk.y)
  536. case PubKeyAlgoECDSA:
  537. return pk.ec.serialize(w)
  538. case PubKeyAlgoEdDSA:
  539. return pk.edk.serialize(w)
  540. case PubKeyAlgoECDH:
  541. if err = pk.ec.serialize(w); err != nil {
  542. return
  543. }
  544. return pk.ecdh.serialize(w)
  545. }
  546. return errors.InvalidArgumentError("bad public-key algorithm")
  547. }
  548. // CanSign returns true iff this public key can generate signatures
  549. func (pk *PublicKey) CanSign() bool {
  550. return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly && pk.PubKeyAlgo != PubKeyAlgoElGamal
  551. }
  552. // VerifySignature returns nil iff sig is a valid signature, made by this
  553. // public key, of the data hashed into signed. signed is mutated by this call.
  554. func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) {
  555. if !pk.CanSign() {
  556. return errors.InvalidArgumentError("public key cannot generate signatures")
  557. }
  558. signed.Write(sig.HashSuffix)
  559. hashBytes := signed.Sum(nil)
  560. // NOTE(maxtaco) 2016-08-22
  561. //
  562. // We used to do this:
  563. //
  564. // if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
  565. // return errors.SignatureError("hash tag doesn't match")
  566. // }
  567. //
  568. // But don't do anything in this case. Some GPGs generate bad
  569. // 2-byte hash prefixes, but GPG also doesn't seem to care on
  570. // import. See BrentMaxwell's key. I think it's safe to disable
  571. // this check!
  572. if pk.PubKeyAlgo != sig.PubKeyAlgo {
  573. return errors.InvalidArgumentError("public key and signature use different algorithms")
  574. }
  575. switch pk.PubKeyAlgo {
  576. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  577. rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey)
  578. err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes)
  579. if err != nil {
  580. return errors.SignatureError("RSA verification failure")
  581. }
  582. return nil
  583. case PubKeyAlgoDSA:
  584. dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey)
  585. // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
  586. subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8
  587. if len(hashBytes) > subgroupSize {
  588. hashBytes = hashBytes[:subgroupSize]
  589. }
  590. if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
  591. return errors.SignatureError("DSA verification failure")
  592. }
  593. return nil
  594. case PubKeyAlgoECDSA:
  595. ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey)
  596. if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.bytes), new(big.Int).SetBytes(sig.ECDSASigS.bytes)) {
  597. return errors.SignatureError("ECDSA verification failure")
  598. }
  599. return nil
  600. case PubKeyAlgoEdDSA:
  601. if !pk.edk.Verify(hashBytes, sig.EdDSASigR, sig.EdDSASigS) {
  602. return errors.SignatureError("EdDSA verification failure")
  603. }
  604. return nil
  605. default:
  606. return errors.SignatureError("Unsupported public key algorithm used in signature")
  607. }
  608. panic("unreachable")
  609. }
  610. // VerifySignatureV3 returns nil iff sig is a valid signature, made by this
  611. // public key, of the data hashed into signed. signed is mutated by this call.
  612. func (pk *PublicKey) VerifySignatureV3(signed hash.Hash, sig *SignatureV3) (err error) {
  613. if !pk.CanSign() {
  614. return errors.InvalidArgumentError("public key cannot generate signatures")
  615. }
  616. suffix := make([]byte, 5)
  617. suffix[0] = byte(sig.SigType)
  618. binary.BigEndian.PutUint32(suffix[1:], uint32(sig.CreationTime.Unix()))
  619. signed.Write(suffix)
  620. hashBytes := signed.Sum(nil)
  621. if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] {
  622. return errors.SignatureError("hash tag doesn't match")
  623. }
  624. if pk.PubKeyAlgo != sig.PubKeyAlgo {
  625. return errors.InvalidArgumentError("public key and signature use different algorithms")
  626. }
  627. switch pk.PubKeyAlgo {
  628. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly:
  629. rsaPublicKey := pk.PublicKey.(*rsa.PublicKey)
  630. if err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, sig.RSASignature.bytes); err != nil {
  631. return errors.SignatureError("RSA verification failure")
  632. }
  633. return
  634. case PubKeyAlgoDSA:
  635. dsaPublicKey := pk.PublicKey.(*dsa.PublicKey)
  636. // Need to truncate hashBytes to match FIPS 186-3 section 4.6.
  637. subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8
  638. if len(hashBytes) > subgroupSize {
  639. hashBytes = hashBytes[:subgroupSize]
  640. }
  641. if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.bytes), new(big.Int).SetBytes(sig.DSASigS.bytes)) {
  642. return errors.SignatureError("DSA verification failure")
  643. }
  644. return nil
  645. default:
  646. panic("shouldn't happen")
  647. }
  648. panic("unreachable")
  649. }
  650. // keySignatureHash returns a Hash of the message that needs to be signed for
  651. // pk to assert a subkey relationship to signed.
  652. func keySignatureHash(pk, signed signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) {
  653. if !hashFunc.Available() {
  654. return nil, errors.UnsupportedError("hash function")
  655. }
  656. h = hashFunc.New()
  657. updateKeySignatureHash(pk, signed, h)
  658. return
  659. }
  660. // updateKeySignatureHash does the actual hash updates for keySignatureHash.
  661. func updateKeySignatureHash(pk, signed signingKey, h hash.Hash) {
  662. // RFC 4880, section 5.2.4
  663. pk.SerializeSignaturePrefix(h)
  664. pk.serializeWithoutHeaders(h)
  665. signed.SerializeSignaturePrefix(h)
  666. signed.serializeWithoutHeaders(h)
  667. }
  668. // VerifyKeySignature returns nil iff sig is a valid signature, made by this
  669. // public key, of signed.
  670. func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) error {
  671. h, err := keySignatureHash(pk, signed, sig.Hash)
  672. if err != nil {
  673. return err
  674. }
  675. if err = pk.VerifySignature(h, sig); err != nil {
  676. return err
  677. }
  678. if sig.FlagSign {
  679. // BUG(maxtaco)
  680. //
  681. // We should check for more than FlagsSign here, because if
  682. // you read keys.go, we can sometimes use signing subkeys even if they're
  683. // not explicitly flagged as such. However, so doing fails lots of currently
  684. // working tests, so I'm not going to do much here.
  685. //
  686. // In other words, we should have this disjunction in the condition above:
  687. //
  688. // || (!sig.FlagsValid && pk.PubKeyAlgo.CanSign()) {
  689. //
  690. // Signing subkeys must be cross-signed. See
  691. // https://www.gnupg.org/faq/subkey-cross-certify.html.
  692. if sig.EmbeddedSignature == nil {
  693. return errors.StructuralError("signing subkey is missing cross-signature")
  694. }
  695. // Verify the cross-signature. This is calculated over the same
  696. // data as the main signature, so we cannot just recursively
  697. // call signed.VerifyKeySignature(...)
  698. if h, err = keySignatureHash(pk, signed, sig.EmbeddedSignature.Hash); err != nil {
  699. return errors.StructuralError("error while hashing for cross-signature: " + err.Error())
  700. }
  701. if err := signed.VerifySignature(h, sig.EmbeddedSignature); err != nil {
  702. return errors.StructuralError("error while verifying cross-signature: " + err.Error())
  703. }
  704. }
  705. return nil
  706. }
  707. func keyRevocationHash(pk signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) {
  708. if !hashFunc.Available() {
  709. return nil, errors.UnsupportedError("hash function")
  710. }
  711. h = hashFunc.New()
  712. // RFC 4880, section 5.2.4
  713. pk.SerializeSignaturePrefix(h)
  714. pk.serializeWithoutHeaders(h)
  715. return
  716. }
  717. // VerifyRevocationSignature returns nil iff sig is a valid signature, made by this
  718. // public key.
  719. func (pk *PublicKey) VerifyRevocationSignature(revokedKey *PublicKey, sig *Signature) (err error) {
  720. h, err := keyRevocationHash(revokedKey, sig.Hash)
  721. if err != nil {
  722. return err
  723. }
  724. return pk.VerifySignature(h, sig)
  725. }
  726. type teeHash struct {
  727. h hash.Hash
  728. }
  729. func (t teeHash) Write(b []byte) (n int, err error) {
  730. fmt.Printf("hash -> %s %+v\n", string(b), b)
  731. return t.h.Write(b)
  732. }
  733. func (t teeHash) Sum(b []byte) []byte { return t.h.Sum(b) }
  734. func (t teeHash) Reset() { t.h.Reset() }
  735. func (t teeHash) Size() int { return t.h.Size() }
  736. func (t teeHash) BlockSize() int { return t.h.BlockSize() }
  737. // userIdSignatureHash returns a Hash of the message that needs to be signed
  738. // to assert that pk is a valid key for id.
  739. func userIdSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash.Hash, err error) {
  740. if !hashFunc.Available() {
  741. return nil, errors.UnsupportedError("hash function")
  742. }
  743. h = hashFunc.New()
  744. updateUserIdSignatureHash(id, pk, h)
  745. return
  746. }
  747. // updateUserIdSignatureHash does the actual hash updates for
  748. // userIdSignatureHash.
  749. func updateUserIdSignatureHash(id string, pk *PublicKey, h hash.Hash) {
  750. // RFC 4880, section 5.2.4
  751. pk.SerializeSignaturePrefix(h)
  752. pk.serializeWithoutHeaders(h)
  753. var buf [5]byte
  754. buf[0] = 0xb4
  755. buf[1] = byte(len(id) >> 24)
  756. buf[2] = byte(len(id) >> 16)
  757. buf[3] = byte(len(id) >> 8)
  758. buf[4] = byte(len(id))
  759. h.Write(buf[:])
  760. h.Write([]byte(id))
  761. return
  762. }
  763. // VerifyUserIdSignature returns nil iff sig is a valid signature, made by this
  764. // public key, that id is the identity of pub.
  765. func (pk *PublicKey) VerifyUserIdSignature(id string, pub *PublicKey, sig *Signature) (err error) {
  766. h, err := userIdSignatureHash(id, pub, sig.Hash)
  767. if err != nil {
  768. return err
  769. }
  770. return pk.VerifySignature(h, sig)
  771. }
  772. // VerifyUserIdSignatureV3 returns nil iff sig is a valid signature, made by this
  773. // public key, that id is the identity of pub.
  774. func (pk *PublicKey) VerifyUserIdSignatureV3(id string, pub *PublicKey, sig *SignatureV3) (err error) {
  775. h, err := userIdSignatureV3Hash(id, pub, sig.Hash)
  776. if err != nil {
  777. return err
  778. }
  779. return pk.VerifySignatureV3(h, sig)
  780. }
  781. // KeyIdString returns the public key's fingerprint in capital hex
  782. // (e.g. "6C7EE1B8621CC013").
  783. func (pk *PublicKey) KeyIdString() string {
  784. return fmt.Sprintf("%X", pk.Fingerprint[12:20])
  785. }
  786. // KeyIdShortString returns the short form of public key's fingerprint
  787. // in capital hex, as shown by gpg --list-keys (e.g. "621CC013").
  788. func (pk *PublicKey) KeyIdShortString() string {
  789. return fmt.Sprintf("%X", pk.Fingerprint[16:20])
  790. }
  791. // A parsedMPI is used to store the contents of a big integer, along with the
  792. // bit length that was specified in the original input. This allows the MPI to
  793. // be reserialized exactly.
  794. type parsedMPI struct {
  795. bytes []byte
  796. bitLength uint16
  797. }
  798. // writeMPIs is a utility function for serializing several big integers to the
  799. // given Writer.
  800. func writeMPIs(w io.Writer, mpis ...parsedMPI) (err error) {
  801. for _, mpi := range mpis {
  802. err = writeMPI(w, mpi.bitLength, mpi.bytes)
  803. if err != nil {
  804. return
  805. }
  806. }
  807. return
  808. }
  809. // BitLength returns the bit length for the given public key. Used for
  810. // displaying key information, actual buffers and BigInts inside may
  811. // have non-matching different size if the key is invalid.
  812. func (pk *PublicKey) BitLength() (bitLength uint16, err error) {
  813. switch pk.PubKeyAlgo {
  814. case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly:
  815. bitLength = pk.n.bitLength
  816. case PubKeyAlgoDSA:
  817. bitLength = pk.p.bitLength
  818. case PubKeyAlgoElGamal:
  819. bitLength = pk.p.bitLength
  820. case PubKeyAlgoECDH:
  821. ecdhPublicKey := pk.PublicKey.(*ecdh.PublicKey)
  822. bitLength = uint16(ecdhPublicKey.Curve.Params().BitSize)
  823. case PubKeyAlgoECDSA:
  824. ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey)
  825. bitLength = uint16(ecdsaPublicKey.Curve.Params().BitSize)
  826. case PubKeyAlgoEdDSA:
  827. // EdDSA only support ed25519 curves right now, just return
  828. // the length. Also, we don't have any PublicKey.Curve object
  829. // to look the size up from.
  830. bitLength = 256
  831. default:
  832. err = errors.InvalidArgumentError("bad public-key algorithm")
  833. }
  834. return
  835. }
上海开阖软件有限公司 沪ICP备12045867号-1