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.

628 lines
15 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/rsa"
  12. "crypto/x509"
  13. "encoding/asn1"
  14. "encoding/base64"
  15. "encoding/pem"
  16. "errors"
  17. "fmt"
  18. "io"
  19. "math/big"
  20. )
  21. // These constants represent the algorithm names for key types supported by this
  22. // package.
  23. const (
  24. KeyAlgoRSA = "ssh-rsa"
  25. KeyAlgoDSA = "ssh-dss"
  26. KeyAlgoECDSA256 = "ecdsa-sha2-nistp256"
  27. KeyAlgoECDSA384 = "ecdsa-sha2-nistp384"
  28. KeyAlgoECDSA521 = "ecdsa-sha2-nistp521"
  29. )
  30. // parsePubKey parses a public key of the given algorithm.
  31. // Use ParsePublicKey for keys with prepended algorithm.
  32. func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err error) {
  33. switch algo {
  34. case KeyAlgoRSA:
  35. return parseRSA(in)
  36. case KeyAlgoDSA:
  37. return parseDSA(in)
  38. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  39. return parseECDSA(in)
  40. case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
  41. cert, err := parseCert(in, certToPrivAlgo(algo))
  42. if err != nil {
  43. return nil, nil, err
  44. }
  45. return cert, nil, nil
  46. }
  47. return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", err)
  48. }
  49. // parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
  50. // (see sshd(8) manual page) once the options and key type fields have been
  51. // removed.
  52. func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) {
  53. in = bytes.TrimSpace(in)
  54. i := bytes.IndexAny(in, " \t")
  55. if i == -1 {
  56. i = len(in)
  57. }
  58. base64Key := in[:i]
  59. key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key)))
  60. n, err := base64.StdEncoding.Decode(key, base64Key)
  61. if err != nil {
  62. return nil, "", err
  63. }
  64. key = key[:n]
  65. out, err = ParsePublicKey(key)
  66. if err != nil {
  67. return nil, "", err
  68. }
  69. comment = string(bytes.TrimSpace(in[i:]))
  70. return out, comment, nil
  71. }
  72. // ParseAuthorizedKeys parses a public key from an authorized_keys
  73. // file used in OpenSSH according to the sshd(8) manual page.
  74. func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) {
  75. for len(in) > 0 {
  76. end := bytes.IndexByte(in, '\n')
  77. if end != -1 {
  78. rest = in[end+1:]
  79. in = in[:end]
  80. } else {
  81. rest = nil
  82. }
  83. end = bytes.IndexByte(in, '\r')
  84. if end != -1 {
  85. in = in[:end]
  86. }
  87. in = bytes.TrimSpace(in)
  88. if len(in) == 0 || in[0] == '#' {
  89. in = rest
  90. continue
  91. }
  92. i := bytes.IndexAny(in, " \t")
  93. if i == -1 {
  94. in = rest
  95. continue
  96. }
  97. if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
  98. return out, comment, options, rest, nil
  99. }
  100. // No key type recognised. Maybe there's an options field at
  101. // the beginning.
  102. var b byte
  103. inQuote := false
  104. var candidateOptions []string
  105. optionStart := 0
  106. for i, b = range in {
  107. isEnd := !inQuote && (b == ' ' || b == '\t')
  108. if (b == ',' && !inQuote) || isEnd {
  109. if i-optionStart > 0 {
  110. candidateOptions = append(candidateOptions, string(in[optionStart:i]))
  111. }
  112. optionStart = i + 1
  113. }
  114. if isEnd {
  115. break
  116. }
  117. if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) {
  118. inQuote = !inQuote
  119. }
  120. }
  121. for i < len(in) && (in[i] == ' ' || in[i] == '\t') {
  122. i++
  123. }
  124. if i == len(in) {
  125. // Invalid line: unmatched quote
  126. in = rest
  127. continue
  128. }
  129. in = in[i:]
  130. i = bytes.IndexAny(in, " \t")
  131. if i == -1 {
  132. in = rest
  133. continue
  134. }
  135. if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
  136. options = candidateOptions
  137. return out, comment, options, rest, nil
  138. }
  139. in = rest
  140. continue
  141. }
  142. return nil, "", nil, nil, errors.New("ssh: no key found")
  143. }
  144. // ParsePublicKey parses an SSH public key formatted for use in
  145. // the SSH wire protocol according to RFC 4253, section 6.6.
  146. func ParsePublicKey(in []byte) (out PublicKey, err error) {
  147. algo, in, ok := parseString(in)
  148. if !ok {
  149. return nil, errShortRead
  150. }
  151. var rest []byte
  152. out, rest, err = parsePubKey(in, string(algo))
  153. if len(rest) > 0 {
  154. return nil, errors.New("ssh: trailing junk in public key")
  155. }
  156. return out, err
  157. }
  158. // MarshalAuthorizedKey serializes key for inclusion in an OpenSSH
  159. // authorized_keys file. The return value ends with newline.
  160. func MarshalAuthorizedKey(key PublicKey) []byte {
  161. b := &bytes.Buffer{}
  162. b.WriteString(key.Type())
  163. b.WriteByte(' ')
  164. e := base64.NewEncoder(base64.StdEncoding, b)
  165. e.Write(key.Marshal())
  166. e.Close()
  167. b.WriteByte('\n')
  168. return b.Bytes()
  169. }
  170. // PublicKey is an abstraction of different types of public keys.
  171. type PublicKey interface {
  172. // Type returns the key's type, e.g. "ssh-rsa".
  173. Type() string
  174. // Marshal returns the serialized key data in SSH wire format,
  175. // with the name prefix.
  176. Marshal() []byte
  177. // Verify that sig is a signature on the given data using this
  178. // key. This function will hash the data appropriately first.
  179. Verify(data []byte, sig *Signature) error
  180. }
  181. // A Signer can create signatures that verify against a public key.
  182. type Signer interface {
  183. // PublicKey returns an associated PublicKey instance.
  184. PublicKey() PublicKey
  185. // Sign returns raw signature for the given data. This method
  186. // will apply the hash specified for the keytype to the data.
  187. Sign(rand io.Reader, data []byte) (*Signature, error)
  188. }
  189. type rsaPublicKey rsa.PublicKey
  190. func (r *rsaPublicKey) Type() string {
  191. return "ssh-rsa"
  192. }
  193. // parseRSA parses an RSA key according to RFC 4253, section 6.6.
  194. func parseRSA(in []byte) (out PublicKey, rest []byte, err error) {
  195. var w struct {
  196. E *big.Int
  197. N *big.Int
  198. Rest []byte `ssh:"rest"`
  199. }
  200. if err := Unmarshal(in, &w); err != nil {
  201. return nil, nil, err
  202. }
  203. if w.E.BitLen() > 24 {
  204. return nil, nil, errors.New("ssh: exponent too large")
  205. }
  206. e := w.E.Int64()
  207. if e < 3 || e&1 == 0 {
  208. return nil, nil, errors.New("ssh: incorrect exponent")
  209. }
  210. var key rsa.PublicKey
  211. key.E = int(e)
  212. key.N = w.N
  213. return (*rsaPublicKey)(&key), w.Rest, nil
  214. }
  215. func (r *rsaPublicKey) Marshal() []byte {
  216. e := new(big.Int).SetInt64(int64(r.E))
  217. wirekey := struct {
  218. Name string
  219. E *big.Int
  220. N *big.Int
  221. }{
  222. KeyAlgoRSA,
  223. e,
  224. r.N,
  225. }
  226. return Marshal(&wirekey)
  227. }
  228. func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error {
  229. if sig.Format != r.Type() {
  230. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type())
  231. }
  232. h := crypto.SHA1.New()
  233. h.Write(data)
  234. digest := h.Sum(nil)
  235. return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), crypto.SHA1, digest, sig.Blob)
  236. }
  237. type rsaPrivateKey struct {
  238. *rsa.PrivateKey
  239. }
  240. func (r *rsaPrivateKey) PublicKey() PublicKey {
  241. return (*rsaPublicKey)(&r.PrivateKey.PublicKey)
  242. }
  243. func (r *rsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) {
  244. h := crypto.SHA1.New()
  245. h.Write(data)
  246. digest := h.Sum(nil)
  247. blob, err := rsa.SignPKCS1v15(rand, r.PrivateKey, crypto.SHA1, digest)
  248. if err != nil {
  249. return nil, err
  250. }
  251. return &Signature{
  252. Format: r.PublicKey().Type(),
  253. Blob: blob,
  254. }, nil
  255. }
  256. type dsaPublicKey dsa.PublicKey
  257. func (r *dsaPublicKey) Type() string {
  258. return "ssh-dss"
  259. }
  260. // parseDSA parses an DSA key according to RFC 4253, section 6.6.
  261. func parseDSA(in []byte) (out PublicKey, rest []byte, err error) {
  262. var w struct {
  263. P, Q, G, Y *big.Int
  264. Rest []byte `ssh:"rest"`
  265. }
  266. if err := Unmarshal(in, &w); err != nil {
  267. return nil, nil, err
  268. }
  269. key := &dsaPublicKey{
  270. Parameters: dsa.Parameters{
  271. P: w.P,
  272. Q: w.Q,
  273. G: w.G,
  274. },
  275. Y: w.Y,
  276. }
  277. return key, w.Rest, nil
  278. }
  279. func (k *dsaPublicKey) Marshal() []byte {
  280. w := struct {
  281. Name string
  282. P, Q, G, Y *big.Int
  283. }{
  284. k.Type(),
  285. k.P,
  286. k.Q,
  287. k.G,
  288. k.Y,
  289. }
  290. return Marshal(&w)
  291. }
  292. func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error {
  293. if sig.Format != k.Type() {
  294. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  295. }
  296. h := crypto.SHA1.New()
  297. h.Write(data)
  298. digest := h.Sum(nil)
  299. // Per RFC 4253, section 6.6,
  300. // The value for 'dss_signature_blob' is encoded as a string containing
  301. // r, followed by s (which are 160-bit integers, without lengths or
  302. // padding, unsigned, and in network byte order).
  303. // For DSS purposes, sig.Blob should be exactly 40 bytes in length.
  304. if len(sig.Blob) != 40 {
  305. return errors.New("ssh: DSA signature parse error")
  306. }
  307. r := new(big.Int).SetBytes(sig.Blob[:20])
  308. s := new(big.Int).SetBytes(sig.Blob[20:])
  309. if dsa.Verify((*dsa.PublicKey)(k), digest, r, s) {
  310. return nil
  311. }
  312. return errors.New("ssh: signature did not verify")
  313. }
  314. type dsaPrivateKey struct {
  315. *dsa.PrivateKey
  316. }
  317. func (k *dsaPrivateKey) PublicKey() PublicKey {
  318. return (*dsaPublicKey)(&k.PrivateKey.PublicKey)
  319. }
  320. func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) {
  321. h := crypto.SHA1.New()
  322. h.Write(data)
  323. digest := h.Sum(nil)
  324. r, s, err := dsa.Sign(rand, k.PrivateKey, digest)
  325. if err != nil {
  326. return nil, err
  327. }
  328. sig := make([]byte, 40)
  329. rb := r.Bytes()
  330. sb := s.Bytes()
  331. copy(sig[20-len(rb):20], rb)
  332. copy(sig[40-len(sb):], sb)
  333. return &Signature{
  334. Format: k.PublicKey().Type(),
  335. Blob: sig,
  336. }, nil
  337. }
  338. type ecdsaPublicKey ecdsa.PublicKey
  339. func (key *ecdsaPublicKey) Type() string {
  340. return "ecdsa-sha2-" + key.nistID()
  341. }
  342. func (key *ecdsaPublicKey) nistID() string {
  343. switch key.Params().BitSize {
  344. case 256:
  345. return "nistp256"
  346. case 384:
  347. return "nistp384"
  348. case 521:
  349. return "nistp521"
  350. }
  351. panic("ssh: unsupported ecdsa key size")
  352. }
  353. func supportedEllipticCurve(curve elliptic.Curve) bool {
  354. return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521()
  355. }
  356. // ecHash returns the hash to match the given elliptic curve, see RFC
  357. // 5656, section 6.2.1
  358. func ecHash(curve elliptic.Curve) crypto.Hash {
  359. bitSize := curve.Params().BitSize
  360. switch {
  361. case bitSize <= 256:
  362. return crypto.SHA256
  363. case bitSize <= 384:
  364. return crypto.SHA384
  365. }
  366. return crypto.SHA512
  367. }
  368. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  369. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  370. var w struct {
  371. Curve string
  372. KeyBytes []byte
  373. Rest []byte `ssh:"rest"`
  374. }
  375. if err := Unmarshal(in, &w); err != nil {
  376. return nil, nil, err
  377. }
  378. key := new(ecdsa.PublicKey)
  379. switch w.Curve {
  380. case "nistp256":
  381. key.Curve = elliptic.P256()
  382. case "nistp384":
  383. key.Curve = elliptic.P384()
  384. case "nistp521":
  385. key.Curve = elliptic.P521()
  386. default:
  387. return nil, nil, errors.New("ssh: unsupported curve")
  388. }
  389. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  390. if key.X == nil || key.Y == nil {
  391. return nil, nil, errors.New("ssh: invalid curve point")
  392. }
  393. return (*ecdsaPublicKey)(key), w.Rest, nil
  394. }
  395. func (key *ecdsaPublicKey) Marshal() []byte {
  396. // See RFC 5656, section 3.1.
  397. keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y)
  398. w := struct {
  399. Name string
  400. ID string
  401. Key []byte
  402. }{
  403. key.Type(),
  404. key.nistID(),
  405. keyBytes,
  406. }
  407. return Marshal(&w)
  408. }
  409. func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error {
  410. if sig.Format != key.Type() {
  411. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type())
  412. }
  413. h := ecHash(key.Curve).New()
  414. h.Write(data)
  415. digest := h.Sum(nil)
  416. // Per RFC 5656, section 3.1.2,
  417. // The ecdsa_signature_blob value has the following specific encoding:
  418. // mpint r
  419. // mpint s
  420. var ecSig struct {
  421. R *big.Int
  422. S *big.Int
  423. }
  424. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  425. return err
  426. }
  427. if ecdsa.Verify((*ecdsa.PublicKey)(key), digest, ecSig.R, ecSig.S) {
  428. return nil
  429. }
  430. return errors.New("ssh: signature did not verify")
  431. }
  432. type ecdsaPrivateKey struct {
  433. *ecdsa.PrivateKey
  434. }
  435. func (k *ecdsaPrivateKey) PublicKey() PublicKey {
  436. return (*ecdsaPublicKey)(&k.PrivateKey.PublicKey)
  437. }
  438. func (k *ecdsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) {
  439. h := ecHash(k.PrivateKey.PublicKey.Curve).New()
  440. h.Write(data)
  441. digest := h.Sum(nil)
  442. r, s, err := ecdsa.Sign(rand, k.PrivateKey, digest)
  443. if err != nil {
  444. return nil, err
  445. }
  446. sig := make([]byte, intLength(r)+intLength(s))
  447. rest := marshalInt(sig, r)
  448. marshalInt(rest, s)
  449. return &Signature{
  450. Format: k.PublicKey().Type(),
  451. Blob: sig,
  452. }, nil
  453. }
  454. // NewSignerFromKey takes a pointer to rsa, dsa or ecdsa PrivateKey
  455. // returns a corresponding Signer instance. EC keys should use P256,
  456. // P384 or P521.
  457. func NewSignerFromKey(k interface{}) (Signer, error) {
  458. var sshKey Signer
  459. switch t := k.(type) {
  460. case *rsa.PrivateKey:
  461. sshKey = &rsaPrivateKey{t}
  462. case *dsa.PrivateKey:
  463. sshKey = &dsaPrivateKey{t}
  464. case *ecdsa.PrivateKey:
  465. if !supportedEllipticCurve(t.Curve) {
  466. return nil, errors.New("ssh: only P256, P384 and P521 EC keys are supported.")
  467. }
  468. sshKey = &ecdsaPrivateKey{t}
  469. default:
  470. return nil, fmt.Errorf("ssh: unsupported key type %T", k)
  471. }
  472. return sshKey, nil
  473. }
  474. // NewPublicKey takes a pointer to rsa, dsa or ecdsa PublicKey
  475. // and returns a corresponding ssh PublicKey instance. EC keys should use P256, P384 or P521.
  476. func NewPublicKey(k interface{}) (PublicKey, error) {
  477. var sshKey PublicKey
  478. switch t := k.(type) {
  479. case *rsa.PublicKey:
  480. sshKey = (*rsaPublicKey)(t)
  481. case *ecdsa.PublicKey:
  482. if !supportedEllipticCurve(t.Curve) {
  483. return nil, errors.New("ssh: only P256, P384 and P521 EC keys are supported.")
  484. }
  485. sshKey = (*ecdsaPublicKey)(t)
  486. case *dsa.PublicKey:
  487. sshKey = (*dsaPublicKey)(t)
  488. default:
  489. return nil, fmt.Errorf("ssh: unsupported key type %T", k)
  490. }
  491. return sshKey, nil
  492. }
  493. // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports
  494. // the same keys as ParseRawPrivateKey.
  495. func ParsePrivateKey(pemBytes []byte) (Signer, error) {
  496. key, err := ParseRawPrivateKey(pemBytes)
  497. if err != nil {
  498. return nil, err
  499. }
  500. return NewSignerFromKey(key)
  501. }
  502. // ParseRawPrivateKey returns a private key from a PEM encoded private key. It
  503. // supports RSA (PKCS#1), DSA (OpenSSL), and ECDSA private keys.
  504. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
  505. block, _ := pem.Decode(pemBytes)
  506. if block == nil {
  507. return nil, errors.New("ssh: no key found")
  508. }
  509. switch block.Type {
  510. case "RSA PRIVATE KEY":
  511. return x509.ParsePKCS1PrivateKey(block.Bytes)
  512. case "EC PRIVATE KEY":
  513. return x509.ParseECPrivateKey(block.Bytes)
  514. case "DSA PRIVATE KEY":
  515. return ParseDSAPrivateKey(block.Bytes)
  516. default:
  517. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  518. }
  519. }
  520. // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
  521. // specified by the OpenSSL DSA man page.
  522. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
  523. var k struct {
  524. Version int
  525. P *big.Int
  526. Q *big.Int
  527. G *big.Int
  528. Priv *big.Int
  529. Pub *big.Int
  530. }
  531. rest, err := asn1.Unmarshal(der, &k)
  532. if err != nil {
  533. return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
  534. }
  535. if len(rest) > 0 {
  536. return nil, errors.New("ssh: garbage after DSA key")
  537. }
  538. return &dsa.PrivateKey{
  539. PublicKey: dsa.PublicKey{
  540. Parameters: dsa.Parameters{
  541. P: k.P,
  542. Q: k.Q,
  543. G: k.G,
  544. },
  545. Y: k.Priv,
  546. },
  547. X: k.Pub,
  548. }, nil
  549. }