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

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