keys.go 14 KB

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