keys.go 37 KB

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