keys.go 17 KB

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