您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

1033 行
25 KiB

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