keys.go 15 KB

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