keys.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. // These constants represent non-default signature algorithms that are supported
  37. // as algorithm parameters to AlgorithmSigner.SignWithAlgorithm methods. See
  38. // [PROTOCOL.agent] section 4.5.1 and
  39. // https://tools.ietf.org/html/draft-ietf-curdle-rsa-sha2-10
  40. const (
  41. SigAlgoRSA = "ssh-rsa"
  42. SigAlgoRSASHA2256 = "rsa-sha2-256"
  43. SigAlgoRSASHA2512 = "rsa-sha2-512"
  44. )
  45. // parsePubKey parses a public key of the given algorithm.
  46. // Use ParsePublicKey for keys with prepended algorithm.
  47. func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err error) {
  48. switch algo {
  49. case KeyAlgoRSA:
  50. return parseRSA(in)
  51. case KeyAlgoDSA:
  52. return parseDSA(in)
  53. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  54. return parseECDSA(in)
  55. case KeyAlgoED25519:
  56. return parseED25519(in)
  57. case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01:
  58. cert, err := parseCert(in, certToPrivAlgo(algo))
  59. if err != nil {
  60. return nil, nil, err
  61. }
  62. return cert, nil, nil
  63. }
  64. return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", algo)
  65. }
  66. // parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
  67. // (see sshd(8) manual page) once the options and key type fields have been
  68. // removed.
  69. func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) {
  70. in = bytes.TrimSpace(in)
  71. i := bytes.IndexAny(in, " \t")
  72. if i == -1 {
  73. i = len(in)
  74. }
  75. base64Key := in[:i]
  76. key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key)))
  77. n, err := base64.StdEncoding.Decode(key, base64Key)
  78. if err != nil {
  79. return nil, "", err
  80. }
  81. key = key[:n]
  82. out, err = ParsePublicKey(key)
  83. if err != nil {
  84. return nil, "", err
  85. }
  86. comment = string(bytes.TrimSpace(in[i:]))
  87. return out, comment, nil
  88. }
  89. // ParseKnownHosts parses an entry in the format of the known_hosts file.
  90. //
  91. // The known_hosts format is documented in the sshd(8) manual page. This
  92. // function will parse a single entry from in. On successful return, marker
  93. // will contain the optional marker value (i.e. "cert-authority" or "revoked")
  94. // or else be empty, hosts will contain the hosts that this entry matches,
  95. // pubKey will contain the public key and comment will contain any trailing
  96. // comment at the end of the line. See the sshd(8) manual page for the various
  97. // forms that a host string can take.
  98. //
  99. // The unparsed remainder of the input will be returned in rest. This function
  100. // can be called repeatedly to parse multiple entries.
  101. //
  102. // If no entries were found in the input then err will be io.EOF. Otherwise a
  103. // non-nil err value indicates a parse error.
  104. func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey, comment string, rest []byte, err error) {
  105. for len(in) > 0 {
  106. end := bytes.IndexByte(in, '\n')
  107. if end != -1 {
  108. rest = in[end+1:]
  109. in = in[:end]
  110. } else {
  111. rest = nil
  112. }
  113. end = bytes.IndexByte(in, '\r')
  114. if end != -1 {
  115. in = in[:end]
  116. }
  117. in = bytes.TrimSpace(in)
  118. if len(in) == 0 || in[0] == '#' {
  119. in = rest
  120. continue
  121. }
  122. i := bytes.IndexAny(in, " \t")
  123. if i == -1 {
  124. in = rest
  125. continue
  126. }
  127. // Strip out the beginning of the known_host key.
  128. // This is either an optional marker or a (set of) hostname(s).
  129. keyFields := bytes.Fields(in)
  130. if len(keyFields) < 3 || len(keyFields) > 5 {
  131. return "", nil, nil, "", nil, errors.New("ssh: invalid entry in known_hosts data")
  132. }
  133. // keyFields[0] is either "@cert-authority", "@revoked" or a comma separated
  134. // list of hosts
  135. marker := ""
  136. if keyFields[0][0] == '@' {
  137. marker = string(keyFields[0][1:])
  138. keyFields = keyFields[1:]
  139. }
  140. hosts := string(keyFields[0])
  141. // keyFields[1] contains the key type (e.g. “ssh-rsa”).
  142. // However, that information is duplicated inside the
  143. // base64-encoded key and so is ignored here.
  144. key := bytes.Join(keyFields[2:], []byte(" "))
  145. if pubKey, comment, err = parseAuthorizedKey(key); err != nil {
  146. return "", nil, nil, "", nil, err
  147. }
  148. return marker, strings.Split(hosts, ","), pubKey, comment, rest, nil
  149. }
  150. return "", nil, nil, "", nil, io.EOF
  151. }
  152. // ParseAuthorizedKeys parses a public key from an authorized_keys
  153. // file used in OpenSSH according to the sshd(8) manual page.
  154. func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) {
  155. for len(in) > 0 {
  156. end := bytes.IndexByte(in, '\n')
  157. if end != -1 {
  158. rest = in[end+1:]
  159. in = in[:end]
  160. } else {
  161. rest = nil
  162. }
  163. end = bytes.IndexByte(in, '\r')
  164. if end != -1 {
  165. in = in[:end]
  166. }
  167. in = bytes.TrimSpace(in)
  168. if len(in) == 0 || in[0] == '#' {
  169. in = rest
  170. continue
  171. }
  172. i := bytes.IndexAny(in, " \t")
  173. if i == -1 {
  174. in = rest
  175. continue
  176. }
  177. if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
  178. return out, comment, options, rest, nil
  179. }
  180. // No key type recognised. Maybe there's an options field at
  181. // the beginning.
  182. var b byte
  183. inQuote := false
  184. var candidateOptions []string
  185. optionStart := 0
  186. for i, b = range in {
  187. isEnd := !inQuote && (b == ' ' || b == '\t')
  188. if (b == ',' && !inQuote) || isEnd {
  189. if i-optionStart > 0 {
  190. candidateOptions = append(candidateOptions, string(in[optionStart:i]))
  191. }
  192. optionStart = i + 1
  193. }
  194. if isEnd {
  195. break
  196. }
  197. if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) {
  198. inQuote = !inQuote
  199. }
  200. }
  201. for i < len(in) && (in[i] == ' ' || in[i] == '\t') {
  202. i++
  203. }
  204. if i == len(in) {
  205. // Invalid line: unmatched quote
  206. in = rest
  207. continue
  208. }
  209. in = in[i:]
  210. i = bytes.IndexAny(in, " \t")
  211. if i == -1 {
  212. in = rest
  213. continue
  214. }
  215. if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
  216. options = candidateOptions
  217. return out, comment, options, rest, nil
  218. }
  219. in = rest
  220. continue
  221. }
  222. return nil, "", nil, nil, errors.New("ssh: no key found")
  223. }
  224. // ParsePublicKey parses an SSH public key formatted for use in
  225. // the SSH wire protocol according to RFC 4253, section 6.6.
  226. func ParsePublicKey(in []byte) (out PublicKey, err error) {
  227. algo, in, ok := parseString(in)
  228. if !ok {
  229. return nil, errShortRead
  230. }
  231. var rest []byte
  232. out, rest, err = parsePubKey(in, string(algo))
  233. if len(rest) > 0 {
  234. return nil, errors.New("ssh: trailing junk in public key")
  235. }
  236. return out, err
  237. }
  238. // MarshalAuthorizedKey serializes key for inclusion in an OpenSSH
  239. // authorized_keys file. The return value ends with newline.
  240. func MarshalAuthorizedKey(key PublicKey) []byte {
  241. b := &bytes.Buffer{}
  242. b.WriteString(key.Type())
  243. b.WriteByte(' ')
  244. e := base64.NewEncoder(base64.StdEncoding, b)
  245. e.Write(key.Marshal())
  246. e.Close()
  247. b.WriteByte('\n')
  248. return b.Bytes()
  249. }
  250. // PublicKey is an abstraction of different types of public keys.
  251. type PublicKey interface {
  252. // Type returns the key's type, e.g. "ssh-rsa".
  253. Type() string
  254. // Marshal returns the serialized key data in SSH wire format,
  255. // with the name prefix. To unmarshal the returned data, use
  256. // the ParsePublicKey function.
  257. Marshal() []byte
  258. // Verify that sig is a signature on the given data using this
  259. // key. This function will hash the data appropriately first.
  260. Verify(data []byte, sig *Signature) error
  261. }
  262. // CryptoPublicKey, if implemented by a PublicKey,
  263. // returns the underlying crypto.PublicKey form of the key.
  264. type CryptoPublicKey interface {
  265. CryptoPublicKey() crypto.PublicKey
  266. }
  267. // A Signer can create signatures that verify against a public key.
  268. type Signer interface {
  269. // PublicKey returns an associated PublicKey instance.
  270. PublicKey() PublicKey
  271. // Sign returns raw signature for the given data. This method
  272. // will apply the hash specified for the keytype to the data.
  273. Sign(rand io.Reader, data []byte) (*Signature, error)
  274. }
  275. // A AlgorithmSigner is a Signer that also supports specifying a specific
  276. // algorithm to use for signing.
  277. type AlgorithmSigner interface {
  278. Signer
  279. // SignWithAlgorithm is like Signer.Sign, but allows specification of a
  280. // non-default signing algorithm. See the SigAlgo* constants in this
  281. // package for signature algorithms supported by this package. Callers may
  282. // pass an empty string for the algorithm in which case the AlgorithmSigner
  283. // will use its default algorithm.
  284. SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error)
  285. }
  286. type rsaPublicKey rsa.PublicKey
  287. func (r *rsaPublicKey) Type() string {
  288. return "ssh-rsa"
  289. }
  290. // parseRSA parses an RSA key according to RFC 4253, section 6.6.
  291. func parseRSA(in []byte) (out PublicKey, rest []byte, err error) {
  292. var w struct {
  293. E *big.Int
  294. N *big.Int
  295. Rest []byte `ssh:"rest"`
  296. }
  297. if err := Unmarshal(in, &w); err != nil {
  298. return nil, nil, err
  299. }
  300. if w.E.BitLen() > 24 {
  301. return nil, nil, errors.New("ssh: exponent too large")
  302. }
  303. e := w.E.Int64()
  304. if e < 3 || e&1 == 0 {
  305. return nil, nil, errors.New("ssh: incorrect exponent")
  306. }
  307. var key rsa.PublicKey
  308. key.E = int(e)
  309. key.N = w.N
  310. return (*rsaPublicKey)(&key), w.Rest, nil
  311. }
  312. func (r *rsaPublicKey) Marshal() []byte {
  313. e := new(big.Int).SetInt64(int64(r.E))
  314. // RSA publickey struct layout should match the struct used by
  315. // parseRSACert in the x/crypto/ssh/agent package.
  316. wirekey := struct {
  317. Name string
  318. E *big.Int
  319. N *big.Int
  320. }{
  321. KeyAlgoRSA,
  322. e,
  323. r.N,
  324. }
  325. return Marshal(&wirekey)
  326. }
  327. func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error {
  328. var hash crypto.Hash
  329. switch sig.Format {
  330. case SigAlgoRSA:
  331. hash = crypto.SHA1
  332. case SigAlgoRSASHA2256:
  333. hash = crypto.SHA256
  334. case SigAlgoRSASHA2512:
  335. hash = crypto.SHA512
  336. default:
  337. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type())
  338. }
  339. h := hash.New()
  340. h.Write(data)
  341. digest := h.Sum(nil)
  342. return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), hash, digest, sig.Blob)
  343. }
  344. func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  345. return (*rsa.PublicKey)(r)
  346. }
  347. type dsaPublicKey dsa.PublicKey
  348. func (k *dsaPublicKey) Type() string {
  349. return "ssh-dss"
  350. }
  351. func checkDSAParams(param *dsa.Parameters) error {
  352. // SSH specifies FIPS 186-2, which only provided a single size
  353. // (1024 bits) DSA key. FIPS 186-3 allows for larger key
  354. // sizes, which would confuse SSH.
  355. if l := param.P.BitLen(); l != 1024 {
  356. return fmt.Errorf("ssh: unsupported DSA key size %d", l)
  357. }
  358. return nil
  359. }
  360. // parseDSA parses an DSA key according to RFC 4253, section 6.6.
  361. func parseDSA(in []byte) (out PublicKey, rest []byte, err error) {
  362. var w struct {
  363. P, Q, G, Y *big.Int
  364. Rest []byte `ssh:"rest"`
  365. }
  366. if err := Unmarshal(in, &w); err != nil {
  367. return nil, nil, err
  368. }
  369. param := dsa.Parameters{
  370. P: w.P,
  371. Q: w.Q,
  372. G: w.G,
  373. }
  374. if err := checkDSAParams(&param); err != nil {
  375. return nil, nil, err
  376. }
  377. key := &dsaPublicKey{
  378. Parameters: param,
  379. Y: w.Y,
  380. }
  381. return key, w.Rest, nil
  382. }
  383. func (k *dsaPublicKey) Marshal() []byte {
  384. // DSA publickey struct layout should match the struct used by
  385. // parseDSACert in the x/crypto/ssh/agent package.
  386. w := struct {
  387. Name string
  388. P, Q, G, Y *big.Int
  389. }{
  390. k.Type(),
  391. k.P,
  392. k.Q,
  393. k.G,
  394. k.Y,
  395. }
  396. return Marshal(&w)
  397. }
  398. func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error {
  399. if sig.Format != k.Type() {
  400. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  401. }
  402. h := crypto.SHA1.New()
  403. h.Write(data)
  404. digest := h.Sum(nil)
  405. // Per RFC 4253, section 6.6,
  406. // The value for 'dss_signature_blob' is encoded as a string containing
  407. // r, followed by s (which are 160-bit integers, without lengths or
  408. // padding, unsigned, and in network byte order).
  409. // For DSS purposes, sig.Blob should be exactly 40 bytes in length.
  410. if len(sig.Blob) != 40 {
  411. return errors.New("ssh: DSA signature parse error")
  412. }
  413. r := new(big.Int).SetBytes(sig.Blob[:20])
  414. s := new(big.Int).SetBytes(sig.Blob[20:])
  415. if dsa.Verify((*dsa.PublicKey)(k), digest, r, s) {
  416. return nil
  417. }
  418. return errors.New("ssh: signature did not verify")
  419. }
  420. func (k *dsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  421. return (*dsa.PublicKey)(k)
  422. }
  423. type dsaPrivateKey struct {
  424. *dsa.PrivateKey
  425. }
  426. func (k *dsaPrivateKey) PublicKey() PublicKey {
  427. return (*dsaPublicKey)(&k.PrivateKey.PublicKey)
  428. }
  429. func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) {
  430. return k.SignWithAlgorithm(rand, data, "")
  431. }
  432. func (k *dsaPrivateKey) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  433. if algorithm != "" && algorithm != k.PublicKey().Type() {
  434. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  435. }
  436. h := crypto.SHA1.New()
  437. h.Write(data)
  438. digest := h.Sum(nil)
  439. r, s, err := dsa.Sign(rand, k.PrivateKey, digest)
  440. if err != nil {
  441. return nil, err
  442. }
  443. sig := make([]byte, 40)
  444. rb := r.Bytes()
  445. sb := s.Bytes()
  446. copy(sig[20-len(rb):20], rb)
  447. copy(sig[40-len(sb):], sb)
  448. return &Signature{
  449. Format: k.PublicKey().Type(),
  450. Blob: sig,
  451. }, nil
  452. }
  453. type ecdsaPublicKey ecdsa.PublicKey
  454. func (k *ecdsaPublicKey) Type() string {
  455. return "ecdsa-sha2-" + k.nistID()
  456. }
  457. func (k *ecdsaPublicKey) nistID() string {
  458. switch k.Params().BitSize {
  459. case 256:
  460. return "nistp256"
  461. case 384:
  462. return "nistp384"
  463. case 521:
  464. return "nistp521"
  465. }
  466. panic("ssh: unsupported ecdsa key size")
  467. }
  468. type ed25519PublicKey ed25519.PublicKey
  469. func (k ed25519PublicKey) Type() string {
  470. return KeyAlgoED25519
  471. }
  472. func parseED25519(in []byte) (out PublicKey, rest []byte, err error) {
  473. var w struct {
  474. KeyBytes []byte
  475. Rest []byte `ssh:"rest"`
  476. }
  477. if err := Unmarshal(in, &w); err != nil {
  478. return nil, nil, err
  479. }
  480. key := ed25519.PublicKey(w.KeyBytes)
  481. return (ed25519PublicKey)(key), w.Rest, nil
  482. }
  483. func (k ed25519PublicKey) Marshal() []byte {
  484. w := struct {
  485. Name string
  486. KeyBytes []byte
  487. }{
  488. KeyAlgoED25519,
  489. []byte(k),
  490. }
  491. return Marshal(&w)
  492. }
  493. func (k ed25519PublicKey) Verify(b []byte, sig *Signature) error {
  494. if sig.Format != k.Type() {
  495. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  496. }
  497. edKey := (ed25519.PublicKey)(k)
  498. if ok := ed25519.Verify(edKey, b, sig.Blob); !ok {
  499. return errors.New("ssh: signature did not verify")
  500. }
  501. return nil
  502. }
  503. func (k ed25519PublicKey) CryptoPublicKey() crypto.PublicKey {
  504. return ed25519.PublicKey(k)
  505. }
  506. func supportedEllipticCurve(curve elliptic.Curve) bool {
  507. return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521()
  508. }
  509. // ecHash returns the hash to match the given elliptic curve, see RFC
  510. // 5656, section 6.2.1
  511. func ecHash(curve elliptic.Curve) crypto.Hash {
  512. bitSize := curve.Params().BitSize
  513. switch {
  514. case bitSize <= 256:
  515. return crypto.SHA256
  516. case bitSize <= 384:
  517. return crypto.SHA384
  518. }
  519. return crypto.SHA512
  520. }
  521. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  522. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  523. var w struct {
  524. Curve string
  525. KeyBytes []byte
  526. Rest []byte `ssh:"rest"`
  527. }
  528. if err := Unmarshal(in, &w); err != nil {
  529. return nil, nil, err
  530. }
  531. key := new(ecdsa.PublicKey)
  532. switch w.Curve {
  533. case "nistp256":
  534. key.Curve = elliptic.P256()
  535. case "nistp384":
  536. key.Curve = elliptic.P384()
  537. case "nistp521":
  538. key.Curve = elliptic.P521()
  539. default:
  540. return nil, nil, errors.New("ssh: unsupported curve")
  541. }
  542. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  543. if key.X == nil || key.Y == nil {
  544. return nil, nil, errors.New("ssh: invalid curve point")
  545. }
  546. return (*ecdsaPublicKey)(key), w.Rest, nil
  547. }
  548. func (k *ecdsaPublicKey) Marshal() []byte {
  549. // See RFC 5656, section 3.1.
  550. keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y)
  551. // ECDSA publickey struct layout should match the struct used by
  552. // parseECDSACert in the x/crypto/ssh/agent package.
  553. w := struct {
  554. Name string
  555. ID string
  556. Key []byte
  557. }{
  558. k.Type(),
  559. k.nistID(),
  560. keyBytes,
  561. }
  562. return Marshal(&w)
  563. }
  564. func (k *ecdsaPublicKey) Verify(data []byte, sig *Signature) error {
  565. if sig.Format != k.Type() {
  566. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  567. }
  568. h := ecHash(k.Curve).New()
  569. h.Write(data)
  570. digest := h.Sum(nil)
  571. // Per RFC 5656, section 3.1.2,
  572. // The ecdsa_signature_blob value has the following specific encoding:
  573. // mpint r
  574. // mpint s
  575. var ecSig struct {
  576. R *big.Int
  577. S *big.Int
  578. }
  579. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  580. return err
  581. }
  582. if ecdsa.Verify((*ecdsa.PublicKey)(k), digest, ecSig.R, ecSig.S) {
  583. return nil
  584. }
  585. return errors.New("ssh: signature did not verify")
  586. }
  587. func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  588. return (*ecdsa.PublicKey)(k)
  589. }
  590. // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey,
  591. // *ecdsa.PrivateKey or any other crypto.Signer and returns a
  592. // corresponding Signer instance. ECDSA keys must use P-256, P-384 or
  593. // P-521. DSA keys must use parameter size L1024N160.
  594. func NewSignerFromKey(key interface{}) (Signer, error) {
  595. switch key := key.(type) {
  596. case crypto.Signer:
  597. return NewSignerFromSigner(key)
  598. case *dsa.PrivateKey:
  599. return newDSAPrivateKey(key)
  600. default:
  601. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  602. }
  603. }
  604. func newDSAPrivateKey(key *dsa.PrivateKey) (Signer, error) {
  605. if err := checkDSAParams(&key.PublicKey.Parameters); err != nil {
  606. return nil, err
  607. }
  608. return &dsaPrivateKey{key}, nil
  609. }
  610. type wrappedSigner struct {
  611. signer crypto.Signer
  612. pubKey PublicKey
  613. }
  614. // NewSignerFromSigner takes any crypto.Signer implementation and
  615. // returns a corresponding Signer interface. This can be used, for
  616. // example, with keys kept in hardware modules.
  617. func NewSignerFromSigner(signer crypto.Signer) (Signer, error) {
  618. pubKey, err := NewPublicKey(signer.Public())
  619. if err != nil {
  620. return nil, err
  621. }
  622. return &wrappedSigner{signer, pubKey}, nil
  623. }
  624. func (s *wrappedSigner) PublicKey() PublicKey {
  625. return s.pubKey
  626. }
  627. func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  628. return s.SignWithAlgorithm(rand, data, "")
  629. }
  630. func (s *wrappedSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  631. var hashFunc crypto.Hash
  632. if _, ok := s.pubKey.(*rsaPublicKey); ok {
  633. // RSA keys support a few hash functions determined by the requested signature algorithm
  634. switch algorithm {
  635. case "", SigAlgoRSA:
  636. algorithm = SigAlgoRSA
  637. hashFunc = crypto.SHA1
  638. case SigAlgoRSASHA2256:
  639. hashFunc = crypto.SHA256
  640. case SigAlgoRSASHA2512:
  641. hashFunc = crypto.SHA512
  642. default:
  643. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  644. }
  645. } else {
  646. // The only supported algorithm for all other key types is the same as the type of the key
  647. if algorithm == "" {
  648. algorithm = s.pubKey.Type()
  649. } else if algorithm != s.pubKey.Type() {
  650. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  651. }
  652. switch key := s.pubKey.(type) {
  653. case *dsaPublicKey:
  654. hashFunc = crypto.SHA1
  655. case *ecdsaPublicKey:
  656. hashFunc = ecHash(key.Curve)
  657. case ed25519PublicKey:
  658. default:
  659. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  660. }
  661. }
  662. var digest []byte
  663. if hashFunc != 0 {
  664. h := hashFunc.New()
  665. h.Write(data)
  666. digest = h.Sum(nil)
  667. } else {
  668. digest = data
  669. }
  670. signature, err := s.signer.Sign(rand, digest, hashFunc)
  671. if err != nil {
  672. return nil, err
  673. }
  674. // crypto.Signer.Sign is expected to return an ASN.1-encoded signature
  675. // for ECDSA and DSA, but that's not the encoding expected by SSH, so
  676. // re-encode.
  677. switch s.pubKey.(type) {
  678. case *ecdsaPublicKey, *dsaPublicKey:
  679. type asn1Signature struct {
  680. R, S *big.Int
  681. }
  682. asn1Sig := new(asn1Signature)
  683. _, err := asn1.Unmarshal(signature, asn1Sig)
  684. if err != nil {
  685. return nil, err
  686. }
  687. switch s.pubKey.(type) {
  688. case *ecdsaPublicKey:
  689. signature = Marshal(asn1Sig)
  690. case *dsaPublicKey:
  691. signature = make([]byte, 40)
  692. r := asn1Sig.R.Bytes()
  693. s := asn1Sig.S.Bytes()
  694. copy(signature[20-len(r):20], r)
  695. copy(signature[40-len(s):40], s)
  696. }
  697. }
  698. return &Signature{
  699. Format: algorithm,
  700. Blob: signature,
  701. }, nil
  702. }
  703. // NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
  704. // or ed25519.PublicKey returns a corresponding PublicKey instance.
  705. // ECDSA keys must use P-256, P-384 or P-521.
  706. func NewPublicKey(key interface{}) (PublicKey, error) {
  707. switch key := key.(type) {
  708. case *rsa.PublicKey:
  709. return (*rsaPublicKey)(key), nil
  710. case *ecdsa.PublicKey:
  711. if !supportedEllipticCurve(key.Curve) {
  712. return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported")
  713. }
  714. return (*ecdsaPublicKey)(key), nil
  715. case *dsa.PublicKey:
  716. return (*dsaPublicKey)(key), nil
  717. case ed25519.PublicKey:
  718. return (ed25519PublicKey)(key), nil
  719. default:
  720. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  721. }
  722. }
  723. // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports
  724. // the same keys as ParseRawPrivateKey.
  725. func ParsePrivateKey(pemBytes []byte) (Signer, error) {
  726. key, err := ParseRawPrivateKey(pemBytes)
  727. if err != nil {
  728. return nil, err
  729. }
  730. return NewSignerFromKey(key)
  731. }
  732. // ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private
  733. // key and passphrase. It supports the same keys as
  734. // ParseRawPrivateKeyWithPassphrase.
  735. func ParsePrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (Signer, error) {
  736. key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase)
  737. if err != nil {
  738. return nil, err
  739. }
  740. return NewSignerFromKey(key)
  741. }
  742. // encryptedBlock tells whether a private key is
  743. // encrypted by examining its Proc-Type header
  744. // for a mention of ENCRYPTED
  745. // according to RFC 1421 Section 4.6.1.1.
  746. func encryptedBlock(block *pem.Block) bool {
  747. return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED")
  748. }
  749. // ParseRawPrivateKey returns a private key from a PEM encoded private key. It
  750. // supports RSA (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys.
  751. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
  752. block, _ := pem.Decode(pemBytes)
  753. if block == nil {
  754. return nil, errors.New("ssh: no key found")
  755. }
  756. if encryptedBlock(block) {
  757. return nil, errors.New("ssh: cannot decode encrypted private keys")
  758. }
  759. switch block.Type {
  760. case "RSA PRIVATE KEY":
  761. return x509.ParsePKCS1PrivateKey(block.Bytes)
  762. // RFC5208 - https://tools.ietf.org/html/rfc5208
  763. case "PRIVATE KEY":
  764. return x509.ParsePKCS8PrivateKey(block.Bytes)
  765. case "EC PRIVATE KEY":
  766. return x509.ParseECPrivateKey(block.Bytes)
  767. case "DSA PRIVATE KEY":
  768. return ParseDSAPrivateKey(block.Bytes)
  769. case "OPENSSH PRIVATE KEY":
  770. return parseOpenSSHPrivateKey(block.Bytes)
  771. default:
  772. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  773. }
  774. }
  775. // ParseRawPrivateKeyWithPassphrase returns a private key decrypted with
  776. // passphrase from a PEM encoded private key. If wrong passphrase, return
  777. // x509.IncorrectPasswordError.
  778. func ParseRawPrivateKeyWithPassphrase(pemBytes, passPhrase []byte) (interface{}, error) {
  779. block, _ := pem.Decode(pemBytes)
  780. if block == nil {
  781. return nil, errors.New("ssh: no key found")
  782. }
  783. buf := block.Bytes
  784. if encryptedBlock(block) {
  785. if x509.IsEncryptedPEMBlock(block) {
  786. var err error
  787. buf, err = x509.DecryptPEMBlock(block, passPhrase)
  788. if err != nil {
  789. if err == x509.IncorrectPasswordError {
  790. return nil, err
  791. }
  792. return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err)
  793. }
  794. }
  795. }
  796. switch block.Type {
  797. case "RSA PRIVATE KEY":
  798. return x509.ParsePKCS1PrivateKey(buf)
  799. case "EC PRIVATE KEY":
  800. return x509.ParseECPrivateKey(buf)
  801. case "DSA PRIVATE KEY":
  802. return ParseDSAPrivateKey(buf)
  803. case "OPENSSH PRIVATE KEY":
  804. return parseOpenSSHPrivateKey(buf)
  805. default:
  806. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  807. }
  808. }
  809. // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
  810. // specified by the OpenSSL DSA man page.
  811. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
  812. var k struct {
  813. Version int
  814. P *big.Int
  815. Q *big.Int
  816. G *big.Int
  817. Pub *big.Int
  818. Priv *big.Int
  819. }
  820. rest, err := asn1.Unmarshal(der, &k)
  821. if err != nil {
  822. return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
  823. }
  824. if len(rest) > 0 {
  825. return nil, errors.New("ssh: garbage after DSA key")
  826. }
  827. return &dsa.PrivateKey{
  828. PublicKey: dsa.PublicKey{
  829. Parameters: dsa.Parameters{
  830. P: k.P,
  831. Q: k.Q,
  832. G: k.G,
  833. },
  834. Y: k.Pub,
  835. },
  836. X: k.Priv,
  837. }, nil
  838. }
  839. // Implemented based on the documentation at
  840. // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key
  841. func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) {
  842. const magic = "openssh-key-v1\x00"
  843. if len(key) < len(magic) || string(key[:len(magic)]) != magic {
  844. return nil, errors.New("ssh: invalid openssh private key format")
  845. }
  846. remaining := key[len(magic):]
  847. var w struct {
  848. CipherName string
  849. KdfName string
  850. KdfOpts string
  851. NumKeys uint32
  852. PubKey []byte
  853. PrivKeyBlock []byte
  854. }
  855. if err := Unmarshal(remaining, &w); err != nil {
  856. return nil, err
  857. }
  858. if w.KdfName != "none" || w.CipherName != "none" {
  859. return nil, errors.New("ssh: cannot decode encrypted private keys")
  860. }
  861. pk1 := struct {
  862. Check1 uint32
  863. Check2 uint32
  864. Keytype string
  865. Rest []byte `ssh:"rest"`
  866. }{}
  867. if err := Unmarshal(w.PrivKeyBlock, &pk1); err != nil {
  868. return nil, err
  869. }
  870. if pk1.Check1 != pk1.Check2 {
  871. return nil, errors.New("ssh: checkint mismatch")
  872. }
  873. // we only handle ed25519 and rsa keys currently
  874. switch pk1.Keytype {
  875. case KeyAlgoRSA:
  876. // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L2760-L2773
  877. key := struct {
  878. N *big.Int
  879. E *big.Int
  880. D *big.Int
  881. Iqmp *big.Int
  882. P *big.Int
  883. Q *big.Int
  884. Comment string
  885. Pad []byte `ssh:"rest"`
  886. }{}
  887. if err := Unmarshal(pk1.Rest, &key); err != nil {
  888. return nil, err
  889. }
  890. for i, b := range key.Pad {
  891. if int(b) != i+1 {
  892. return nil, errors.New("ssh: padding not as expected")
  893. }
  894. }
  895. pk := &rsa.PrivateKey{
  896. PublicKey: rsa.PublicKey{
  897. N: key.N,
  898. E: int(key.E.Int64()),
  899. },
  900. D: key.D,
  901. Primes: []*big.Int{key.P, key.Q},
  902. }
  903. if err := pk.Validate(); err != nil {
  904. return nil, err
  905. }
  906. pk.Precompute()
  907. return pk, nil
  908. case KeyAlgoED25519:
  909. key := struct {
  910. Pub []byte
  911. Priv []byte
  912. Comment string
  913. Pad []byte `ssh:"rest"`
  914. }{}
  915. if err := Unmarshal(pk1.Rest, &key); err != nil {
  916. return nil, err
  917. }
  918. if len(key.Priv) != ed25519.PrivateKeySize {
  919. return nil, errors.New("ssh: private key unexpected length")
  920. }
  921. for i, b := range key.Pad {
  922. if int(b) != i+1 {
  923. return nil, errors.New("ssh: padding not as expected")
  924. }
  925. }
  926. pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize))
  927. copy(pk, key.Priv)
  928. return &pk, nil
  929. default:
  930. return nil, errors.New("ssh: unhandled key type")
  931. }
  932. }
  933. // FingerprintLegacyMD5 returns the user presentation of the key's
  934. // fingerprint as described by RFC 4716 section 4.
  935. func FingerprintLegacyMD5(pubKey PublicKey) string {
  936. md5sum := md5.Sum(pubKey.Marshal())
  937. hexarray := make([]string, len(md5sum))
  938. for i, c := range md5sum {
  939. hexarray[i] = hex.EncodeToString([]byte{c})
  940. }
  941. return strings.Join(hexarray, ":")
  942. }
  943. // FingerprintSHA256 returns the user presentation of the key's
  944. // fingerprint as unpadded base64 encoded sha256 hash.
  945. // This format was introduced from OpenSSH 6.8.
  946. // https://www.openssh.com/txt/release-6.8
  947. // https://tools.ietf.org/html/rfc4648#section-3.2 (unpadded base64 encoding)
  948. func FingerprintSHA256(pubKey PublicKey) string {
  949. sha256sum := sha256.Sum256(pubKey.Marshal())
  950. hash := base64.RawStdEncoding.EncodeToString(sha256sum[:])
  951. return "SHA256:" + hash
  952. }