keys.go 20 KB

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