You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

keys.go 37 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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/aes"
  9. "crypto/cipher"
  10. "crypto/dsa"
  11. "crypto/ecdsa"
  12. "crypto/elliptic"
  13. "crypto/md5"
  14. "crypto/rsa"
  15. "crypto/sha256"
  16. "crypto/x509"
  17. "encoding/asn1"
  18. "encoding/base64"
  19. "encoding/hex"
  20. "encoding/pem"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "math/big"
  25. "strings"
  26. "golang.org/x/crypto/ed25519"
  27. "golang.org/x/crypto/ssh/internal/bcrypt_pbkdf"
  28. )
  29. // These constants represent the algorithm names for key types supported by this
  30. // package.
  31. const (
  32. KeyAlgoRSA = "ssh-rsa"
  33. KeyAlgoDSA = "ssh-dss"
  34. KeyAlgoECDSA256 = "ecdsa-sha2-nistp256"
  35. KeyAlgoSKECDSA256 = "sk-ecdsa-sha2-nistp256@openssh.com"
  36. KeyAlgoECDSA384 = "ecdsa-sha2-nistp384"
  37. KeyAlgoECDSA521 = "ecdsa-sha2-nistp521"
  38. KeyAlgoED25519 = "ssh-ed25519"
  39. KeyAlgoSKED25519 = "sk-ssh-ed25519@openssh.com"
  40. )
  41. // These constants represent non-default signature algorithms that are supported
  42. // as algorithm parameters to AlgorithmSigner.SignWithAlgorithm methods. See
  43. // [PROTOCOL.agent] section 4.5.1 and
  44. // https://tools.ietf.org/html/draft-ietf-curdle-rsa-sha2-10
  45. const (
  46. SigAlgoRSA = "ssh-rsa"
  47. SigAlgoRSASHA2256 = "rsa-sha2-256"
  48. SigAlgoRSASHA2512 = "rsa-sha2-512"
  49. )
  50. // parsePubKey parses a public key of the given algorithm.
  51. // Use ParsePublicKey for keys with prepended algorithm.
  52. func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err error) {
  53. switch algo {
  54. case KeyAlgoRSA:
  55. return parseRSA(in)
  56. case KeyAlgoDSA:
  57. return parseDSA(in)
  58. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  59. return parseECDSA(in)
  60. case KeyAlgoSKECDSA256:
  61. return parseSKECDSA(in)
  62. case KeyAlgoED25519:
  63. return parseED25519(in)
  64. case KeyAlgoSKED25519:
  65. return parseSKEd25519(in)
  66. case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoSKECDSA256v01, CertAlgoED25519v01, CertAlgoSKED25519v01:
  67. cert, err := parseCert(in, certToPrivAlgo(algo))
  68. if err != nil {
  69. return nil, nil, err
  70. }
  71. return cert, nil, nil
  72. }
  73. return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", algo)
  74. }
  75. // parseAuthorizedKey parses a public key in OpenSSH authorized_keys format
  76. // (see sshd(8) manual page) once the options and key type fields have been
  77. // removed.
  78. func parseAuthorizedKey(in []byte) (out PublicKey, comment string, err error) {
  79. in = bytes.TrimSpace(in)
  80. i := bytes.IndexAny(in, " \t")
  81. if i == -1 {
  82. i = len(in)
  83. }
  84. base64Key := in[:i]
  85. key := make([]byte, base64.StdEncoding.DecodedLen(len(base64Key)))
  86. n, err := base64.StdEncoding.Decode(key, base64Key)
  87. if err != nil {
  88. return nil, "", err
  89. }
  90. key = key[:n]
  91. out, err = ParsePublicKey(key)
  92. if err != nil {
  93. return nil, "", err
  94. }
  95. comment = string(bytes.TrimSpace(in[i:]))
  96. return out, comment, nil
  97. }
  98. // ParseKnownHosts parses an entry in the format of the known_hosts file.
  99. //
  100. // The known_hosts format is documented in the sshd(8) manual page. This
  101. // function will parse a single entry from in. On successful return, marker
  102. // will contain the optional marker value (i.e. "cert-authority" or "revoked")
  103. // or else be empty, hosts will contain the hosts that this entry matches,
  104. // pubKey will contain the public key and comment will contain any trailing
  105. // comment at the end of the line. See the sshd(8) manual page for the various
  106. // forms that a host string can take.
  107. //
  108. // The unparsed remainder of the input will be returned in rest. This function
  109. // can be called repeatedly to parse multiple entries.
  110. //
  111. // If no entries were found in the input then err will be io.EOF. Otherwise a
  112. // non-nil err value indicates a parse error.
  113. func ParseKnownHosts(in []byte) (marker string, hosts []string, pubKey PublicKey, comment string, rest []byte, err error) {
  114. for len(in) > 0 {
  115. end := bytes.IndexByte(in, '\n')
  116. if end != -1 {
  117. rest = in[end+1:]
  118. in = in[:end]
  119. } else {
  120. rest = nil
  121. }
  122. end = bytes.IndexByte(in, '\r')
  123. if end != -1 {
  124. in = in[:end]
  125. }
  126. in = bytes.TrimSpace(in)
  127. if len(in) == 0 || in[0] == '#' {
  128. in = rest
  129. continue
  130. }
  131. i := bytes.IndexAny(in, " \t")
  132. if i == -1 {
  133. in = rest
  134. continue
  135. }
  136. // Strip out the beginning of the known_host key.
  137. // This is either an optional marker or a (set of) hostname(s).
  138. keyFields := bytes.Fields(in)
  139. if len(keyFields) < 3 || len(keyFields) > 5 {
  140. return "", nil, nil, "", nil, errors.New("ssh: invalid entry in known_hosts data")
  141. }
  142. // keyFields[0] is either "@cert-authority", "@revoked" or a comma separated
  143. // list of hosts
  144. marker := ""
  145. if keyFields[0][0] == '@' {
  146. marker = string(keyFields[0][1:])
  147. keyFields = keyFields[1:]
  148. }
  149. hosts := string(keyFields[0])
  150. // keyFields[1] contains the key type (e.g. “ssh-rsa”).
  151. // However, that information is duplicated inside the
  152. // base64-encoded key and so is ignored here.
  153. key := bytes.Join(keyFields[2:], []byte(" "))
  154. if pubKey, comment, err = parseAuthorizedKey(key); err != nil {
  155. return "", nil, nil, "", nil, err
  156. }
  157. return marker, strings.Split(hosts, ","), pubKey, comment, rest, nil
  158. }
  159. return "", nil, nil, "", nil, io.EOF
  160. }
  161. // ParseAuthorizedKeys parses a public key from an authorized_keys
  162. // file used in OpenSSH according to the sshd(8) manual page.
  163. func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error) {
  164. for len(in) > 0 {
  165. end := bytes.IndexByte(in, '\n')
  166. if end != -1 {
  167. rest = in[end+1:]
  168. in = in[:end]
  169. } else {
  170. rest = nil
  171. }
  172. end = bytes.IndexByte(in, '\r')
  173. if end != -1 {
  174. in = in[:end]
  175. }
  176. in = bytes.TrimSpace(in)
  177. if len(in) == 0 || in[0] == '#' {
  178. in = rest
  179. continue
  180. }
  181. i := bytes.IndexAny(in, " \t")
  182. if i == -1 {
  183. in = rest
  184. continue
  185. }
  186. if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
  187. return out, comment, options, rest, nil
  188. }
  189. // No key type recognised. Maybe there's an options field at
  190. // the beginning.
  191. var b byte
  192. inQuote := false
  193. var candidateOptions []string
  194. optionStart := 0
  195. for i, b = range in {
  196. isEnd := !inQuote && (b == ' ' || b == '\t')
  197. if (b == ',' && !inQuote) || isEnd {
  198. if i-optionStart > 0 {
  199. candidateOptions = append(candidateOptions, string(in[optionStart:i]))
  200. }
  201. optionStart = i + 1
  202. }
  203. if isEnd {
  204. break
  205. }
  206. if b == '"' && (i == 0 || (i > 0 && in[i-1] != '\\')) {
  207. inQuote = !inQuote
  208. }
  209. }
  210. for i < len(in) && (in[i] == ' ' || in[i] == '\t') {
  211. i++
  212. }
  213. if i == len(in) {
  214. // Invalid line: unmatched quote
  215. in = rest
  216. continue
  217. }
  218. in = in[i:]
  219. i = bytes.IndexAny(in, " \t")
  220. if i == -1 {
  221. in = rest
  222. continue
  223. }
  224. if out, comment, err = parseAuthorizedKey(in[i:]); err == nil {
  225. options = candidateOptions
  226. return out, comment, options, rest, nil
  227. }
  228. in = rest
  229. continue
  230. }
  231. return nil, "", nil, nil, errors.New("ssh: no key found")
  232. }
  233. // ParsePublicKey parses an SSH public key formatted for use in
  234. // the SSH wire protocol according to RFC 4253, section 6.6.
  235. func ParsePublicKey(in []byte) (out PublicKey, err error) {
  236. algo, in, ok := parseString(in)
  237. if !ok {
  238. return nil, errShortRead
  239. }
  240. var rest []byte
  241. out, rest, err = parsePubKey(in, string(algo))
  242. if len(rest) > 0 {
  243. return nil, errors.New("ssh: trailing junk in public key")
  244. }
  245. return out, err
  246. }
  247. // MarshalAuthorizedKey serializes key for inclusion in an OpenSSH
  248. // authorized_keys file. The return value ends with newline.
  249. func MarshalAuthorizedKey(key PublicKey) []byte {
  250. b := &bytes.Buffer{}
  251. b.WriteString(key.Type())
  252. b.WriteByte(' ')
  253. e := base64.NewEncoder(base64.StdEncoding, b)
  254. e.Write(key.Marshal())
  255. e.Close()
  256. b.WriteByte('\n')
  257. return b.Bytes()
  258. }
  259. // PublicKey is an abstraction of different types of public keys.
  260. type PublicKey interface {
  261. // Type returns the key's type, e.g. "ssh-rsa".
  262. Type() string
  263. // Marshal returns the serialized key data in SSH wire format,
  264. // with the name prefix. To unmarshal the returned data, use
  265. // the ParsePublicKey function.
  266. Marshal() []byte
  267. // Verify that sig is a signature on the given data using this
  268. // key. This function will hash the data appropriately first.
  269. Verify(data []byte, sig *Signature) error
  270. }
  271. // CryptoPublicKey, if implemented by a PublicKey,
  272. // returns the underlying crypto.PublicKey form of the key.
  273. type CryptoPublicKey interface {
  274. CryptoPublicKey() crypto.PublicKey
  275. }
  276. // A Signer can create signatures that verify against a public key.
  277. type Signer interface {
  278. // PublicKey returns an associated PublicKey instance.
  279. PublicKey() PublicKey
  280. // Sign returns raw signature for the given data. This method
  281. // will apply the hash specified for the keytype to the data.
  282. Sign(rand io.Reader, data []byte) (*Signature, error)
  283. }
  284. // A AlgorithmSigner is a Signer that also supports specifying a specific
  285. // algorithm to use for signing.
  286. type AlgorithmSigner interface {
  287. Signer
  288. // SignWithAlgorithm is like Signer.Sign, but allows specification of a
  289. // non-default signing algorithm. See the SigAlgo* constants in this
  290. // package for signature algorithms supported by this package. Callers may
  291. // pass an empty string for the algorithm in which case the AlgorithmSigner
  292. // will use its default algorithm.
  293. SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error)
  294. }
  295. type rsaPublicKey rsa.PublicKey
  296. func (r *rsaPublicKey) Type() string {
  297. return "ssh-rsa"
  298. }
  299. // parseRSA parses an RSA key according to RFC 4253, section 6.6.
  300. func parseRSA(in []byte) (out PublicKey, rest []byte, err error) {
  301. var w struct {
  302. E *big.Int
  303. N *big.Int
  304. Rest []byte `ssh:"rest"`
  305. }
  306. if err := Unmarshal(in, &w); err != nil {
  307. return nil, nil, err
  308. }
  309. if w.E.BitLen() > 24 {
  310. return nil, nil, errors.New("ssh: exponent too large")
  311. }
  312. e := w.E.Int64()
  313. if e < 3 || e&1 == 0 {
  314. return nil, nil, errors.New("ssh: incorrect exponent")
  315. }
  316. var key rsa.PublicKey
  317. key.E = int(e)
  318. key.N = w.N
  319. return (*rsaPublicKey)(&key), w.Rest, nil
  320. }
  321. func (r *rsaPublicKey) Marshal() []byte {
  322. e := new(big.Int).SetInt64(int64(r.E))
  323. // RSA publickey struct layout should match the struct used by
  324. // parseRSACert in the x/crypto/ssh/agent package.
  325. wirekey := struct {
  326. Name string
  327. E *big.Int
  328. N *big.Int
  329. }{
  330. KeyAlgoRSA,
  331. e,
  332. r.N,
  333. }
  334. return Marshal(&wirekey)
  335. }
  336. func (r *rsaPublicKey) Verify(data []byte, sig *Signature) error {
  337. var hash crypto.Hash
  338. switch sig.Format {
  339. case SigAlgoRSA:
  340. hash = crypto.SHA1
  341. case SigAlgoRSASHA2256:
  342. hash = crypto.SHA256
  343. case SigAlgoRSASHA2512:
  344. hash = crypto.SHA512
  345. default:
  346. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, r.Type())
  347. }
  348. h := hash.New()
  349. h.Write(data)
  350. digest := h.Sum(nil)
  351. return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), hash, digest, sig.Blob)
  352. }
  353. func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  354. return (*rsa.PublicKey)(r)
  355. }
  356. type dsaPublicKey dsa.PublicKey
  357. func (k *dsaPublicKey) Type() string {
  358. return "ssh-dss"
  359. }
  360. func checkDSAParams(param *dsa.Parameters) error {
  361. // SSH specifies FIPS 186-2, which only provided a single size
  362. // (1024 bits) DSA key. FIPS 186-3 allows for larger key
  363. // sizes, which would confuse SSH.
  364. if l := param.P.BitLen(); l != 1024 {
  365. return fmt.Errorf("ssh: unsupported DSA key size %d", l)
  366. }
  367. return nil
  368. }
  369. // parseDSA parses an DSA key according to RFC 4253, section 6.6.
  370. func parseDSA(in []byte) (out PublicKey, rest []byte, err error) {
  371. var w struct {
  372. P, Q, G, Y *big.Int
  373. Rest []byte `ssh:"rest"`
  374. }
  375. if err := Unmarshal(in, &w); err != nil {
  376. return nil, nil, err
  377. }
  378. param := dsa.Parameters{
  379. P: w.P,
  380. Q: w.Q,
  381. G: w.G,
  382. }
  383. if err := checkDSAParams(&param); err != nil {
  384. return nil, nil, err
  385. }
  386. key := &dsaPublicKey{
  387. Parameters: param,
  388. Y: w.Y,
  389. }
  390. return key, w.Rest, nil
  391. }
  392. func (k *dsaPublicKey) Marshal() []byte {
  393. // DSA publickey struct layout should match the struct used by
  394. // parseDSACert in the x/crypto/ssh/agent package.
  395. w := struct {
  396. Name string
  397. P, Q, G, Y *big.Int
  398. }{
  399. k.Type(),
  400. k.P,
  401. k.Q,
  402. k.G,
  403. k.Y,
  404. }
  405. return Marshal(&w)
  406. }
  407. func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error {
  408. if sig.Format != k.Type() {
  409. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  410. }
  411. h := crypto.SHA1.New()
  412. h.Write(data)
  413. digest := h.Sum(nil)
  414. // Per RFC 4253, section 6.6,
  415. // The value for 'dss_signature_blob' is encoded as a string containing
  416. // r, followed by s (which are 160-bit integers, without lengths or
  417. // padding, unsigned, and in network byte order).
  418. // For DSS purposes, sig.Blob should be exactly 40 bytes in length.
  419. if len(sig.Blob) != 40 {
  420. return errors.New("ssh: DSA signature parse error")
  421. }
  422. r := new(big.Int).SetBytes(sig.Blob[:20])
  423. s := new(big.Int).SetBytes(sig.Blob[20:])
  424. if dsa.Verify((*dsa.PublicKey)(k), digest, r, s) {
  425. return nil
  426. }
  427. return errors.New("ssh: signature did not verify")
  428. }
  429. func (k *dsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  430. return (*dsa.PublicKey)(k)
  431. }
  432. type dsaPrivateKey struct {
  433. *dsa.PrivateKey
  434. }
  435. func (k *dsaPrivateKey) PublicKey() PublicKey {
  436. return (*dsaPublicKey)(&k.PrivateKey.PublicKey)
  437. }
  438. func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) {
  439. return k.SignWithAlgorithm(rand, data, "")
  440. }
  441. func (k *dsaPrivateKey) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  442. if algorithm != "" && algorithm != k.PublicKey().Type() {
  443. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  444. }
  445. h := crypto.SHA1.New()
  446. h.Write(data)
  447. digest := h.Sum(nil)
  448. r, s, err := dsa.Sign(rand, k.PrivateKey, digest)
  449. if err != nil {
  450. return nil, err
  451. }
  452. sig := make([]byte, 40)
  453. rb := r.Bytes()
  454. sb := s.Bytes()
  455. copy(sig[20-len(rb):20], rb)
  456. copy(sig[40-len(sb):], sb)
  457. return &Signature{
  458. Format: k.PublicKey().Type(),
  459. Blob: sig,
  460. }, nil
  461. }
  462. type ecdsaPublicKey ecdsa.PublicKey
  463. func (k *ecdsaPublicKey) Type() string {
  464. return "ecdsa-sha2-" + k.nistID()
  465. }
  466. func (k *ecdsaPublicKey) nistID() string {
  467. switch k.Params().BitSize {
  468. case 256:
  469. return "nistp256"
  470. case 384:
  471. return "nistp384"
  472. case 521:
  473. return "nistp521"
  474. }
  475. panic("ssh: unsupported ecdsa key size")
  476. }
  477. type ed25519PublicKey ed25519.PublicKey
  478. func (k ed25519PublicKey) Type() string {
  479. return KeyAlgoED25519
  480. }
  481. func parseED25519(in []byte) (out PublicKey, rest []byte, err error) {
  482. var w struct {
  483. KeyBytes []byte
  484. Rest []byte `ssh:"rest"`
  485. }
  486. if err := Unmarshal(in, &w); err != nil {
  487. return nil, nil, err
  488. }
  489. key := ed25519.PublicKey(w.KeyBytes)
  490. return (ed25519PublicKey)(key), w.Rest, nil
  491. }
  492. func (k ed25519PublicKey) Marshal() []byte {
  493. w := struct {
  494. Name string
  495. KeyBytes []byte
  496. }{
  497. KeyAlgoED25519,
  498. []byte(k),
  499. }
  500. return Marshal(&w)
  501. }
  502. func (k ed25519PublicKey) Verify(b []byte, sig *Signature) error {
  503. if sig.Format != k.Type() {
  504. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  505. }
  506. edKey := (ed25519.PublicKey)(k)
  507. if ok := ed25519.Verify(edKey, b, sig.Blob); !ok {
  508. return errors.New("ssh: signature did not verify")
  509. }
  510. return nil
  511. }
  512. func (k ed25519PublicKey) CryptoPublicKey() crypto.PublicKey {
  513. return ed25519.PublicKey(k)
  514. }
  515. func supportedEllipticCurve(curve elliptic.Curve) bool {
  516. return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521()
  517. }
  518. // ecHash returns the hash to match the given elliptic curve, see RFC
  519. // 5656, section 6.2.1
  520. func ecHash(curve elliptic.Curve) crypto.Hash {
  521. bitSize := curve.Params().BitSize
  522. switch {
  523. case bitSize <= 256:
  524. return crypto.SHA256
  525. case bitSize <= 384:
  526. return crypto.SHA384
  527. }
  528. return crypto.SHA512
  529. }
  530. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  531. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  532. var w struct {
  533. Curve string
  534. KeyBytes []byte
  535. Rest []byte `ssh:"rest"`
  536. }
  537. if err := Unmarshal(in, &w); err != nil {
  538. return nil, nil, err
  539. }
  540. key := new(ecdsa.PublicKey)
  541. switch w.Curve {
  542. case "nistp256":
  543. key.Curve = elliptic.P256()
  544. case "nistp384":
  545. key.Curve = elliptic.P384()
  546. case "nistp521":
  547. key.Curve = elliptic.P521()
  548. default:
  549. return nil, nil, errors.New("ssh: unsupported curve")
  550. }
  551. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  552. if key.X == nil || key.Y == nil {
  553. return nil, nil, errors.New("ssh: invalid curve point")
  554. }
  555. return (*ecdsaPublicKey)(key), w.Rest, nil
  556. }
  557. func (k *ecdsaPublicKey) Marshal() []byte {
  558. // See RFC 5656, section 3.1.
  559. keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y)
  560. // ECDSA publickey struct layout should match the struct used by
  561. // parseECDSACert in the x/crypto/ssh/agent package.
  562. w := struct {
  563. Name string
  564. ID string
  565. Key []byte
  566. }{
  567. k.Type(),
  568. k.nistID(),
  569. keyBytes,
  570. }
  571. return Marshal(&w)
  572. }
  573. func (k *ecdsaPublicKey) Verify(data []byte, sig *Signature) error {
  574. if sig.Format != k.Type() {
  575. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  576. }
  577. h := ecHash(k.Curve).New()
  578. h.Write(data)
  579. digest := h.Sum(nil)
  580. // Per RFC 5656, section 3.1.2,
  581. // The ecdsa_signature_blob value has the following specific encoding:
  582. // mpint r
  583. // mpint s
  584. var ecSig struct {
  585. R *big.Int
  586. S *big.Int
  587. }
  588. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  589. return err
  590. }
  591. if ecdsa.Verify((*ecdsa.PublicKey)(k), digest, ecSig.R, ecSig.S) {
  592. return nil
  593. }
  594. return errors.New("ssh: signature did not verify")
  595. }
  596. func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  597. return (*ecdsa.PublicKey)(k)
  598. }
  599. // skFields holds the additional fields present in U2F/FIDO2 signatures.
  600. // See openssh/PROTOCOL.u2f 'SSH U2F Signatures' for details.
  601. type skFields struct {
  602. // Flags contains U2F/FIDO2 flags such as 'user present'
  603. Flags byte
  604. // Counter is a monotonic signature counter which can be
  605. // used to detect concurrent use of a private key, should
  606. // it be extracted from hardware.
  607. Counter uint32
  608. }
  609. type skECDSAPublicKey struct {
  610. // application is a URL-like string, typically "ssh:" for SSH.
  611. // see openssh/PROTOCOL.u2f for details.
  612. application string
  613. ecdsa.PublicKey
  614. }
  615. func (k *skECDSAPublicKey) Type() string {
  616. return KeyAlgoSKECDSA256
  617. }
  618. func (k *skECDSAPublicKey) nistID() string {
  619. return "nistp256"
  620. }
  621. func parseSKECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  622. var w struct {
  623. Curve string
  624. KeyBytes []byte
  625. Application string
  626. Rest []byte `ssh:"rest"`
  627. }
  628. if err := Unmarshal(in, &w); err != nil {
  629. return nil, nil, err
  630. }
  631. key := new(skECDSAPublicKey)
  632. key.application = w.Application
  633. if w.Curve != "nistp256" {
  634. return nil, nil, errors.New("ssh: unsupported curve")
  635. }
  636. key.Curve = elliptic.P256()
  637. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  638. if key.X == nil || key.Y == nil {
  639. return nil, nil, errors.New("ssh: invalid curve point")
  640. }
  641. return key, w.Rest, nil
  642. }
  643. func (k *skECDSAPublicKey) Marshal() []byte {
  644. // See RFC 5656, section 3.1.
  645. keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y)
  646. w := struct {
  647. Name string
  648. ID string
  649. Key []byte
  650. Application string
  651. }{
  652. k.Type(),
  653. k.nistID(),
  654. keyBytes,
  655. k.application,
  656. }
  657. return Marshal(&w)
  658. }
  659. func (k *skECDSAPublicKey) Verify(data []byte, sig *Signature) error {
  660. if sig.Format != k.Type() {
  661. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  662. }
  663. h := ecHash(k.Curve).New()
  664. h.Write([]byte(k.application))
  665. appDigest := h.Sum(nil)
  666. h.Reset()
  667. h.Write(data)
  668. dataDigest := h.Sum(nil)
  669. var ecSig struct {
  670. R *big.Int
  671. S *big.Int
  672. }
  673. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  674. return err
  675. }
  676. var skf skFields
  677. if err := Unmarshal(sig.Rest, &skf); err != nil {
  678. return err
  679. }
  680. blob := struct {
  681. ApplicationDigest []byte `ssh:"rest"`
  682. Flags byte
  683. Counter uint32
  684. MessageDigest []byte `ssh:"rest"`
  685. }{
  686. appDigest,
  687. skf.Flags,
  688. skf.Counter,
  689. dataDigest,
  690. }
  691. original := Marshal(blob)
  692. h.Reset()
  693. h.Write(original)
  694. digest := h.Sum(nil)
  695. if ecdsa.Verify((*ecdsa.PublicKey)(&k.PublicKey), digest, ecSig.R, ecSig.S) {
  696. return nil
  697. }
  698. return errors.New("ssh: signature did not verify")
  699. }
  700. type skEd25519PublicKey struct {
  701. // application is a URL-like string, typically "ssh:" for SSH.
  702. // see openssh/PROTOCOL.u2f for details.
  703. application string
  704. ed25519.PublicKey
  705. }
  706. func (k *skEd25519PublicKey) Type() string {
  707. return KeyAlgoSKED25519
  708. }
  709. func parseSKEd25519(in []byte) (out PublicKey, rest []byte, err error) {
  710. var w struct {
  711. KeyBytes []byte
  712. Application string
  713. Rest []byte `ssh:"rest"`
  714. }
  715. if err := Unmarshal(in, &w); err != nil {
  716. return nil, nil, err
  717. }
  718. key := new(skEd25519PublicKey)
  719. key.application = w.Application
  720. key.PublicKey = ed25519.PublicKey(w.KeyBytes)
  721. return key, w.Rest, nil
  722. }
  723. func (k *skEd25519PublicKey) Marshal() []byte {
  724. w := struct {
  725. Name string
  726. KeyBytes []byte
  727. Application string
  728. }{
  729. KeyAlgoSKED25519,
  730. []byte(k.PublicKey),
  731. k.application,
  732. }
  733. return Marshal(&w)
  734. }
  735. func (k *skEd25519PublicKey) Verify(data []byte, sig *Signature) error {
  736. if sig.Format != k.Type() {
  737. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  738. }
  739. h := sha256.New()
  740. h.Write([]byte(k.application))
  741. appDigest := h.Sum(nil)
  742. h.Reset()
  743. h.Write(data)
  744. dataDigest := h.Sum(nil)
  745. var edSig struct {
  746. Signature []byte `ssh:"rest"`
  747. }
  748. if err := Unmarshal(sig.Blob, &edSig); err != nil {
  749. return err
  750. }
  751. var skf skFields
  752. if err := Unmarshal(sig.Rest, &skf); err != nil {
  753. return err
  754. }
  755. blob := struct {
  756. ApplicationDigest []byte `ssh:"rest"`
  757. Flags byte
  758. Counter uint32
  759. MessageDigest []byte `ssh:"rest"`
  760. }{
  761. appDigest,
  762. skf.Flags,
  763. skf.Counter,
  764. dataDigest,
  765. }
  766. original := Marshal(blob)
  767. edKey := (ed25519.PublicKey)(k.PublicKey)
  768. if ok := ed25519.Verify(edKey, original, edSig.Signature); !ok {
  769. return errors.New("ssh: signature did not verify")
  770. }
  771. return nil
  772. }
  773. // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey,
  774. // *ecdsa.PrivateKey or any other crypto.Signer and returns a
  775. // corresponding Signer instance. ECDSA keys must use P-256, P-384 or
  776. // P-521. DSA keys must use parameter size L1024N160.
  777. func NewSignerFromKey(key interface{}) (Signer, error) {
  778. switch key := key.(type) {
  779. case crypto.Signer:
  780. return NewSignerFromSigner(key)
  781. case *dsa.PrivateKey:
  782. return newDSAPrivateKey(key)
  783. default:
  784. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  785. }
  786. }
  787. func newDSAPrivateKey(key *dsa.PrivateKey) (Signer, error) {
  788. if err := checkDSAParams(&key.PublicKey.Parameters); err != nil {
  789. return nil, err
  790. }
  791. return &dsaPrivateKey{key}, nil
  792. }
  793. type wrappedSigner struct {
  794. signer crypto.Signer
  795. pubKey PublicKey
  796. }
  797. // NewSignerFromSigner takes any crypto.Signer implementation and
  798. // returns a corresponding Signer interface. This can be used, for
  799. // example, with keys kept in hardware modules.
  800. func NewSignerFromSigner(signer crypto.Signer) (Signer, error) {
  801. pubKey, err := NewPublicKey(signer.Public())
  802. if err != nil {
  803. return nil, err
  804. }
  805. return &wrappedSigner{signer, pubKey}, nil
  806. }
  807. func (s *wrappedSigner) PublicKey() PublicKey {
  808. return s.pubKey
  809. }
  810. func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  811. return s.SignWithAlgorithm(rand, data, "")
  812. }
  813. func (s *wrappedSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  814. var hashFunc crypto.Hash
  815. if _, ok := s.pubKey.(*rsaPublicKey); ok {
  816. // RSA keys support a few hash functions determined by the requested signature algorithm
  817. switch algorithm {
  818. case "", SigAlgoRSA:
  819. algorithm = SigAlgoRSA
  820. hashFunc = crypto.SHA1
  821. case SigAlgoRSASHA2256:
  822. hashFunc = crypto.SHA256
  823. case SigAlgoRSASHA2512:
  824. hashFunc = crypto.SHA512
  825. default:
  826. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  827. }
  828. } else {
  829. // The only supported algorithm for all other key types is the same as the type of the key
  830. if algorithm == "" {
  831. algorithm = s.pubKey.Type()
  832. } else if algorithm != s.pubKey.Type() {
  833. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  834. }
  835. switch key := s.pubKey.(type) {
  836. case *dsaPublicKey:
  837. hashFunc = crypto.SHA1
  838. case *ecdsaPublicKey:
  839. hashFunc = ecHash(key.Curve)
  840. case ed25519PublicKey:
  841. default:
  842. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  843. }
  844. }
  845. var digest []byte
  846. if hashFunc != 0 {
  847. h := hashFunc.New()
  848. h.Write(data)
  849. digest = h.Sum(nil)
  850. } else {
  851. digest = data
  852. }
  853. signature, err := s.signer.Sign(rand, digest, hashFunc)
  854. if err != nil {
  855. return nil, err
  856. }
  857. // crypto.Signer.Sign is expected to return an ASN.1-encoded signature
  858. // for ECDSA and DSA, but that's not the encoding expected by SSH, so
  859. // re-encode.
  860. switch s.pubKey.(type) {
  861. case *ecdsaPublicKey, *dsaPublicKey:
  862. type asn1Signature struct {
  863. R, S *big.Int
  864. }
  865. asn1Sig := new(asn1Signature)
  866. _, err := asn1.Unmarshal(signature, asn1Sig)
  867. if err != nil {
  868. return nil, err
  869. }
  870. switch s.pubKey.(type) {
  871. case *ecdsaPublicKey:
  872. signature = Marshal(asn1Sig)
  873. case *dsaPublicKey:
  874. signature = make([]byte, 40)
  875. r := asn1Sig.R.Bytes()
  876. s := asn1Sig.S.Bytes()
  877. copy(signature[20-len(r):20], r)
  878. copy(signature[40-len(s):40], s)
  879. }
  880. }
  881. return &Signature{
  882. Format: algorithm,
  883. Blob: signature,
  884. }, nil
  885. }
  886. // NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
  887. // or ed25519.PublicKey returns a corresponding PublicKey instance.
  888. // ECDSA keys must use P-256, P-384 or P-521.
  889. func NewPublicKey(key interface{}) (PublicKey, error) {
  890. switch key := key.(type) {
  891. case *rsa.PublicKey:
  892. return (*rsaPublicKey)(key), nil
  893. case *ecdsa.PublicKey:
  894. if !supportedEllipticCurve(key.Curve) {
  895. return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported")
  896. }
  897. return (*ecdsaPublicKey)(key), nil
  898. case *dsa.PublicKey:
  899. return (*dsaPublicKey)(key), nil
  900. case ed25519.PublicKey:
  901. return (ed25519PublicKey)(key), nil
  902. default:
  903. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  904. }
  905. }
  906. // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports
  907. // the same keys as ParseRawPrivateKey. If the private key is encrypted, it
  908. // will return a PassphraseMissingError.
  909. func ParsePrivateKey(pemBytes []byte) (Signer, error) {
  910. key, err := ParseRawPrivateKey(pemBytes)
  911. if err != nil {
  912. return nil, err
  913. }
  914. return NewSignerFromKey(key)
  915. }
  916. // ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private
  917. // key and passphrase. It supports the same keys as
  918. // ParseRawPrivateKeyWithPassphrase.
  919. func ParsePrivateKeyWithPassphrase(pemBytes, passphrase []byte) (Signer, error) {
  920. key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase)
  921. if err != nil {
  922. return nil, err
  923. }
  924. return NewSignerFromKey(key)
  925. }
  926. // encryptedBlock tells whether a private key is
  927. // encrypted by examining its Proc-Type header
  928. // for a mention of ENCRYPTED
  929. // according to RFC 1421 Section 4.6.1.1.
  930. func encryptedBlock(block *pem.Block) bool {
  931. return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED")
  932. }
  933. // A PassphraseMissingError indicates that parsing this private key requires a
  934. // passphrase. Use ParsePrivateKeyWithPassphrase.
  935. type PassphraseMissingError struct {
  936. // PublicKey will be set if the private key format includes an unencrypted
  937. // public key along with the encrypted private key.
  938. PublicKey PublicKey
  939. }
  940. func (*PassphraseMissingError) Error() string {
  941. return "ssh: this private key is passphrase protected"
  942. }
  943. // ParseRawPrivateKey returns a private key from a PEM encoded private key. It
  944. // supports RSA (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys. If the
  945. // private key is encrypted, it will return a PassphraseMissingError.
  946. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
  947. block, _ := pem.Decode(pemBytes)
  948. if block == nil {
  949. return nil, errors.New("ssh: no key found")
  950. }
  951. if encryptedBlock(block) {
  952. return nil, &PassphraseMissingError{}
  953. }
  954. switch block.Type {
  955. case "RSA PRIVATE KEY":
  956. return x509.ParsePKCS1PrivateKey(block.Bytes)
  957. // RFC5208 - https://tools.ietf.org/html/rfc5208
  958. case "PRIVATE KEY":
  959. return x509.ParsePKCS8PrivateKey(block.Bytes)
  960. case "EC PRIVATE KEY":
  961. return x509.ParseECPrivateKey(block.Bytes)
  962. case "DSA PRIVATE KEY":
  963. return ParseDSAPrivateKey(block.Bytes)
  964. case "OPENSSH PRIVATE KEY":
  965. return parseOpenSSHPrivateKey(block.Bytes, unencryptedOpenSSHKey)
  966. default:
  967. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  968. }
  969. }
  970. // ParseRawPrivateKeyWithPassphrase returns a private key decrypted with
  971. // passphrase from a PEM encoded private key. If the passphrase is wrong, it
  972. // will return x509.IncorrectPasswordError.
  973. func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, error) {
  974. block, _ := pem.Decode(pemBytes)
  975. if block == nil {
  976. return nil, errors.New("ssh: no key found")
  977. }
  978. if block.Type == "OPENSSH PRIVATE KEY" {
  979. return parseOpenSSHPrivateKey(block.Bytes, passphraseProtectedOpenSSHKey(passphrase))
  980. }
  981. if !encryptedBlock(block) || !x509.IsEncryptedPEMBlock(block) {
  982. return nil, errors.New("ssh: not an encrypted key")
  983. }
  984. buf, err := x509.DecryptPEMBlock(block, passphrase)
  985. if err != nil {
  986. if err == x509.IncorrectPasswordError {
  987. return nil, err
  988. }
  989. return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err)
  990. }
  991. switch block.Type {
  992. case "RSA PRIVATE KEY":
  993. return x509.ParsePKCS1PrivateKey(buf)
  994. case "EC PRIVATE KEY":
  995. return x509.ParseECPrivateKey(buf)
  996. case "DSA PRIVATE KEY":
  997. return ParseDSAPrivateKey(buf)
  998. default:
  999. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  1000. }
  1001. }
  1002. // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
  1003. // specified by the OpenSSL DSA man page.
  1004. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
  1005. var k struct {
  1006. Version int
  1007. P *big.Int
  1008. Q *big.Int
  1009. G *big.Int
  1010. Pub *big.Int
  1011. Priv *big.Int
  1012. }
  1013. rest, err := asn1.Unmarshal(der, &k)
  1014. if err != nil {
  1015. return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
  1016. }
  1017. if len(rest) > 0 {
  1018. return nil, errors.New("ssh: garbage after DSA key")
  1019. }
  1020. return &dsa.PrivateKey{
  1021. PublicKey: dsa.PublicKey{
  1022. Parameters: dsa.Parameters{
  1023. P: k.P,
  1024. Q: k.Q,
  1025. G: k.G,
  1026. },
  1027. Y: k.Pub,
  1028. },
  1029. X: k.Priv,
  1030. }, nil
  1031. }
  1032. func unencryptedOpenSSHKey(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) {
  1033. if kdfName != "none" || cipherName != "none" {
  1034. return nil, &PassphraseMissingError{}
  1035. }
  1036. if kdfOpts != "" {
  1037. return nil, errors.New("ssh: invalid openssh private key")
  1038. }
  1039. return privKeyBlock, nil
  1040. }
  1041. func passphraseProtectedOpenSSHKey(passphrase []byte) openSSHDecryptFunc {
  1042. return func(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) {
  1043. if kdfName == "none" || cipherName == "none" {
  1044. return nil, errors.New("ssh: key is not password protected")
  1045. }
  1046. if kdfName != "bcrypt" {
  1047. return nil, fmt.Errorf("ssh: unknown KDF %q, only supports %q", kdfName, "bcrypt")
  1048. }
  1049. var opts struct {
  1050. Salt string
  1051. Rounds uint32
  1052. }
  1053. if err := Unmarshal([]byte(kdfOpts), &opts); err != nil {
  1054. return nil, err
  1055. }
  1056. k, err := bcrypt_pbkdf.Key(passphrase, []byte(opts.Salt), int(opts.Rounds), 32+16)
  1057. if err != nil {
  1058. return nil, err
  1059. }
  1060. key, iv := k[:32], k[32:]
  1061. if cipherName != "aes256-ctr" {
  1062. return nil, fmt.Errorf("ssh: unknown cipher %q, only supports %q", cipherName, "aes256-ctr")
  1063. }
  1064. c, err := aes.NewCipher(key)
  1065. if err != nil {
  1066. return nil, err
  1067. }
  1068. ctr := cipher.NewCTR(c, iv)
  1069. ctr.XORKeyStream(privKeyBlock, privKeyBlock)
  1070. return privKeyBlock, nil
  1071. }
  1072. }
  1073. type openSSHDecryptFunc func(CipherName, KdfName, KdfOpts string, PrivKeyBlock []byte) ([]byte, error)
  1074. // parseOpenSSHPrivateKey parses an OpenSSH private key, using the decrypt
  1075. // function to unwrap the encrypted portion. unencryptedOpenSSHKey can be used
  1076. // as the decrypt function to parse an unencrypted private key. See
  1077. // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key.
  1078. func parseOpenSSHPrivateKey(key []byte, decrypt openSSHDecryptFunc) (crypto.PrivateKey, error) {
  1079. const magic = "openssh-key-v1\x00"
  1080. if len(key) < len(magic) || string(key[:len(magic)]) != magic {
  1081. return nil, errors.New("ssh: invalid openssh private key format")
  1082. }
  1083. remaining := key[len(magic):]
  1084. var w struct {
  1085. CipherName string
  1086. KdfName string
  1087. KdfOpts string
  1088. NumKeys uint32
  1089. PubKey []byte
  1090. PrivKeyBlock []byte
  1091. }
  1092. if err := Unmarshal(remaining, &w); err != nil {
  1093. return nil, err
  1094. }
  1095. if w.NumKeys != 1 {
  1096. // We only support single key files, and so does OpenSSH.
  1097. // https://github.com/openssh/openssh-portable/blob/4103a3ec7/sshkey.c#L4171
  1098. return nil, errors.New("ssh: multi-key files are not supported")
  1099. }
  1100. privKeyBlock, err := decrypt(w.CipherName, w.KdfName, w.KdfOpts, w.PrivKeyBlock)
  1101. if err != nil {
  1102. if err, ok := err.(*PassphraseMissingError); ok {
  1103. pub, errPub := ParsePublicKey(w.PubKey)
  1104. if errPub != nil {
  1105. return nil, fmt.Errorf("ssh: failed to parse embedded public key: %v", errPub)
  1106. }
  1107. err.PublicKey = pub
  1108. }
  1109. return nil, err
  1110. }
  1111. pk1 := struct {
  1112. Check1 uint32
  1113. Check2 uint32
  1114. Keytype string
  1115. Rest []byte `ssh:"rest"`
  1116. }{}
  1117. if err := Unmarshal(privKeyBlock, &pk1); err != nil || pk1.Check1 != pk1.Check2 {
  1118. if w.CipherName != "none" {
  1119. return nil, x509.IncorrectPasswordError
  1120. }
  1121. return nil, errors.New("ssh: malformed OpenSSH key")
  1122. }
  1123. // we only handle ed25519 and rsa keys currently
  1124. switch pk1.Keytype {
  1125. case KeyAlgoRSA:
  1126. // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L2760-L2773
  1127. key := struct {
  1128. N *big.Int
  1129. E *big.Int
  1130. D *big.Int
  1131. Iqmp *big.Int
  1132. P *big.Int
  1133. Q *big.Int
  1134. Comment string
  1135. Pad []byte `ssh:"rest"`
  1136. }{}
  1137. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1138. return nil, err
  1139. }
  1140. if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1141. return nil, err
  1142. }
  1143. pk := &rsa.PrivateKey{
  1144. PublicKey: rsa.PublicKey{
  1145. N: key.N,
  1146. E: int(key.E.Int64()),
  1147. },
  1148. D: key.D,
  1149. Primes: []*big.Int{key.P, key.Q},
  1150. }
  1151. if err := pk.Validate(); err != nil {
  1152. return nil, err
  1153. }
  1154. pk.Precompute()
  1155. return pk, nil
  1156. case KeyAlgoED25519:
  1157. key := struct {
  1158. Pub []byte
  1159. Priv []byte
  1160. Comment string
  1161. Pad []byte `ssh:"rest"`
  1162. }{}
  1163. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1164. return nil, err
  1165. }
  1166. if len(key.Priv) != ed25519.PrivateKeySize {
  1167. return nil, errors.New("ssh: private key unexpected length")
  1168. }
  1169. if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1170. return nil, err
  1171. }
  1172. pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize))
  1173. copy(pk, key.Priv)
  1174. return &pk, nil
  1175. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  1176. key := struct {
  1177. Curve string
  1178. Pub []byte
  1179. D *big.Int
  1180. Comment string
  1181. Pad []byte `ssh:"rest"`
  1182. }{}
  1183. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1184. return nil, err
  1185. }
  1186. if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1187. return nil, err
  1188. }
  1189. var curve elliptic.Curve
  1190. switch key.Curve {
  1191. case "nistp256":
  1192. curve = elliptic.P256()
  1193. case "nistp384":
  1194. curve = elliptic.P384()
  1195. case "nistp521":
  1196. curve = elliptic.P521()
  1197. default:
  1198. return nil, errors.New("ssh: unhandled elliptic curve: " + key.Curve)
  1199. }
  1200. X, Y := elliptic.Unmarshal(curve, key.Pub)
  1201. if X == nil || Y == nil {
  1202. return nil, errors.New("ssh: failed to unmarshal public key")
  1203. }
  1204. if key.D.Cmp(curve.Params().N) >= 0 {
  1205. return nil, errors.New("ssh: scalar is out of range")
  1206. }
  1207. x, y := curve.ScalarBaseMult(key.D.Bytes())
  1208. if x.Cmp(X) != 0 || y.Cmp(Y) != 0 {
  1209. return nil, errors.New("ssh: public key does not match private key")
  1210. }
  1211. return &ecdsa.PrivateKey{
  1212. PublicKey: ecdsa.PublicKey{
  1213. Curve: curve,
  1214. X: X,
  1215. Y: Y,
  1216. },
  1217. D: key.D,
  1218. }, nil
  1219. default:
  1220. return nil, errors.New("ssh: unhandled key type")
  1221. }
  1222. }
  1223. func checkOpenSSHKeyPadding(pad []byte) error {
  1224. for i, b := range pad {
  1225. if int(b) != i+1 {
  1226. return errors.New("ssh: padding not as expected")
  1227. }
  1228. }
  1229. return nil
  1230. }
  1231. // FingerprintLegacyMD5 returns the user presentation of the key's
  1232. // fingerprint as described by RFC 4716 section 4.
  1233. func FingerprintLegacyMD5(pubKey PublicKey) string {
  1234. md5sum := md5.Sum(pubKey.Marshal())
  1235. hexarray := make([]string, len(md5sum))
  1236. for i, c := range md5sum {
  1237. hexarray[i] = hex.EncodeToString([]byte{c})
  1238. }
  1239. return strings.Join(hexarray, ":")
  1240. }
  1241. // FingerprintSHA256 returns the user presentation of the key's
  1242. // fingerprint as unpadded base64 encoded sha256 hash.
  1243. // This format was introduced from OpenSSH 6.8.
  1244. // https://www.openssh.com/txt/release-6.8
  1245. // https://tools.ietf.org/html/rfc4648#section-3.2 (unpadded base64 encoding)
  1246. func FingerprintSHA256(pubKey PublicKey) string {
  1247. sha256sum := sha256.Sum256(pubKey.Marshal())
  1248. hash := base64.RawStdEncoding.EncodeToString(sha256sum[:])
  1249. return "SHA256:" + hash
  1250. }