keys.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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. // RSA publickey struct layout should match the struct used by
  282. // parseRSACert in the x/crypto/ssh/agent package.
  283. wirekey := struct {
  284. Name string
  285. E *big.Int
  286. N *big.Int
  287. }{
  288. KeyAlgoRSA,
  289. e,
  290. r.N,
  291. }
  292. return Marshal(&wirekey)
  293. }
  294. func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error {
  295. if sig.Format != r.Type() {
  296. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type())
  297. }
  298. h := crypto.SHA1.New()
  299. h.Write(data)
  300. digest := h.Sum(nil)
  301. return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), crypto.SHA1, digest, sig.Blob)
  302. }
  303. type dsaPublicKey dsa.PublicKey
  304. func (r *dsaPublicKey) Type() string {
  305. return "ssh-dss"
  306. }
  307. // parseDSA parses an DSA key according to RFC 4253, section 6.6.
  308. func parseDSA(in []byte) (out PublicKey, rest []byte, err error) {
  309. var w struct {
  310. P, Q, G, Y *big.Int
  311. Rest []byte `ssh:"rest"`
  312. }
  313. if err := Unmarshal(in, &w); err != nil {
  314. return nil, nil, err
  315. }
  316. key := &dsaPublicKey{
  317. Parameters: dsa.Parameters{
  318. P: w.P,
  319. Q: w.Q,
  320. G: w.G,
  321. },
  322. Y: w.Y,
  323. }
  324. return key, w.Rest, nil
  325. }
  326. func (k *dsaPublicKey) Marshal() []byte {
  327. // DSA publickey struct layout should match the struct used by
  328. // parseDSACert in the x/crypto/ssh/agent package.
  329. w := struct {
  330. Name string
  331. P, Q, G, Y *big.Int
  332. }{
  333. k.Type(),
  334. k.P,
  335. k.Q,
  336. k.G,
  337. k.Y,
  338. }
  339. return Marshal(&w)
  340. }
  341. func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error {
  342. if sig.Format != k.Type() {
  343. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  344. }
  345. h := crypto.SHA1.New()
  346. h.Write(data)
  347. digest := h.Sum(nil)
  348. // Per RFC 4253, section 6.6,
  349. // The value for 'dss_signature_blob' is encoded as a string containing
  350. // r, followed by s (which are 160-bit integers, without lengths or
  351. // padding, unsigned, and in network byte order).
  352. // For DSS purposes, sig.Blob should be exactly 40 bytes in length.
  353. if len(sig.Blob) != 40 {
  354. return errors.New("ssh: DSA signature parse error")
  355. }
  356. r := new(big.Int).SetBytes(sig.Blob[:20])
  357. s := new(big.Int).SetBytes(sig.Blob[20:])
  358. if dsa.Verify((*dsa.PublicKey)(k), digest, r, s) {
  359. return nil
  360. }
  361. return errors.New("ssh: signature did not verify")
  362. }
  363. type dsaPrivateKey struct {
  364. *dsa.PrivateKey
  365. }
  366. func (k *dsaPrivateKey) PublicKey() PublicKey {
  367. return (*dsaPublicKey)(&k.PrivateKey.PublicKey)
  368. }
  369. func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) {
  370. h := crypto.SHA1.New()
  371. h.Write(data)
  372. digest := h.Sum(nil)
  373. r, s, err := dsa.Sign(rand, k.PrivateKey, digest)
  374. if err != nil {
  375. return nil, err
  376. }
  377. sig := make([]byte, 40)
  378. rb := r.Bytes()
  379. sb := s.Bytes()
  380. copy(sig[20-len(rb):20], rb)
  381. copy(sig[40-len(sb):], sb)
  382. return &Signature{
  383. Format: k.PublicKey().Type(),
  384. Blob: sig,
  385. }, nil
  386. }
  387. type ecdsaPublicKey ecdsa.PublicKey
  388. func (key *ecdsaPublicKey) Type() string {
  389. return "ecdsa-sha2-" + key.nistID()
  390. }
  391. func (key *ecdsaPublicKey) nistID() string {
  392. switch key.Params().BitSize {
  393. case 256:
  394. return "nistp256"
  395. case 384:
  396. return "nistp384"
  397. case 521:
  398. return "nistp521"
  399. }
  400. panic("ssh: unsupported ecdsa key size")
  401. }
  402. func supportedEllipticCurve(curve elliptic.Curve) bool {
  403. return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521()
  404. }
  405. // ecHash returns the hash to match the given elliptic curve, see RFC
  406. // 5656, section 6.2.1
  407. func ecHash(curve elliptic.Curve) crypto.Hash {
  408. bitSize := curve.Params().BitSize
  409. switch {
  410. case bitSize <= 256:
  411. return crypto.SHA256
  412. case bitSize <= 384:
  413. return crypto.SHA384
  414. }
  415. return crypto.SHA512
  416. }
  417. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  418. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  419. var w struct {
  420. Curve string
  421. KeyBytes []byte
  422. Rest []byte `ssh:"rest"`
  423. }
  424. if err := Unmarshal(in, &w); err != nil {
  425. return nil, nil, err
  426. }
  427. key := new(ecdsa.PublicKey)
  428. switch w.Curve {
  429. case "nistp256":
  430. key.Curve = elliptic.P256()
  431. case "nistp384":
  432. key.Curve = elliptic.P384()
  433. case "nistp521":
  434. key.Curve = elliptic.P521()
  435. default:
  436. return nil, nil, errors.New("ssh: unsupported curve")
  437. }
  438. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  439. if key.X == nil || key.Y == nil {
  440. return nil, nil, errors.New("ssh: invalid curve point")
  441. }
  442. return (*ecdsaPublicKey)(key), w.Rest, nil
  443. }
  444. func (key *ecdsaPublicKey) Marshal() []byte {
  445. // See RFC 5656, section 3.1.
  446. keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y)
  447. // ECDSA publickey struct layout should match the struct used by
  448. // parseECDSACert in the x/crypto/ssh/agent package.
  449. w := struct {
  450. Name string
  451. ID string
  452. Key []byte
  453. }{
  454. key.Type(),
  455. key.nistID(),
  456. keyBytes,
  457. }
  458. return Marshal(&w)
  459. }
  460. func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error {
  461. if sig.Format != key.Type() {
  462. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type())
  463. }
  464. h := ecHash(key.Curve).New()
  465. h.Write(data)
  466. digest := h.Sum(nil)
  467. // Per RFC 5656, section 3.1.2,
  468. // The ecdsa_signature_blob value has the following specific encoding:
  469. // mpint r
  470. // mpint s
  471. var ecSig struct {
  472. R *big.Int
  473. S *big.Int
  474. }
  475. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  476. return err
  477. }
  478. if ecdsa.Verify((*ecdsa.PublicKey)(key), digest, ecSig.R, ecSig.S) {
  479. return nil
  480. }
  481. return errors.New("ssh: signature did not verify")
  482. }
  483. // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey,
  484. // *ecdsa.PrivateKey or any other crypto.Signer and returns a corresponding
  485. // Signer instance. ECDSA keys must use P-256, P-384 or P-521.
  486. func NewSignerFromKey(key interface{}) (Signer, error) {
  487. switch key := key.(type) {
  488. case crypto.Signer:
  489. return NewSignerFromSigner(key)
  490. case *dsa.PrivateKey:
  491. return &dsaPrivateKey{key}, nil
  492. default:
  493. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  494. }
  495. }
  496. type wrappedSigner struct {
  497. signer crypto.Signer
  498. pubKey PublicKey
  499. }
  500. // NewSignerFromSigner takes any crypto.Signer implementation and
  501. // returns a corresponding Signer interface. This can be used, for
  502. // example, with keys kept in hardware modules.
  503. func NewSignerFromSigner(signer crypto.Signer) (Signer, error) {
  504. pubKey, err := NewPublicKey(signer.Public())
  505. if err != nil {
  506. return nil, err
  507. }
  508. return &wrappedSigner{signer, pubKey}, nil
  509. }
  510. func (s *wrappedSigner) PublicKey() PublicKey {
  511. return s.pubKey
  512. }
  513. func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  514. var hashFunc crypto.Hash
  515. switch key := s.pubKey.(type) {
  516. case *rsaPublicKey, *dsaPublicKey:
  517. hashFunc = crypto.SHA1
  518. case *ecdsaPublicKey:
  519. hashFunc = ecHash(key.Curve)
  520. default:
  521. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  522. }
  523. h := hashFunc.New()
  524. h.Write(data)
  525. digest := h.Sum(nil)
  526. signature, err := s.signer.Sign(rand, digest, hashFunc)
  527. if err != nil {
  528. return nil, err
  529. }
  530. // crypto.Signer.Sign is expected to return an ASN.1-encoded signature
  531. // for ECDSA and DSA, but that's not the encoding expected by SSH, so
  532. // re-encode.
  533. switch s.pubKey.(type) {
  534. case *ecdsaPublicKey, *dsaPublicKey:
  535. type asn1Signature struct {
  536. R, S *big.Int
  537. }
  538. asn1Sig := new(asn1Signature)
  539. _, err := asn1.Unmarshal(signature, asn1Sig)
  540. if err != nil {
  541. return nil, err
  542. }
  543. switch s.pubKey.(type) {
  544. case *ecdsaPublicKey:
  545. signature = Marshal(asn1Sig)
  546. case *dsaPublicKey:
  547. signature = make([]byte, 40)
  548. r := asn1Sig.R.Bytes()
  549. s := asn1Sig.S.Bytes()
  550. copy(signature[20-len(r):20], r)
  551. copy(signature[40-len(s):40], s)
  552. }
  553. }
  554. return &Signature{
  555. Format: s.pubKey.Type(),
  556. Blob: signature,
  557. }, nil
  558. }
  559. // NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey or
  560. // any other crypto.Signer and returns a corresponding Signer instance. ECDSA
  561. // keys must use P-256, P-384 or P-521.
  562. func NewPublicKey(key interface{}) (PublicKey, error) {
  563. switch key := key.(type) {
  564. case *rsa.PublicKey:
  565. return (*rsaPublicKey)(key), nil
  566. case *ecdsa.PublicKey:
  567. if !supportedEllipticCurve(key.Curve) {
  568. return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported.")
  569. }
  570. return (*ecdsaPublicKey)(key), nil
  571. case *dsa.PublicKey:
  572. return (*dsaPublicKey)(key), nil
  573. default:
  574. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  575. }
  576. }
  577. // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports
  578. // the same keys as ParseRawPrivateKey.
  579. func ParsePrivateKey(pemBytes []byte) (Signer, error) {
  580. key, err := ParseRawPrivateKey(pemBytes)
  581. if err != nil {
  582. return nil, err
  583. }
  584. return NewSignerFromKey(key)
  585. }
  586. // ParseRawPrivateKey returns a private key from a PEM encoded private key. It
  587. // supports RSA (PKCS#1), DSA (OpenSSL), and ECDSA private keys.
  588. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
  589. block, _ := pem.Decode(pemBytes)
  590. if block == nil {
  591. return nil, errors.New("ssh: no key found")
  592. }
  593. switch block.Type {
  594. case "RSA PRIVATE KEY":
  595. return x509.ParsePKCS1PrivateKey(block.Bytes)
  596. case "EC PRIVATE KEY":
  597. return x509.ParseECPrivateKey(block.Bytes)
  598. case "DSA PRIVATE KEY":
  599. return ParseDSAPrivateKey(block.Bytes)
  600. default:
  601. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  602. }
  603. }
  604. // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
  605. // specified by the OpenSSL DSA man page.
  606. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
  607. var k struct {
  608. Version int
  609. P *big.Int
  610. Q *big.Int
  611. G *big.Int
  612. Priv *big.Int
  613. Pub *big.Int
  614. }
  615. rest, err := asn1.Unmarshal(der, &k)
  616. if err != nil {
  617. return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
  618. }
  619. if len(rest) > 0 {
  620. return nil, errors.New("ssh: garbage after DSA key")
  621. }
  622. return &dsa.PrivateKey{
  623. PublicKey: dsa.PublicKey{
  624. Parameters: dsa.Parameters{
  625. P: k.P,
  626. Q: k.Q,
  627. G: k.G,
  628. },
  629. Y: k.Priv,
  630. },
  631. X: k.Pub,
  632. }, nil
  633. }