You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

keys.go 22 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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 beginning 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. // CryptoPublicKey, if implemented by a PublicKey,
  250. // returns the underlying crypto.PublicKey form of the key.
  251. type CryptoPublicKey interface {
  252. CryptoPublicKey() crypto.PublicKey
  253. }
  254. // A Signer can create signatures that verify against a public key.
  255. type Signer interface {
  256. // PublicKey returns an associated PublicKey instance.
  257. PublicKey() PublicKey
  258. // Sign returns raw signature for the given data. This method
  259. // will apply the hash specified for the keytype to the data.
  260. Sign(rand io.Reader, data []byte) (*Signature, error)
  261. }
  262. type rsaPublicKey rsa.PublicKey
  263. func (r *rsaPublicKey) Type() string {
  264. return "ssh-rsa"
  265. }
  266. // parseRSA parses an RSA key according to RFC 4253, section 6.6.
  267. func parseRSA(in []byte) (out PublicKey, rest []byte, err error) {
  268. var w struct {
  269. E *big.Int
  270. N *big.Int
  271. Rest []byte `ssh:"rest"`
  272. }
  273. if err := Unmarshal(in, &w); err != nil {
  274. return nil, nil, err
  275. }
  276. if w.E.BitLen() > 24 {
  277. return nil, nil, errors.New("ssh: exponent too large")
  278. }
  279. e := w.E.Int64()
  280. if e < 3 || e&1 == 0 {
  281. return nil, nil, errors.New("ssh: incorrect exponent")
  282. }
  283. var key rsa.PublicKey
  284. key.E = int(e)
  285. key.N = w.N
  286. return (*rsaPublicKey)(&key), w.Rest, nil
  287. }
  288. func (r *rsaPublicKey) Marshal() []byte {
  289. e := new(big.Int).SetInt64(int64(r.E))
  290. // RSA publickey struct layout should match the struct used by
  291. // parseRSACert in the x/crypto/ssh/agent package.
  292. wirekey := struct {
  293. Name string
  294. E *big.Int
  295. N *big.Int
  296. }{
  297. KeyAlgoRSA,
  298. e,
  299. r.N,
  300. }
  301. return Marshal(&wirekey)
  302. }
  303. func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error {
  304. if sig.Format != r.Type() {
  305. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type())
  306. }
  307. h := crypto.SHA1.New()
  308. h.Write(data)
  309. digest := h.Sum(nil)
  310. return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), crypto.SHA1, digest, sig.Blob)
  311. }
  312. func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  313. return (*rsa.PublicKey)(r)
  314. }
  315. type dsaPublicKey dsa.PublicKey
  316. func (r *dsaPublicKey) Type() string {
  317. return "ssh-dss"
  318. }
  319. // parseDSA parses an DSA key according to RFC 4253, section 6.6.
  320. func parseDSA(in []byte) (out PublicKey, rest []byte, err error) {
  321. var w struct {
  322. P, Q, G, Y *big.Int
  323. Rest []byte `ssh:"rest"`
  324. }
  325. if err := Unmarshal(in, &w); err != nil {
  326. return nil, nil, err
  327. }
  328. key := &dsaPublicKey{
  329. Parameters: dsa.Parameters{
  330. P: w.P,
  331. Q: w.Q,
  332. G: w.G,
  333. },
  334. Y: w.Y,
  335. }
  336. return key, w.Rest, nil
  337. }
  338. func (k *dsaPublicKey) Marshal() []byte {
  339. // DSA publickey struct layout should match the struct used by
  340. // parseDSACert in the x/crypto/ssh/agent package.
  341. w := struct {
  342. Name string
  343. P, Q, G, Y *big.Int
  344. }{
  345. k.Type(),
  346. k.P,
  347. k.Q,
  348. k.G,
  349. k.Y,
  350. }
  351. return Marshal(&w)
  352. }
  353. func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error {
  354. if sig.Format != k.Type() {
  355. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  356. }
  357. h := crypto.SHA1.New()
  358. h.Write(data)
  359. digest := h.Sum(nil)
  360. // Per RFC 4253, section 6.6,
  361. // The value for 'dss_signature_blob' is encoded as a string containing
  362. // r, followed by s (which are 160-bit integers, without lengths or
  363. // padding, unsigned, and in network byte order).
  364. // For DSS purposes, sig.Blob should be exactly 40 bytes in length.
  365. if len(sig.Blob) != 40 {
  366. return errors.New("ssh: DSA signature parse error")
  367. }
  368. r := new(big.Int).SetBytes(sig.Blob[:20])
  369. s := new(big.Int).SetBytes(sig.Blob[20:])
  370. if dsa.Verify((*dsa.PublicKey)(k), digest, r, s) {
  371. return nil
  372. }
  373. return errors.New("ssh: signature did not verify")
  374. }
  375. func (k *dsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  376. return (*dsa.PublicKey)(k)
  377. }
  378. type dsaPrivateKey struct {
  379. *dsa.PrivateKey
  380. }
  381. func (k *dsaPrivateKey) PublicKey() PublicKey {
  382. return (*dsaPublicKey)(&k.PrivateKey.PublicKey)
  383. }
  384. func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) {
  385. h := crypto.SHA1.New()
  386. h.Write(data)
  387. digest := h.Sum(nil)
  388. r, s, err := dsa.Sign(rand, k.PrivateKey, digest)
  389. if err != nil {
  390. return nil, err
  391. }
  392. sig := make([]byte, 40)
  393. rb := r.Bytes()
  394. sb := s.Bytes()
  395. copy(sig[20-len(rb):20], rb)
  396. copy(sig[40-len(sb):], sb)
  397. return &Signature{
  398. Format: k.PublicKey().Type(),
  399. Blob: sig,
  400. }, nil
  401. }
  402. type ecdsaPublicKey ecdsa.PublicKey
  403. func (key *ecdsaPublicKey) Type() string {
  404. return "ecdsa-sha2-" + key.nistID()
  405. }
  406. func (key *ecdsaPublicKey) nistID() string {
  407. switch key.Params().BitSize {
  408. case 256:
  409. return "nistp256"
  410. case 384:
  411. return "nistp384"
  412. case 521:
  413. return "nistp521"
  414. }
  415. panic("ssh: unsupported ecdsa key size")
  416. }
  417. type ed25519PublicKey ed25519.PublicKey
  418. func (key ed25519PublicKey) Type() string {
  419. return KeyAlgoED25519
  420. }
  421. func parseED25519(in []byte) (out PublicKey, rest []byte, err error) {
  422. var w struct {
  423. KeyBytes []byte
  424. Rest []byte `ssh:"rest"`
  425. }
  426. if err := Unmarshal(in, &w); err != nil {
  427. return nil, nil, err
  428. }
  429. key := ed25519.PublicKey(w.KeyBytes)
  430. return (ed25519PublicKey)(key), w.Rest, nil
  431. }
  432. func (key ed25519PublicKey) Marshal() []byte {
  433. w := struct {
  434. Name string
  435. KeyBytes []byte
  436. }{
  437. KeyAlgoED25519,
  438. []byte(key),
  439. }
  440. return Marshal(&w)
  441. }
  442. func (key ed25519PublicKey) Verify(b []byte, sig *Signature) error {
  443. if sig.Format != key.Type() {
  444. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type())
  445. }
  446. edKey := (ed25519.PublicKey)(key)
  447. if ok := ed25519.Verify(edKey, b, sig.Blob); !ok {
  448. return errors.New("ssh: signature did not verify")
  449. }
  450. return nil
  451. }
  452. func (k ed25519PublicKey) CryptoPublicKey() crypto.PublicKey {
  453. return ed25519.PublicKey(k)
  454. }
  455. func supportedEllipticCurve(curve elliptic.Curve) bool {
  456. return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521()
  457. }
  458. // ecHash returns the hash to match the given elliptic curve, see RFC
  459. // 5656, section 6.2.1
  460. func ecHash(curve elliptic.Curve) crypto.Hash {
  461. bitSize := curve.Params().BitSize
  462. switch {
  463. case bitSize <= 256:
  464. return crypto.SHA256
  465. case bitSize <= 384:
  466. return crypto.SHA384
  467. }
  468. return crypto.SHA512
  469. }
  470. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  471. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  472. var w struct {
  473. Curve string
  474. KeyBytes []byte
  475. Rest []byte `ssh:"rest"`
  476. }
  477. if err := Unmarshal(in, &w); err != nil {
  478. return nil, nil, err
  479. }
  480. key := new(ecdsa.PublicKey)
  481. switch w.Curve {
  482. case "nistp256":
  483. key.Curve = elliptic.P256()
  484. case "nistp384":
  485. key.Curve = elliptic.P384()
  486. case "nistp521":
  487. key.Curve = elliptic.P521()
  488. default:
  489. return nil, nil, errors.New("ssh: unsupported curve")
  490. }
  491. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  492. if key.X == nil || key.Y == nil {
  493. return nil, nil, errors.New("ssh: invalid curve point")
  494. }
  495. return (*ecdsaPublicKey)(key), w.Rest, nil
  496. }
  497. func (key *ecdsaPublicKey) Marshal() []byte {
  498. // See RFC 5656, section 3.1.
  499. keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y)
  500. // ECDSA publickey struct layout should match the struct used by
  501. // parseECDSACert in the x/crypto/ssh/agent package.
  502. w := struct {
  503. Name string
  504. ID string
  505. Key []byte
  506. }{
  507. key.Type(),
  508. key.nistID(),
  509. keyBytes,
  510. }
  511. return Marshal(&w)
  512. }
  513. func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error {
  514. if sig.Format != key.Type() {
  515. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type())
  516. }
  517. h := ecHash(key.Curve).New()
  518. h.Write(data)
  519. digest := h.Sum(nil)
  520. // Per RFC 5656, section 3.1.2,
  521. // The ecdsa_signature_blob value has the following specific encoding:
  522. // mpint r
  523. // mpint s
  524. var ecSig struct {
  525. R *big.Int
  526. S *big.Int
  527. }
  528. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  529. return err
  530. }
  531. if ecdsa.Verify((*ecdsa.PublicKey)(key), digest, ecSig.R, ecSig.S) {
  532. return nil
  533. }
  534. return errors.New("ssh: signature did not verify")
  535. }
  536. func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  537. return (*ecdsa.PublicKey)(k)
  538. }
  539. // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey,
  540. // *ecdsa.PrivateKey or any other crypto.Signer and returns a corresponding
  541. // Signer instance. ECDSA keys must use P-256, P-384 or P-521.
  542. func NewSignerFromKey(key interface{}) (Signer, error) {
  543. switch key := key.(type) {
  544. case crypto.Signer:
  545. return NewSignerFromSigner(key)
  546. case *dsa.PrivateKey:
  547. return &dsaPrivateKey{key}, nil
  548. default:
  549. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  550. }
  551. }
  552. type wrappedSigner struct {
  553. signer crypto.Signer
  554. pubKey PublicKey
  555. }
  556. // NewSignerFromSigner takes any crypto.Signer implementation and
  557. // returns a corresponding Signer interface. This can be used, for
  558. // example, with keys kept in hardware modules.
  559. func NewSignerFromSigner(signer crypto.Signer) (Signer, error) {
  560. pubKey, err := NewPublicKey(signer.Public())
  561. if err != nil {
  562. return nil, err
  563. }
  564. return &wrappedSigner{signer, pubKey}, nil
  565. }
  566. func (s *wrappedSigner) PublicKey() PublicKey {
  567. return s.pubKey
  568. }
  569. func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  570. var hashFunc crypto.Hash
  571. switch key := s.pubKey.(type) {
  572. case *rsaPublicKey, *dsaPublicKey:
  573. hashFunc = crypto.SHA1
  574. case *ecdsaPublicKey:
  575. hashFunc = ecHash(key.Curve)
  576. case ed25519PublicKey:
  577. default:
  578. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  579. }
  580. var digest []byte
  581. if hashFunc != 0 {
  582. h := hashFunc.New()
  583. h.Write(data)
  584. digest = h.Sum(nil)
  585. } else {
  586. digest = data
  587. }
  588. signature, err := s.signer.Sign(rand, digest, hashFunc)
  589. if err != nil {
  590. return nil, err
  591. }
  592. // crypto.Signer.Sign is expected to return an ASN.1-encoded signature
  593. // for ECDSA and DSA, but that's not the encoding expected by SSH, so
  594. // re-encode.
  595. switch s.pubKey.(type) {
  596. case *ecdsaPublicKey, *dsaPublicKey:
  597. type asn1Signature struct {
  598. R, S *big.Int
  599. }
  600. asn1Sig := new(asn1Signature)
  601. _, err := asn1.Unmarshal(signature, asn1Sig)
  602. if err != nil {
  603. return nil, err
  604. }
  605. switch s.pubKey.(type) {
  606. case *ecdsaPublicKey:
  607. signature = Marshal(asn1Sig)
  608. case *dsaPublicKey:
  609. signature = make([]byte, 40)
  610. r := asn1Sig.R.Bytes()
  611. s := asn1Sig.S.Bytes()
  612. copy(signature[20-len(r):20], r)
  613. copy(signature[40-len(s):40], s)
  614. }
  615. }
  616. return &Signature{
  617. Format: s.pubKey.Type(),
  618. Blob: signature,
  619. }, nil
  620. }
  621. // NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
  622. // or ed25519.PublicKey returns a corresponding PublicKey instance.
  623. // ECDSA keys must use P-256, P-384 or P-521.
  624. func NewPublicKey(key interface{}) (PublicKey, error) {
  625. switch key := key.(type) {
  626. case *rsa.PublicKey:
  627. return (*rsaPublicKey)(key), nil
  628. case *ecdsa.PublicKey:
  629. if !supportedEllipticCurve(key.Curve) {
  630. return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported.")
  631. }
  632. return (*ecdsaPublicKey)(key), nil
  633. case *dsa.PublicKey:
  634. return (*dsaPublicKey)(key), nil
  635. case ed25519.PublicKey:
  636. return (ed25519PublicKey)(key), nil
  637. default:
  638. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  639. }
  640. }
  641. // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports
  642. // the same keys as ParseRawPrivateKey.
  643. func ParsePrivateKey(pemBytes []byte) (Signer, error) {
  644. key, err := ParseRawPrivateKey(pemBytes)
  645. if err != nil {
  646. return nil, err
  647. }
  648. return NewSignerFromKey(key)
  649. }
  650. // encryptedBlock tells whether a private key is
  651. // encrypted by examining its Proc-Type header
  652. // for a mention of ENCRYPTED
  653. // according to RFC 1421 Section 4.6.1.1.
  654. func encryptedBlock(block *pem.Block) bool {
  655. return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED")
  656. }
  657. // ParseRawPrivateKey returns a private key from a PEM encoded private key. It
  658. // supports RSA (PKCS#1), DSA (OpenSSL), and ECDSA private keys.
  659. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
  660. block, _ := pem.Decode(pemBytes)
  661. if block == nil {
  662. return nil, errors.New("ssh: no key found")
  663. }
  664. if encryptedBlock(block) {
  665. return nil, errors.New("ssh: cannot decode encrypted private keys")
  666. }
  667. switch block.Type {
  668. case "RSA PRIVATE KEY":
  669. return x509.ParsePKCS1PrivateKey(block.Bytes)
  670. case "EC PRIVATE KEY":
  671. return x509.ParseECPrivateKey(block.Bytes)
  672. case "DSA PRIVATE KEY":
  673. return ParseDSAPrivateKey(block.Bytes)
  674. case "OPENSSH PRIVATE KEY":
  675. return parseOpenSSHPrivateKey(block.Bytes)
  676. default:
  677. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  678. }
  679. }
  680. // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
  681. // specified by the OpenSSL DSA man page.
  682. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
  683. var k struct {
  684. Version int
  685. P *big.Int
  686. Q *big.Int
  687. G *big.Int
  688. Priv *big.Int
  689. Pub *big.Int
  690. }
  691. rest, err := asn1.Unmarshal(der, &k)
  692. if err != nil {
  693. return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
  694. }
  695. if len(rest) > 0 {
  696. return nil, errors.New("ssh: garbage after DSA key")
  697. }
  698. return &dsa.PrivateKey{
  699. PublicKey: dsa.PublicKey{
  700. Parameters: dsa.Parameters{
  701. P: k.P,
  702. Q: k.Q,
  703. G: k.G,
  704. },
  705. Y: k.Priv,
  706. },
  707. X: k.Pub,
  708. }, nil
  709. }
  710. // Implemented based on the documentation at
  711. // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
  712. func parseOpenSSHPrivateKey(key []byte) (*ed25519.PrivateKey, error) {
  713. magic := append([]byte("openssh-key-v1"), 0)
  714. if !bytes.Equal(magic, key[0:len(magic)]) {
  715. return nil, errors.New("ssh: invalid openssh private key format")
  716. }
  717. remaining := key[len(magic):]
  718. var w struct {
  719. CipherName string
  720. KdfName string
  721. KdfOpts string
  722. NumKeys uint32
  723. PubKey []byte
  724. PrivKeyBlock []byte
  725. }
  726. if err := Unmarshal(remaining, &w); err != nil {
  727. return nil, err
  728. }
  729. pk1 := struct {
  730. Check1 uint32
  731. Check2 uint32
  732. Keytype string
  733. Pub []byte
  734. Priv []byte
  735. Comment string
  736. Pad []byte `ssh:"rest"`
  737. }{}
  738. if err := Unmarshal(w.PrivKeyBlock, &pk1); err != nil {
  739. return nil, err
  740. }
  741. if pk1.Check1 != pk1.Check2 {
  742. return nil, errors.New("ssh: checkint mismatch")
  743. }
  744. // we only handle ed25519 keys currently
  745. if pk1.Keytype != KeyAlgoED25519 {
  746. return nil, errors.New("ssh: unhandled key type")
  747. }
  748. for i, b := range pk1.Pad {
  749. if int(b) != i+1 {
  750. return nil, errors.New("ssh: padding not as expected")
  751. }
  752. }
  753. if len(pk1.Priv) != ed25519.PrivateKeySize {
  754. return nil, errors.New("ssh: private key unexpected length")
  755. }
  756. pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize))
  757. copy(pk, pk1.Priv)
  758. return &pk, nil
  759. }