keys.go 14 KB

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