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.

550 lines
13 KiB

  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package packet
  5. import (
  6. "bytes"
  7. "crypto/cipher"
  8. "crypto/dsa"
  9. "crypto/ecdsa"
  10. "crypto/sha1"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "math/big"
  15. "strconv"
  16. "time"
  17. "github.com/keybase/go-crypto/ed25519"
  18. "github.com/keybase/go-crypto/openpgp/ecdh"
  19. "github.com/keybase/go-crypto/openpgp/elgamal"
  20. "github.com/keybase/go-crypto/openpgp/errors"
  21. "github.com/keybase/go-crypto/openpgp/s2k"
  22. "github.com/keybase/go-crypto/rsa"
  23. )
  24. // PrivateKey represents a possibly encrypted private key. See RFC 4880,
  25. // section 5.5.3.
  26. type PrivateKey struct {
  27. PublicKey
  28. Encrypted bool // if true then the private key is unavailable until Decrypt has been called.
  29. encryptedData []byte
  30. cipher CipherFunction
  31. s2k func(out, in []byte)
  32. PrivateKey interface{} // An *rsa.PrivateKey or *dsa.PrivateKey.
  33. sha1Checksum bool
  34. iv []byte
  35. s2kHeader []byte
  36. }
  37. type EdDSAPrivateKey struct {
  38. PrivateKey
  39. seed parsedMPI
  40. }
  41. func (e *EdDSAPrivateKey) Sign(digest []byte) (R, S []byte, err error) {
  42. r := bytes.NewReader(e.seed.bytes)
  43. publicKey, privateKey, err := ed25519.GenerateKey(r)
  44. if err != nil {
  45. return nil, nil, err
  46. }
  47. if !bytes.Equal(publicKey, e.PublicKey.edk.p.bytes[1:]) { // [1:] because [0] is 0x40 mpi header
  48. return nil, nil, errors.UnsupportedError("EdDSA: Private key does not match public key.")
  49. }
  50. sig := ed25519.Sign(privateKey, digest)
  51. sigLen := ed25519.SignatureSize / 2
  52. return sig[:sigLen], sig[sigLen:], nil
  53. }
  54. func NewRSAPrivateKey(currentTime time.Time, priv *rsa.PrivateKey) *PrivateKey {
  55. pk := new(PrivateKey)
  56. pk.PublicKey = *NewRSAPublicKey(currentTime, &priv.PublicKey)
  57. pk.PrivateKey = priv
  58. return pk
  59. }
  60. func NewDSAPrivateKey(currentTime time.Time, priv *dsa.PrivateKey) *PrivateKey {
  61. pk := new(PrivateKey)
  62. pk.PublicKey = *NewDSAPublicKey(currentTime, &priv.PublicKey)
  63. pk.PrivateKey = priv
  64. return pk
  65. }
  66. func NewElGamalPrivateKey(currentTime time.Time, priv *elgamal.PrivateKey) *PrivateKey {
  67. pk := new(PrivateKey)
  68. pk.PublicKey = *NewElGamalPublicKey(currentTime, &priv.PublicKey)
  69. pk.PrivateKey = priv
  70. return pk
  71. }
  72. func NewECDSAPrivateKey(currentTime time.Time, priv *ecdsa.PrivateKey) *PrivateKey {
  73. pk := new(PrivateKey)
  74. pk.PublicKey = *NewECDSAPublicKey(currentTime, &priv.PublicKey)
  75. pk.PrivateKey = priv
  76. return pk
  77. }
  78. func (pk *PrivateKey) parse(r io.Reader) (err error) {
  79. err = (&pk.PublicKey).parse(r)
  80. if err != nil {
  81. return
  82. }
  83. var buf [1]byte
  84. _, err = readFull(r, buf[:])
  85. if err != nil {
  86. return
  87. }
  88. s2kType := buf[0]
  89. switch s2kType {
  90. case 0:
  91. pk.s2k = nil
  92. pk.Encrypted = false
  93. case 254, 255:
  94. _, err = readFull(r, buf[:])
  95. if err != nil {
  96. return
  97. }
  98. pk.cipher = CipherFunction(buf[0])
  99. pk.Encrypted = true
  100. pk.s2k, err = s2k.Parse(r)
  101. if err != nil {
  102. return
  103. }
  104. if s2kType == 254 {
  105. pk.sha1Checksum = true
  106. }
  107. // S2K == nil implies that we got a "GNU Dummy" S2K. For instance,
  108. // because our master secret key is on a USB key in a vault somewhere.
  109. // In that case, there is no further data to consume here.
  110. if pk.s2k == nil {
  111. pk.Encrypted = false
  112. return
  113. }
  114. default:
  115. return errors.UnsupportedError("deprecated s2k function in private key")
  116. }
  117. if pk.Encrypted {
  118. blockSize := pk.cipher.blockSize()
  119. if blockSize == 0 {
  120. return errors.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher)))
  121. }
  122. pk.iv = make([]byte, blockSize)
  123. _, err = readFull(r, pk.iv)
  124. if err != nil {
  125. return
  126. }
  127. }
  128. pk.encryptedData, err = ioutil.ReadAll(r)
  129. if err != nil {
  130. return
  131. }
  132. if !pk.Encrypted {
  133. return pk.parsePrivateKey(pk.encryptedData)
  134. }
  135. return
  136. }
  137. func mod64kHash(d []byte) uint16 {
  138. var h uint16
  139. for _, b := range d {
  140. h += uint16(b)
  141. }
  142. return h
  143. }
  144. // Encrypt is the counterpart to the Decrypt() method below. It encrypts
  145. // the private key with the provided passphrase. If config is nil, then
  146. // the standard, and sensible, defaults apply.
  147. //
  148. // A key will be derived from the given passphrase using S2K Specifier
  149. // Type 3 (Iterated + Salted, see RFC-4880 Sec. 3.7.1.3). This choice
  150. // is hardcoded in s2k.Serialize(). S2KCount is hardcoded to 0, which is
  151. // equivalent to 65536. And the hash algorithm for key-derivation can be
  152. // set with config. The encrypted PrivateKey, using the algorithm specified
  153. // in config (if provided), is written out to the encryptedData member.
  154. // When Serialize() is called, this encryptedData member will be
  155. // serialized, using S2K Usage value of 254, and thus SHA1 checksum.
  156. func (pk *PrivateKey) Encrypt(passphrase []byte, config *Config) (err error) {
  157. if pk.PrivateKey == nil {
  158. return errors.InvalidArgumentError("there is no private key to encrypt")
  159. }
  160. pk.sha1Checksum = true
  161. pk.cipher = config.Cipher()
  162. s2kConfig := s2k.Config{
  163. Hash: config.Hash(),
  164. S2KCount: 0,
  165. }
  166. s2kBuf := bytes.NewBuffer(nil)
  167. derivedKey := make([]byte, pk.cipher.KeySize())
  168. err = s2k.Serialize(s2kBuf, derivedKey, config.Random(), passphrase, &s2kConfig)
  169. if err != nil {
  170. return err
  171. }
  172. pk.s2kHeader = s2kBuf.Bytes()
  173. // No good way to set pk.s2k but to call s2k.Parse(),
  174. // even though we have all the information here, but
  175. // most of the functions needed are private to s2k.
  176. pk.s2k, err = s2k.Parse(s2kBuf)
  177. pk.iv = make([]byte, pk.cipher.blockSize())
  178. if _, err = config.Random().Read(pk.iv); err != nil {
  179. return err
  180. }
  181. privateKeyBuf := bytes.NewBuffer(nil)
  182. if err = pk.serializePrivateKey(privateKeyBuf); err != nil {
  183. return err
  184. }
  185. checksum := sha1.Sum(privateKeyBuf.Bytes())
  186. if _, err = privateKeyBuf.Write(checksum[:]); err != nil {
  187. return err
  188. }
  189. pkData := privateKeyBuf.Bytes()
  190. block := pk.cipher.new(derivedKey)
  191. pk.encryptedData = make([]byte, len(pkData))
  192. cfb := cipher.NewCFBEncrypter(block, pk.iv)
  193. cfb.XORKeyStream(pk.encryptedData, pkData)
  194. pk.Encrypted = true
  195. return nil
  196. }
  197. func (pk *PrivateKey) Serialize(w io.Writer) (err error) {
  198. buf := bytes.NewBuffer(nil)
  199. err = pk.PublicKey.serializeWithoutHeaders(buf)
  200. if err != nil {
  201. return
  202. }
  203. privateKeyBuf := bytes.NewBuffer(nil)
  204. if pk.PrivateKey == nil {
  205. _, err = buf.Write([]byte{
  206. 254, // SHA-1 Convention
  207. 9, // Encryption scheme (AES256)
  208. 101, // GNU Extensions
  209. 2, // Hash value (SHA1)
  210. 'G', 'N', 'U', // "GNU" as a string
  211. 1, // Extension type 1001 (minus 1000)
  212. })
  213. } else if pk.Encrypted {
  214. _, err = buf.Write([]byte{
  215. 254, // SHA-1 Convention
  216. byte(pk.cipher), // Encryption scheme
  217. })
  218. if err != nil {
  219. return err
  220. }
  221. if _, err = buf.Write(pk.s2kHeader); err != nil {
  222. return err
  223. }
  224. if _, err = buf.Write(pk.iv); err != nil {
  225. return err
  226. }
  227. if _, err = privateKeyBuf.Write(pk.encryptedData); err != nil {
  228. return err
  229. }
  230. } else {
  231. buf.WriteByte(0 /* no encryption */)
  232. if err = pk.serializePrivateKey(privateKeyBuf); err != nil {
  233. return err
  234. }
  235. }
  236. ptype := packetTypePrivateKey
  237. contents := buf.Bytes()
  238. privateKeyBytes := privateKeyBuf.Bytes()
  239. if pk.IsSubkey {
  240. ptype = packetTypePrivateSubkey
  241. }
  242. totalLen := len(contents) + len(privateKeyBytes)
  243. if !pk.Encrypted {
  244. totalLen += 2
  245. }
  246. err = serializeHeader(w, ptype, totalLen)
  247. if err != nil {
  248. return
  249. }
  250. _, err = w.Write(contents)
  251. if err != nil {
  252. return
  253. }
  254. _, err = w.Write(privateKeyBytes)
  255. if err != nil {
  256. return
  257. }
  258. if len(privateKeyBytes) > 0 && !pk.Encrypted {
  259. checksum := mod64kHash(privateKeyBytes)
  260. var checksumBytes [2]byte
  261. checksumBytes[0] = byte(checksum >> 8)
  262. checksumBytes[1] = byte(checksum)
  263. _, err = w.Write(checksumBytes[:])
  264. }
  265. return
  266. }
  267. func (pk *PrivateKey) serializePrivateKey(w io.Writer) (err error) {
  268. switch priv := pk.PrivateKey.(type) {
  269. case *rsa.PrivateKey:
  270. err = serializeRSAPrivateKey(w, priv)
  271. case *dsa.PrivateKey:
  272. err = serializeDSAPrivateKey(w, priv)
  273. case *elgamal.PrivateKey:
  274. err = serializeElGamalPrivateKey(w, priv)
  275. case *ecdsa.PrivateKey:
  276. err = serializeECDSAPrivateKey(w, priv)
  277. case *ecdh.PrivateKey:
  278. err = serializeECDHPrivateKey(w, priv)
  279. case *EdDSAPrivateKey:
  280. err = serializeEdDSAPrivateKey(w, priv)
  281. default:
  282. err = errors.InvalidArgumentError("unknown private key type")
  283. }
  284. return err
  285. }
  286. func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) error {
  287. err := writeBig(w, priv.D)
  288. if err != nil {
  289. return err
  290. }
  291. err = writeBig(w, priv.Primes[1])
  292. if err != nil {
  293. return err
  294. }
  295. err = writeBig(w, priv.Primes[0])
  296. if err != nil {
  297. return err
  298. }
  299. return writeBig(w, priv.Precomputed.Qinv)
  300. }
  301. func serializeDSAPrivateKey(w io.Writer, priv *dsa.PrivateKey) error {
  302. return writeBig(w, priv.X)
  303. }
  304. func serializeElGamalPrivateKey(w io.Writer, priv *elgamal.PrivateKey) error {
  305. return writeBig(w, priv.X)
  306. }
  307. func serializeECDSAPrivateKey(w io.Writer, priv *ecdsa.PrivateKey) error {
  308. return writeBig(w, priv.D)
  309. }
  310. func serializeECDHPrivateKey(w io.Writer, priv *ecdh.PrivateKey) error {
  311. return writeBig(w, priv.X)
  312. }
  313. func serializeEdDSAPrivateKey(w io.Writer, priv *EdDSAPrivateKey) error {
  314. return writeMPI(w, priv.seed.bitLength, priv.seed.bytes)
  315. }
  316. // Decrypt decrypts an encrypted private key using a passphrase.
  317. func (pk *PrivateKey) Decrypt(passphrase []byte) error {
  318. if !pk.Encrypted {
  319. return nil
  320. }
  321. // For GNU Dummy S2K, there's no key here, so don't do anything.
  322. if pk.s2k == nil {
  323. return nil
  324. }
  325. key := make([]byte, pk.cipher.KeySize())
  326. pk.s2k(key, passphrase)
  327. block := pk.cipher.new(key)
  328. cfb := cipher.NewCFBDecrypter(block, pk.iv)
  329. data := make([]byte, len(pk.encryptedData))
  330. cfb.XORKeyStream(data, pk.encryptedData)
  331. if pk.sha1Checksum {
  332. if len(data) < sha1.Size {
  333. return errors.StructuralError("truncated private key data")
  334. }
  335. h := sha1.New()
  336. h.Write(data[:len(data)-sha1.Size])
  337. sum := h.Sum(nil)
  338. if !bytes.Equal(sum, data[len(data)-sha1.Size:]) {
  339. return errors.StructuralError("private key checksum failure")
  340. }
  341. data = data[:len(data)-sha1.Size]
  342. } else {
  343. if len(data) < 2 {
  344. return errors.StructuralError("truncated private key data")
  345. }
  346. var sum uint16
  347. for i := 0; i < len(data)-2; i++ {
  348. sum += uint16(data[i])
  349. }
  350. if data[len(data)-2] != uint8(sum>>8) ||
  351. data[len(data)-1] != uint8(sum) {
  352. return errors.StructuralError("private key checksum failure")
  353. }
  354. data = data[:len(data)-2]
  355. }
  356. return pk.parsePrivateKey(data)
  357. }
  358. func (pk *PrivateKey) parsePrivateKey(data []byte) (err error) {
  359. switch pk.PublicKey.PubKeyAlgo {
  360. case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly:
  361. return pk.parseRSAPrivateKey(data)
  362. case PubKeyAlgoDSA:
  363. return pk.parseDSAPrivateKey(data)
  364. case PubKeyAlgoElGamal:
  365. return pk.parseElGamalPrivateKey(data)
  366. case PubKeyAlgoECDSA:
  367. return pk.parseECDSAPrivateKey(data)
  368. case PubKeyAlgoECDH:
  369. return pk.parseECDHPrivateKey(data)
  370. case PubKeyAlgoEdDSA:
  371. return pk.parseEdDSAPrivateKey(data)
  372. }
  373. panic("impossible")
  374. }
  375. func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) {
  376. rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey)
  377. rsaPriv := new(rsa.PrivateKey)
  378. rsaPriv.PublicKey = *rsaPub
  379. buf := bytes.NewBuffer(data)
  380. d, _, err := readMPI(buf)
  381. if err != nil {
  382. return
  383. }
  384. p, _, err := readMPI(buf)
  385. if err != nil {
  386. return
  387. }
  388. q, _, err := readMPI(buf)
  389. if err != nil {
  390. return
  391. }
  392. rsaPriv.D = new(big.Int).SetBytes(d)
  393. rsaPriv.Primes = make([]*big.Int, 2)
  394. rsaPriv.Primes[0] = new(big.Int).SetBytes(p)
  395. rsaPriv.Primes[1] = new(big.Int).SetBytes(q)
  396. if err := rsaPriv.Validate(); err != nil {
  397. return err
  398. }
  399. rsaPriv.Precompute()
  400. pk.PrivateKey = rsaPriv
  401. pk.Encrypted = false
  402. pk.encryptedData = nil
  403. return nil
  404. }
  405. func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err error) {
  406. dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey)
  407. dsaPriv := new(dsa.PrivateKey)
  408. dsaPriv.PublicKey = *dsaPub
  409. buf := bytes.NewBuffer(data)
  410. x, _, err := readMPI(buf)
  411. if err != nil {
  412. return
  413. }
  414. dsaPriv.X = new(big.Int).SetBytes(x)
  415. pk.PrivateKey = dsaPriv
  416. pk.Encrypted = false
  417. pk.encryptedData = nil
  418. return nil
  419. }
  420. func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err error) {
  421. pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey)
  422. priv := new(elgamal.PrivateKey)
  423. priv.PublicKey = *pub
  424. buf := bytes.NewBuffer(data)
  425. x, _, err := readMPI(buf)
  426. if err != nil {
  427. return
  428. }
  429. priv.X = new(big.Int).SetBytes(x)
  430. pk.PrivateKey = priv
  431. pk.Encrypted = false
  432. pk.encryptedData = nil
  433. return nil
  434. }
  435. func (pk *PrivateKey) parseECDHPrivateKey(data []byte) (err error) {
  436. pub := pk.PublicKey.PublicKey.(*ecdh.PublicKey)
  437. priv := new(ecdh.PrivateKey)
  438. priv.PublicKey = *pub
  439. buf := bytes.NewBuffer(data)
  440. d, _, err := readMPI(buf)
  441. if err != nil {
  442. return
  443. }
  444. priv.X = new(big.Int).SetBytes(d)
  445. pk.PrivateKey = priv
  446. pk.Encrypted = false
  447. pk.encryptedData = nil
  448. return nil
  449. }
  450. func (pk *PrivateKey) parseECDSAPrivateKey(data []byte) (err error) {
  451. ecdsaPub := pk.PublicKey.PublicKey.(*ecdsa.PublicKey)
  452. ecdsaPriv := new(ecdsa.PrivateKey)
  453. ecdsaPriv.PublicKey = *ecdsaPub
  454. buf := bytes.NewBuffer(data)
  455. d, _, err := readMPI(buf)
  456. if err != nil {
  457. return
  458. }
  459. ecdsaPriv.D = new(big.Int).SetBytes(d)
  460. pk.PrivateKey = ecdsaPriv
  461. pk.Encrypted = false
  462. pk.encryptedData = nil
  463. return nil
  464. }
  465. func (pk *PrivateKey) parseEdDSAPrivateKey(data []byte) (err error) {
  466. eddsaPriv := new(EdDSAPrivateKey)
  467. eddsaPriv.PublicKey = pk.PublicKey
  468. buf := bytes.NewBuffer(data)
  469. eddsaPriv.seed.bytes, eddsaPriv.seed.bitLength, err = readMPI(buf)
  470. if err != nil {
  471. return err
  472. }
  473. if bLen := len(eddsaPriv.seed.bytes); bLen != 32 { // 32 bytes private part of ed25519 key.
  474. return errors.UnsupportedError(fmt.Sprintf("Unexpected EdDSA private key length: %d", bLen))
  475. }
  476. pk.PrivateKey = eddsaPriv
  477. pk.Encrypted = false
  478. pk.encryptedData = nil
  479. return nil
  480. }