keys.go 14 KB

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