keys.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. // Copyright 2012 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 ssh
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/dsa"
  9. "crypto/ecdsa"
  10. "crypto/elliptic"
  11. "crypto/rsa"
  12. "crypto/x509"
  13. "encoding/asn1"
  14. "encoding/base64"
  15. "encoding/pem"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "math/big"
  20. )
  21. // These constants represent the algorithm names for key types supported by this
  22. // package.
  23. const (
  24. KeyAlgoRSA = "ssh-rsa"
  25. KeyAlgoDSA = "ssh-dss"
  26. KeyAlgoECDSA256 = "ecdsa-sha2-nistp256"
  27. KeyAlgoECDSA384 = "ecdsa-sha2-nistp384"
  28. KeyAlgoECDSA521 = "ecdsa-sha2-nistp521"
  29. )
  30. // parsePubKey parses a public key of the given algorithm.
  31. // Use ParsePublicKey for keys with prepended algorithm.
  32. func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, ok bool) {
  33. switch algo {
  34. case KeyAlgoRSA:
  35. return parseRSA(in)
  36. case KeyAlgoDSA:
  37. return parseDSA(in)
  38. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  39. return parseECDSA(in)
  40. case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  41. return parseOpenSSHCertV01(in, algo)
  42. }
  43. return nil, nil, false
  44. }
  45. // parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
  46. // (see sshd(8) manual page) once the options and key type fields have been
  47. // removed.
  48. func parseAuthorizedKey(in []byte) (out PublicKey, comment string, ok bool) {
  49. in = bytes.TrimSpace(in)
  50. i := bytes.IndexAny(in, " \t")
  51. if i == -1 {
  52. i = len(in)
  53. }
  54. base64Key := in[:i]
  55. key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key)))
  56. n, err := base64.StdEncoding.Decode(key, base64Key)
  57. if err != nil {
  58. return
  59. }
  60. key = key[:n]
  61. out, _, ok = ParsePublicKey(key)
  62. if !ok {
  63. return nil, "", false
  64. }
  65. comment = string(bytes.TrimSpace(in[i:]))
  66. return
  67. }
  68. // ParseAuthorizedKeys parses a public key from an authorized_keys
  69. // file used in OpenSSH according to the sshd(8) manual page.
  70. func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, ok bool) {
  71. for len(in) > 0 {
  72. end := bytes.IndexByte(in, '\n')
  73. if end != -1 {
  74. rest = in[end+1:]
  75. in = in[:end]
  76. } else {
  77. rest = nil
  78. }
  79. end = bytes.IndexByte(in, '\r')
  80. if end != -1 {
  81. in = in[:end]
  82. }
  83. in = bytes.TrimSpace(in)
  84. if len(in) == 0 || in[0] == '#' {
  85. in = rest
  86. continue
  87. }
  88. i := bytes.IndexAny(in, " \t")
  89. if i == -1 {
  90. in = rest
  91. continue
  92. }
  93. field := string(in[:i])
  94. switch field {
  95. case KeyAlgoRSA, KeyAlgoDSA:
  96. out, comment, ok = parseAuthorizedKey(in[i:])
  97. if ok {
  98. return
  99. }
  100. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  101. // We don't support these keys.
  102. in = rest
  103. continue
  104. case CertAlgoRSAv01, CertAlgoDSAv01,
  105. CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  106. // We don't support these certificates.
  107. in = rest
  108. continue
  109. }
  110. // No key type recognised. Maybe there's an options field at
  111. // the beginning.
  112. var b byte
  113. inQuote := false
  114. var candidateOptions []string
  115. optionStart := 0
  116. for i, b = range in {
  117. isEnd := !inQuote && (b == ' ' || b == '\t')
  118. if (b == ',' && !inQuote) || isEnd {
  119. if i-optionStart > 0 {
  120. candidateOptions = append(candidateOptions, string(in[optionStart:i]))
  121. }
  122. optionStart = i + 1
  123. }
  124. if isEnd {
  125. break
  126. }
  127. if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) {
  128. inQuote = !inQuote
  129. }
  130. }
  131. for i < len(in) && (in[i] == ' ' || in[i] == '\t') {
  132. i++
  133. }
  134. if i == len(in) {
  135. // Invalid line: unmatched quote
  136. in = rest
  137. continue
  138. }
  139. in = in[i:]
  140. i = bytes.IndexAny(in, " \t")
  141. if i == -1 {
  142. in = rest
  143. continue
  144. }
  145. field = string(in[:i])
  146. switch field {
  147. case KeyAlgoRSA, KeyAlgoDSA:
  148. out, comment, ok = parseAuthorizedKey(in[i:])
  149. if ok {
  150. options = candidateOptions
  151. return
  152. }
  153. }
  154. in = rest
  155. continue
  156. }
  157. return
  158. }
  159. // ParsePublicKey parses an SSH public key formatted for use in
  160. // the SSH wire protocol according to RFC 4253, section 6.6.
  161. func ParsePublicKey(in []byte) (out PublicKey, rest []byte, ok bool) {
  162. algo, in, ok := parseString(in)
  163. if !ok {
  164. return
  165. }
  166. return parsePubKey(in, string(algo))
  167. }
  168. // MarshalAuthorizedKey returns a byte stream suitable for inclusion
  169. // in an OpenSSH authorized_keys file following the format specified
  170. // in the sshd(8) manual page.
  171. func MarshalAuthorizedKey(key PublicKey) []byte {
  172. b := &bytes.Buffer{}
  173. b.WriteString(key.PublicKeyAlgo())
  174. b.WriteByte(' ')
  175. e := base64.NewEncoder(base64.StdEncoding, b)
  176. e.Write(MarshalPublicKey(key))
  177. e.Close()
  178. b.WriteByte('\n')
  179. return b.Bytes()
  180. }
  181. // PublicKey is an abstraction of different types of public keys.
  182. type PublicKey interface {
  183. // PrivateKeyAlgo returns the name of the encryption system.
  184. PrivateKeyAlgo() string
  185. // PublicKeyAlgo returns the algorithm for the public key,
  186. // which may be different from PrivateKeyAlgo for certificates.
  187. PublicKeyAlgo() string
  188. // Marshal returns the serialized key data in SSH wire format,
  189. // without the name prefix. Callers should typically use
  190. // MarshalPublicKey().
  191. Marshal() []byte
  192. // Verify that sig is a signature on the given data using this
  193. // key. This function will hash the data appropriately first.
  194. Verify(data []byte, sigBlob []byte) bool
  195. }
  196. // A Signer is can create signatures that verify against a public key.
  197. type Signer interface {
  198. // PublicKey returns an associated PublicKey instance.
  199. PublicKey() PublicKey
  200. // Sign returns raw signature for the given data. This method
  201. // will apply the hash specified for the keytype to the data.
  202. Sign(rand io.Reader, data []byte) ([]byte, error)
  203. }
  204. type rsaPublicKey rsa.PublicKey
  205. func (r *rsaPublicKey) PrivateKeyAlgo() string {
  206. return "ssh-rsa"
  207. }
  208. func (r *rsaPublicKey) PublicKeyAlgo() string {
  209. return r.PrivateKeyAlgo()
  210. }
  211. // parseRSA parses an RSA key according to RFC 4253, section 6.6.
  212. func parseRSA(in []byte) (out PublicKey, rest []byte, ok bool) {
  213. key := new(rsa.PublicKey)
  214. bigE, in, ok := parseInt(in)
  215. if !ok || bigE.BitLen() > 24 {
  216. return
  217. }
  218. e := bigE.Int64()
  219. if e < 3 || e&1 == 0 {
  220. ok = false
  221. return
  222. }
  223. key.E = int(e)
  224. if key.N, in, ok = parseInt(in); !ok {
  225. return
  226. }
  227. ok = true
  228. return (*rsaPublicKey)(key), in, ok
  229. }
  230. func (r *rsaPublicKey) Marshal() []byte {
  231. // See RFC 4253, section 6.6.
  232. e := new(big.Int).SetInt64(int64(r.E))
  233. length := intLength(e)
  234. length += intLength(r.N)
  235. ret := make([]byte, length)
  236. rest := marshalInt(ret, e)
  237. marshalInt(rest, r.N)
  238. return ret
  239. }
  240. func (r *rsaPublicKey) Verify(data []byte, sig []byte) bool {
  241. h := crypto.SHA1.New()
  242. h.Write(data)
  243. digest := h.Sum(nil)
  244. return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), crypto.SHA1, digest, sig) == nil
  245. }
  246. type rsaPrivateKey struct {
  247. *rsa.PrivateKey
  248. }
  249. func (r *rsaPrivateKey) PublicKey() PublicKey {
  250. return (*rsaPublicKey)(&r.PrivateKey.PublicKey)
  251. }
  252. func (r *rsaPrivateKey) Sign(rand io.Reader, data []byte) ([]byte, error) {
  253. h := crypto.SHA1.New()
  254. h.Write(data)
  255. digest := h.Sum(nil)
  256. return rsa.SignPKCS1v15(rand, r.PrivateKey, crypto.SHA1, digest)
  257. }
  258. type dsaPublicKey dsa.PublicKey
  259. func (r *dsaPublicKey) PrivateKeyAlgo() string {
  260. return "ssh-dss"
  261. }
  262. func (r *dsaPublicKey) PublicKeyAlgo() string {
  263. return r.PrivateKeyAlgo()
  264. }
  265. // parseDSA parses an DSA key according to RFC 4253, section 6.6.
  266. func parseDSA(in []byte) (out PublicKey, rest []byte, ok bool) {
  267. key := new(dsa.PublicKey)
  268. if key.P, in, ok = parseInt(in); !ok {
  269. return
  270. }
  271. if key.Q, in, ok = parseInt(in); !ok {
  272. return
  273. }
  274. if key.G, in, ok = parseInt(in); !ok {
  275. return
  276. }
  277. if key.Y, in, ok = parseInt(in); !ok {
  278. return
  279. }
  280. ok = true
  281. return (*dsaPublicKey)(key), in, ok
  282. }
  283. func (r *dsaPublicKey) Marshal() []byte {
  284. // See RFC 4253, section 6.6.
  285. length := intLength(r.P)
  286. length += intLength(r.Q)
  287. length += intLength(r.G)
  288. length += intLength(r.Y)
  289. ret := make([]byte, length)
  290. rest := marshalInt(ret, r.P)
  291. rest = marshalInt(rest, r.Q)
  292. rest = marshalInt(rest, r.G)
  293. marshalInt(rest, r.Y)
  294. return ret
  295. }
  296. func (k *dsaPublicKey) Verify(data []byte, sigBlob []byte) bool {
  297. h := crypto.SHA1.New()
  298. h.Write(data)
  299. digest := h.Sum(nil)
  300. // Per RFC 4253, section 6.6,
  301. // The value for 'dss_signature_blob' is encoded as a string containing
  302. // r, followed by s (which are 160-bit integers, without lengths or
  303. // padding, unsigned, and in network byte order).
  304. // For DSS purposes, sig.Blob should be exactly 40 bytes in length.
  305. if len(sigBlob) != 40 {
  306. return false
  307. }
  308. r := new(big.Int).SetBytes(sigBlob[:20])
  309. s := new(big.Int).SetBytes(sigBlob[20:])
  310. return dsa.Verify((*dsa.PublicKey)(k), digest, r, s)
  311. }
  312. type dsaPrivateKey struct {
  313. *dsa.PrivateKey
  314. }
  315. func (k *dsaPrivateKey) PublicKey() PublicKey {
  316. return (*dsaPublicKey)(&k.PrivateKey.PublicKey)
  317. }
  318. func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) ([]byte, error) {
  319. h := crypto.SHA1.New()
  320. h.Write(data)
  321. digest := h.Sum(nil)
  322. r, s, err := dsa.Sign(rand, k.PrivateKey, digest)
  323. if err != nil {
  324. return nil, err
  325. }
  326. sig := make([]byte, 40)
  327. copy(sig[:20], r.Bytes())
  328. copy(sig[20:], s.Bytes())
  329. return sig, nil
  330. }
  331. type ecdsaPublicKey ecdsa.PublicKey
  332. func (key *ecdsaPublicKey) PrivateKeyAlgo() string {
  333. return "ecdsa-sha2-" + key.nistID()
  334. }
  335. func (key *ecdsaPublicKey) nistID() string {
  336. switch key.Params().BitSize {
  337. case 256:
  338. return "nistp256"
  339. case 384:
  340. return "nistp384"
  341. case 521:
  342. return "nistp521"
  343. }
  344. panic("ssh: unsupported ecdsa key size")
  345. }
  346. func supportedEllipticCurve(curve elliptic.Curve) bool {
  347. return (curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521())
  348. }
  349. // ecHash returns the hash to match the given elliptic curve, see RFC
  350. // 5656, section 6.2.1
  351. func ecHash(curve elliptic.Curve) crypto.Hash {
  352. bitSize := curve.Params().BitSize
  353. switch {
  354. case bitSize <= 256:
  355. return crypto.SHA256
  356. case bitSize <= 384:
  357. return crypto.SHA384
  358. }
  359. return crypto.SHA512
  360. }
  361. func (key *ecdsaPublicKey) PublicKeyAlgo() string {
  362. return key.PrivateKeyAlgo()
  363. }
  364. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  365. func parseECDSA(in []byte) (out PublicKey, rest []byte, ok bool) {
  366. var identifier []byte
  367. if identifier, in, ok = parseString(in); !ok {
  368. return
  369. }
  370. key := new(ecdsa.PublicKey)
  371. switch string(identifier) {
  372. case "nistp256":
  373. key.Curve = elliptic.P256()
  374. case "nistp384":
  375. key.Curve = elliptic.P384()
  376. case "nistp521":
  377. key.Curve = elliptic.P521()
  378. default:
  379. ok = false
  380. return
  381. }
  382. var keyBytes []byte
  383. if keyBytes, in, ok = parseString(in); !ok {
  384. return
  385. }
  386. key.X, key.Y = elliptic.Unmarshal(key.Curve, keyBytes)
  387. if key.X == nil || key.Y == nil {
  388. ok = false
  389. return
  390. }
  391. return (*ecdsaPublicKey)(key), in, ok
  392. }
  393. func (key *ecdsaPublicKey) Marshal() []byte {
  394. // See RFC 5656, section 3.1.
  395. keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y)
  396. ID := key.nistID()
  397. length := stringLength(len(ID))
  398. length += stringLength(len(keyBytes))
  399. ret := make([]byte, length)
  400. r := marshalString(ret, []byte(ID))
  401. r = marshalString(r, keyBytes)
  402. return ret
  403. }
  404. func (key *ecdsaPublicKey) Verify(data []byte, sigBlob []byte) bool {
  405. h := ecHash(key.Curve).New()
  406. h.Write(data)
  407. digest := h.Sum(nil)
  408. // Per RFC 5656, section 3.1.2,
  409. // The ecdsa_signature_blob value has the following specific encoding:
  410. // mpint r
  411. // mpint s
  412. r, rest, ok := parseInt(sigBlob)
  413. if !ok {
  414. return false
  415. }
  416. s, rest, ok := parseInt(rest)
  417. if !ok || len(rest) > 0 {
  418. return false
  419. }
  420. return ecdsa.Verify((*ecdsa.PublicKey)(key), digest, r, s)
  421. }
  422. type ecdsaPrivateKey struct {
  423. *ecdsa.PrivateKey
  424. }
  425. func (k *ecdsaPrivateKey) PublicKey() PublicKey {
  426. return (*ecdsaPublicKey)(&k.PrivateKey.PublicKey)
  427. }
  428. func (k *ecdsaPrivateKey) Sign(rand io.Reader, data []byte) ([]byte, error) {
  429. h := ecHash(k.PrivateKey.PublicKey.Curve).New()
  430. h.Write(data)
  431. digest := h.Sum(nil)
  432. r, s, err := ecdsa.Sign(rand, k.PrivateKey, digest)
  433. if err != nil {
  434. return nil, err
  435. }
  436. sig := make([]byte, intLength(r)+intLength(s))
  437. rest := marshalInt(sig, r)
  438. marshalInt(rest, s)
  439. return sig, nil
  440. }
  441. // NewPrivateKey takes a pointer to rsa, dsa or ecdsa PrivateKey
  442. // returns a corresponding Signer instance. EC keys should use P256,
  443. // P384 or P521.
  444. func NewSignerFromKey(k interface{}) (Signer, error) {
  445. var sshKey Signer
  446. switch t := k.(type) {
  447. case *rsa.PrivateKey:
  448. sshKey = &rsaPrivateKey{t}
  449. case *dsa.PrivateKey:
  450. sshKey = &dsaPrivateKey{t}
  451. case *ecdsa.PrivateKey:
  452. if !supportedEllipticCurve(t.Curve) {
  453. return nil, errors.New("ssh: only P256, P384 and P521 EC keys are supported.")
  454. }
  455. sshKey = &ecdsaPrivateKey{t}
  456. default:
  457. return nil, fmt.Errorf("ssh: unsupported key type %T", k)
  458. }
  459. return sshKey, nil
  460. }
  461. // NewPublicKey takes a pointer to rsa, dsa or ecdsa PublicKey
  462. // and returns a corresponding ssh PublicKey instance. EC keys should use P256, P384 or P521.
  463. func NewPublicKey(k interface{}) (PublicKey, error) {
  464. var sshKey PublicKey
  465. switch t := k.(type) {
  466. case *rsa.PublicKey:
  467. sshKey = (*rsaPublicKey)(t)
  468. case *ecdsa.PublicKey:
  469. if !supportedEllipticCurve(t.Curve) {
  470. return nil, errors.New("ssh: only P256, P384 and P521 EC keys are supported.")
  471. }
  472. sshKey = (*ecdsaPublicKey)(t)
  473. case *dsa.PublicKey:
  474. sshKey = (*dsaPublicKey)(t)
  475. default:
  476. return nil, fmt.Errorf("ssh: unsupported key type %T", k)
  477. }
  478. return sshKey, nil
  479. }
  480. // ParsePublicKey parses a PEM encoded private key. It supports
  481. // PKCS#1, RSA, DSA and ECDSA private keys.
  482. func ParsePrivateKey(pemBytes []byte) (Signer, error) {
  483. block, _ := pem.Decode(pemBytes)
  484. if block == nil {
  485. return nil, errors.New("ssh: no key found")
  486. }
  487. var rawkey interface{}
  488. switch block.Type {
  489. case "RSA PRIVATE KEY":
  490. rsa, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  491. if err != nil {
  492. return nil, err
  493. }
  494. rawkey = rsa
  495. case "EC PRIVATE KEY":
  496. ec, err := x509.ParseECPrivateKey(block.Bytes)
  497. if err != nil {
  498. return nil, err
  499. }
  500. rawkey = ec
  501. case "DSA PRIVATE KEY":
  502. ec, err := parseDSAPrivate(block.Bytes)
  503. if err != nil {
  504. return nil, err
  505. }
  506. rawkey = ec
  507. default:
  508. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  509. }
  510. return NewSignerFromKey(rawkey)
  511. }
  512. // parseDSAPrivate parses a DSA key in ASN.1 DER encoding, as
  513. // documented in the OpenSSL DSA manpage.
  514. // TODO(hanwen): move this in to crypto/x509 after the Go 1.2 freeze.
  515. func parseDSAPrivate(p []byte) (*dsa.PrivateKey, error) {
  516. k := struct {
  517. Version int
  518. P *big.Int
  519. Q *big.Int
  520. G *big.Int
  521. Priv *big.Int
  522. Pub *big.Int
  523. }{}
  524. rest, err := asn1.Unmarshal(p, &k)
  525. if err != nil {
  526. return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
  527. }
  528. if len(rest) > 0 {
  529. return nil, errors.New("ssh: garbage after DSA key")
  530. }
  531. return &dsa.PrivateKey{
  532. PublicKey: dsa.PublicKey{
  533. Parameters: dsa.Parameters{
  534. P: k.P,
  535. Q: k.Q,
  536. G: k.G,
  537. },
  538. Y: k.Priv,
  539. },
  540. X: k.Pub,
  541. }, nil
  542. }