keys.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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. if l := len(w.KeyBytes); l != ed25519.PublicKeySize {
  490. return nil, nil, fmt.Errorf("invalid size %d for Ed25519 public key", l)
  491. }
  492. return ed25519PublicKey(w.KeyBytes), w.Rest, nil
  493. }
  494. func (k ed25519PublicKey) Marshal() []byte {
  495. w := struct {
  496. Name string
  497. KeyBytes []byte
  498. }{
  499. KeyAlgoED25519,
  500. []byte(k),
  501. }
  502. return Marshal(&w)
  503. }
  504. func (k ed25519PublicKey) Verify(b []byte, sig *Signature) error {
  505. if sig.Format != k.Type() {
  506. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  507. }
  508. if l := len(k); l != ed25519.PublicKeySize {
  509. return fmt.Errorf("ssh: invalid size %d for Ed25519 public key", l)
  510. }
  511. if ok := ed25519.Verify(ed25519.PublicKey(k), b, sig.Blob); !ok {
  512. return errors.New("ssh: signature did not verify")
  513. }
  514. return nil
  515. }
  516. func (k ed25519PublicKey) CryptoPublicKey() crypto.PublicKey {
  517. return ed25519.PublicKey(k)
  518. }
  519. func supportedEllipticCurve(curve elliptic.Curve) bool {
  520. return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521()
  521. }
  522. // ecHash returns the hash to match the given elliptic curve, see RFC
  523. // 5656, section 6.2.1
  524. func ecHash(curve elliptic.Curve) crypto.Hash {
  525. bitSize := curve.Params().BitSize
  526. switch {
  527. case bitSize <= 256:
  528. return crypto.SHA256
  529. case bitSize <= 384:
  530. return crypto.SHA384
  531. }
  532. return crypto.SHA512
  533. }
  534. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  535. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  536. var w struct {
  537. Curve string
  538. KeyBytes []byte
  539. Rest []byte `ssh:"rest"`
  540. }
  541. if err := Unmarshal(in, &w); err != nil {
  542. return nil, nil, err
  543. }
  544. key := new(ecdsa.PublicKey)
  545. switch w.Curve {
  546. case "nistp256":
  547. key.Curve = elliptic.P256()
  548. case "nistp384":
  549. key.Curve = elliptic.P384()
  550. case "nistp521":
  551. key.Curve = elliptic.P521()
  552. default:
  553. return nil, nil, errors.New("ssh: unsupported curve")
  554. }
  555. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  556. if key.X == nil || key.Y == nil {
  557. return nil, nil, errors.New("ssh: invalid curve point")
  558. }
  559. return (*ecdsaPublicKey)(key), w.Rest, nil
  560. }
  561. func (k *ecdsaPublicKey) Marshal() []byte {
  562. // See RFC 5656, section 3.1.
  563. keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y)
  564. // ECDSA publickey struct layout should match the struct used by
  565. // parseECDSACert in the x/crypto/ssh/agent package.
  566. w := struct {
  567. Name string
  568. ID string
  569. Key []byte
  570. }{
  571. k.Type(),
  572. k.nistID(),
  573. keyBytes,
  574. }
  575. return Marshal(&w)
  576. }
  577. func (k *ecdsaPublicKey) Verify(data []byte, sig *Signature) error {
  578. if sig.Format != k.Type() {
  579. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  580. }
  581. h := ecHash(k.Curve).New()
  582. h.Write(data)
  583. digest := h.Sum(nil)
  584. // Per RFC 5656, section 3.1.2,
  585. // The ecdsa_signature_blob value has the following specific encoding:
  586. // mpint r
  587. // mpint s
  588. var ecSig struct {
  589. R *big.Int
  590. S *big.Int
  591. }
  592. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  593. return err
  594. }
  595. if ecdsa.Verify((*ecdsa.PublicKey)(k), digest, ecSig.R, ecSig.S) {
  596. return nil
  597. }
  598. return errors.New("ssh: signature did not verify")
  599. }
  600. func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  601. return (*ecdsa.PublicKey)(k)
  602. }
  603. // skFields holds the additional fields present in U2F/FIDO2 signatures.
  604. // See openssh/PROTOCOL.u2f 'SSH U2F Signatures' for details.
  605. type skFields struct {
  606. // Flags contains U2F/FIDO2 flags such as 'user present'
  607. Flags byte
  608. // Counter is a monotonic signature counter which can be
  609. // used to detect concurrent use of a private key, should
  610. // it be extracted from hardware.
  611. Counter uint32
  612. }
  613. type skECDSAPublicKey struct {
  614. // application is a URL-like string, typically "ssh:" for SSH.
  615. // see openssh/PROTOCOL.u2f for details.
  616. application string
  617. ecdsa.PublicKey
  618. }
  619. func (k *skECDSAPublicKey) Type() string {
  620. return KeyAlgoSKECDSA256
  621. }
  622. func (k *skECDSAPublicKey) nistID() string {
  623. return "nistp256"
  624. }
  625. func parseSKECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  626. var w struct {
  627. Curve string
  628. KeyBytes []byte
  629. Application string
  630. Rest []byte `ssh:"rest"`
  631. }
  632. if err := Unmarshal(in, &w); err != nil {
  633. return nil, nil, err
  634. }
  635. key := new(skECDSAPublicKey)
  636. key.application = w.Application
  637. if w.Curve != "nistp256" {
  638. return nil, nil, errors.New("ssh: unsupported curve")
  639. }
  640. key.Curve = elliptic.P256()
  641. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  642. if key.X == nil || key.Y == nil {
  643. return nil, nil, errors.New("ssh: invalid curve point")
  644. }
  645. return key, w.Rest, nil
  646. }
  647. func (k *skECDSAPublicKey) Marshal() []byte {
  648. // See RFC 5656, section 3.1.
  649. keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y)
  650. w := struct {
  651. Name string
  652. ID string
  653. Key []byte
  654. Application string
  655. }{
  656. k.Type(),
  657. k.nistID(),
  658. keyBytes,
  659. k.application,
  660. }
  661. return Marshal(&w)
  662. }
  663. func (k *skECDSAPublicKey) Verify(data []byte, sig *Signature) error {
  664. if sig.Format != k.Type() {
  665. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  666. }
  667. h := ecHash(k.Curve).New()
  668. h.Write([]byte(k.application))
  669. appDigest := h.Sum(nil)
  670. h.Reset()
  671. h.Write(data)
  672. dataDigest := h.Sum(nil)
  673. var ecSig struct {
  674. R *big.Int
  675. S *big.Int
  676. }
  677. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  678. return err
  679. }
  680. var skf skFields
  681. if err := Unmarshal(sig.Rest, &skf); err != nil {
  682. return err
  683. }
  684. blob := struct {
  685. ApplicationDigest []byte `ssh:"rest"`
  686. Flags byte
  687. Counter uint32
  688. MessageDigest []byte `ssh:"rest"`
  689. }{
  690. appDigest,
  691. skf.Flags,
  692. skf.Counter,
  693. dataDigest,
  694. }
  695. original := Marshal(blob)
  696. h.Reset()
  697. h.Write(original)
  698. digest := h.Sum(nil)
  699. if ecdsa.Verify((*ecdsa.PublicKey)(&k.PublicKey), digest, ecSig.R, ecSig.S) {
  700. return nil
  701. }
  702. return errors.New("ssh: signature did not verify")
  703. }
  704. type skEd25519PublicKey struct {
  705. // application is a URL-like string, typically "ssh:" for SSH.
  706. // see openssh/PROTOCOL.u2f for details.
  707. application string
  708. ed25519.PublicKey
  709. }
  710. func (k *skEd25519PublicKey) Type() string {
  711. return KeyAlgoSKED25519
  712. }
  713. func parseSKEd25519(in []byte) (out PublicKey, rest []byte, err error) {
  714. var w struct {
  715. KeyBytes []byte
  716. Application string
  717. Rest []byte `ssh:"rest"`
  718. }
  719. if err := Unmarshal(in, &w); err != nil {
  720. return nil, nil, err
  721. }
  722. if l := len(w.KeyBytes); l != ed25519.PublicKeySize {
  723. return nil, nil, fmt.Errorf("invalid size %d for Ed25519 public key", l)
  724. }
  725. key := new(skEd25519PublicKey)
  726. key.application = w.Application
  727. key.PublicKey = ed25519.PublicKey(w.KeyBytes)
  728. return key, w.Rest, nil
  729. }
  730. func (k *skEd25519PublicKey) Marshal() []byte {
  731. w := struct {
  732. Name string
  733. KeyBytes []byte
  734. Application string
  735. }{
  736. KeyAlgoSKED25519,
  737. []byte(k.PublicKey),
  738. k.application,
  739. }
  740. return Marshal(&w)
  741. }
  742. func (k *skEd25519PublicKey) Verify(data []byte, sig *Signature) error {
  743. if sig.Format != k.Type() {
  744. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  745. }
  746. if l := len(k.PublicKey); l != ed25519.PublicKeySize {
  747. return fmt.Errorf("invalid size %d for Ed25519 public key", l)
  748. }
  749. h := sha256.New()
  750. h.Write([]byte(k.application))
  751. appDigest := h.Sum(nil)
  752. h.Reset()
  753. h.Write(data)
  754. dataDigest := h.Sum(nil)
  755. var edSig struct {
  756. Signature []byte `ssh:"rest"`
  757. }
  758. if err := Unmarshal(sig.Blob, &edSig); err != nil {
  759. return err
  760. }
  761. var skf skFields
  762. if err := Unmarshal(sig.Rest, &skf); err != nil {
  763. return err
  764. }
  765. blob := struct {
  766. ApplicationDigest []byte `ssh:"rest"`
  767. Flags byte
  768. Counter uint32
  769. MessageDigest []byte `ssh:"rest"`
  770. }{
  771. appDigest,
  772. skf.Flags,
  773. skf.Counter,
  774. dataDigest,
  775. }
  776. original := Marshal(blob)
  777. if ok := ed25519.Verify(k.PublicKey, original, edSig.Signature); !ok {
  778. return errors.New("ssh: signature did not verify")
  779. }
  780. return nil
  781. }
  782. // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey,
  783. // *ecdsa.PrivateKey or any other crypto.Signer and returns a
  784. // corresponding Signer instance. ECDSA keys must use P-256, P-384 or
  785. // P-521. DSA keys must use parameter size L1024N160.
  786. func NewSignerFromKey(key interface{}) (Signer, error) {
  787. switch key := key.(type) {
  788. case crypto.Signer:
  789. return NewSignerFromSigner(key)
  790. case *dsa.PrivateKey:
  791. return newDSAPrivateKey(key)
  792. default:
  793. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  794. }
  795. }
  796. func newDSAPrivateKey(key *dsa.PrivateKey) (Signer, error) {
  797. if err := checkDSAParams(&key.PublicKey.Parameters); err != nil {
  798. return nil, err
  799. }
  800. return &dsaPrivateKey{key}, nil
  801. }
  802. type rsaSigner struct {
  803. AlgorithmSigner
  804. defaultAlgorithm string
  805. }
  806. func (s *rsaSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  807. return s.AlgorithmSigner.SignWithAlgorithm(rand, data, s.defaultAlgorithm)
  808. }
  809. type wrappedSigner struct {
  810. signer crypto.Signer
  811. pubKey PublicKey
  812. }
  813. // NewSignerFromSigner takes any crypto.Signer implementation and
  814. // returns a corresponding Signer interface. This can be used, for
  815. // example, with keys kept in hardware modules.
  816. func NewSignerFromSigner(signer crypto.Signer) (Signer, error) {
  817. pubKey, err := NewPublicKey(signer.Public())
  818. if err != nil {
  819. return nil, err
  820. }
  821. return &wrappedSigner{signer, pubKey}, nil
  822. }
  823. func (s *wrappedSigner) PublicKey() PublicKey {
  824. return s.pubKey
  825. }
  826. func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  827. return s.SignWithAlgorithm(rand, data, "")
  828. }
  829. func (s *wrappedSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  830. var hashFunc crypto.Hash
  831. if _, ok := s.pubKey.(*rsaPublicKey); ok {
  832. // RSA keys support a few hash functions determined by the requested signature algorithm
  833. switch algorithm {
  834. case "", SigAlgoRSA:
  835. algorithm = SigAlgoRSA
  836. hashFunc = crypto.SHA1
  837. case SigAlgoRSASHA2256:
  838. hashFunc = crypto.SHA256
  839. case SigAlgoRSASHA2512:
  840. hashFunc = crypto.SHA512
  841. default:
  842. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  843. }
  844. } else {
  845. // The only supported algorithm for all other key types is the same as the type of the key
  846. if algorithm == "" {
  847. algorithm = s.pubKey.Type()
  848. } else if algorithm != s.pubKey.Type() {
  849. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  850. }
  851. switch key := s.pubKey.(type) {
  852. case *dsaPublicKey:
  853. hashFunc = crypto.SHA1
  854. case *ecdsaPublicKey:
  855. hashFunc = ecHash(key.Curve)
  856. case ed25519PublicKey:
  857. default:
  858. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  859. }
  860. }
  861. var digest []byte
  862. if hashFunc != 0 {
  863. h := hashFunc.New()
  864. h.Write(data)
  865. digest = h.Sum(nil)
  866. } else {
  867. digest = data
  868. }
  869. signature, err := s.signer.Sign(rand, digest, hashFunc)
  870. if err != nil {
  871. return nil, err
  872. }
  873. // crypto.Signer.Sign is expected to return an ASN.1-encoded signature
  874. // for ECDSA and DSA, but that's not the encoding expected by SSH, so
  875. // re-encode.
  876. switch s.pubKey.(type) {
  877. case *ecdsaPublicKey, *dsaPublicKey:
  878. type asn1Signature struct {
  879. R, S *big.Int
  880. }
  881. asn1Sig := new(asn1Signature)
  882. _, err := asn1.Unmarshal(signature, asn1Sig)
  883. if err != nil {
  884. return nil, err
  885. }
  886. switch s.pubKey.(type) {
  887. case *ecdsaPublicKey:
  888. signature = Marshal(asn1Sig)
  889. case *dsaPublicKey:
  890. signature = make([]byte, 40)
  891. r := asn1Sig.R.Bytes()
  892. s := asn1Sig.S.Bytes()
  893. copy(signature[20-len(r):20], r)
  894. copy(signature[40-len(s):40], s)
  895. }
  896. }
  897. return &Signature{
  898. Format: algorithm,
  899. Blob: signature,
  900. }, nil
  901. }
  902. // NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
  903. // or ed25519.PublicKey returns a corresponding PublicKey instance.
  904. // ECDSA keys must use P-256, P-384 or P-521.
  905. func NewPublicKey(key interface{}) (PublicKey, error) {
  906. switch key := key.(type) {
  907. case *rsa.PublicKey:
  908. return (*rsaPublicKey)(key), nil
  909. case *ecdsa.PublicKey:
  910. if !supportedEllipticCurve(key.Curve) {
  911. return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported")
  912. }
  913. return (*ecdsaPublicKey)(key), nil
  914. case *dsa.PublicKey:
  915. return (*dsaPublicKey)(key), nil
  916. case ed25519.PublicKey:
  917. if l := len(key); l != ed25519.PublicKeySize {
  918. return nil, fmt.Errorf("ssh: invalid size %d for Ed25519 public key", l)
  919. }
  920. return ed25519PublicKey(key), nil
  921. default:
  922. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  923. }
  924. }
  925. // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports
  926. // the same keys as ParseRawPrivateKey. If the private key is encrypted, it
  927. // will return a PassphraseMissingError.
  928. func ParsePrivateKey(pemBytes []byte) (Signer, error) {
  929. key, err := ParseRawPrivateKey(pemBytes)
  930. if err != nil {
  931. return nil, err
  932. }
  933. return NewSignerFromKey(key)
  934. }
  935. // ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private
  936. // key and passphrase. It supports the same keys as
  937. // ParseRawPrivateKeyWithPassphrase.
  938. func ParsePrivateKeyWithPassphrase(pemBytes, passphrase []byte) (Signer, error) {
  939. key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase)
  940. if err != nil {
  941. return nil, err
  942. }
  943. return NewSignerFromKey(key)
  944. }
  945. // encryptedBlock tells whether a private key is
  946. // encrypted by examining its Proc-Type header
  947. // for a mention of ENCRYPTED
  948. // according to RFC 1421 Section 4.6.1.1.
  949. func encryptedBlock(block *pem.Block) bool {
  950. return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED")
  951. }
  952. // A PassphraseMissingError indicates that parsing this private key requires a
  953. // passphrase. Use ParsePrivateKeyWithPassphrase.
  954. type PassphraseMissingError struct {
  955. // PublicKey will be set if the private key format includes an unencrypted
  956. // public key along with the encrypted private key.
  957. PublicKey PublicKey
  958. }
  959. func (*PassphraseMissingError) Error() string {
  960. return "ssh: this private key is passphrase protected"
  961. }
  962. // ParseRawPrivateKey returns a private key from a PEM encoded private key. It
  963. // supports RSA (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys. If the
  964. // private key is encrypted, it will return a PassphraseMissingError.
  965. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
  966. block, _ := pem.Decode(pemBytes)
  967. if block == nil {
  968. return nil, errors.New("ssh: no key found")
  969. }
  970. if encryptedBlock(block) {
  971. return nil, &PassphraseMissingError{}
  972. }
  973. switch block.Type {
  974. case "RSA PRIVATE KEY":
  975. return x509.ParsePKCS1PrivateKey(block.Bytes)
  976. // RFC5208 - https://tools.ietf.org/html/rfc5208
  977. case "PRIVATE KEY":
  978. return x509.ParsePKCS8PrivateKey(block.Bytes)
  979. case "EC PRIVATE KEY":
  980. return x509.ParseECPrivateKey(block.Bytes)
  981. case "DSA PRIVATE KEY":
  982. return ParseDSAPrivateKey(block.Bytes)
  983. case "OPENSSH PRIVATE KEY":
  984. return parseOpenSSHPrivateKey(block.Bytes, unencryptedOpenSSHKey)
  985. default:
  986. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  987. }
  988. }
  989. // ParseRawPrivateKeyWithPassphrase returns a private key decrypted with
  990. // passphrase from a PEM encoded private key. If the passphrase is wrong, it
  991. // will return x509.IncorrectPasswordError.
  992. func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, error) {
  993. block, _ := pem.Decode(pemBytes)
  994. if block == nil {
  995. return nil, errors.New("ssh: no key found")
  996. }
  997. if block.Type == "OPENSSH PRIVATE KEY" {
  998. return parseOpenSSHPrivateKey(block.Bytes, passphraseProtectedOpenSSHKey(passphrase))
  999. }
  1000. if !encryptedBlock(block) || !x509.IsEncryptedPEMBlock(block) {
  1001. return nil, errors.New("ssh: not an encrypted key")
  1002. }
  1003. buf, err := x509.DecryptPEMBlock(block, passphrase)
  1004. if err != nil {
  1005. if err == x509.IncorrectPasswordError {
  1006. return nil, err
  1007. }
  1008. return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err)
  1009. }
  1010. switch block.Type {
  1011. case "RSA PRIVATE KEY":
  1012. return x509.ParsePKCS1PrivateKey(buf)
  1013. case "EC PRIVATE KEY":
  1014. return x509.ParseECPrivateKey(buf)
  1015. case "DSA PRIVATE KEY":
  1016. return ParseDSAPrivateKey(buf)
  1017. default:
  1018. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  1019. }
  1020. }
  1021. // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
  1022. // specified by the OpenSSL DSA man page.
  1023. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
  1024. var k struct {
  1025. Version int
  1026. P *big.Int
  1027. Q *big.Int
  1028. G *big.Int
  1029. Pub *big.Int
  1030. Priv *big.Int
  1031. }
  1032. rest, err := asn1.Unmarshal(der, &k)
  1033. if err != nil {
  1034. return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
  1035. }
  1036. if len(rest) > 0 {
  1037. return nil, errors.New("ssh: garbage after DSA key")
  1038. }
  1039. return &dsa.PrivateKey{
  1040. PublicKey: dsa.PublicKey{
  1041. Parameters: dsa.Parameters{
  1042. P: k.P,
  1043. Q: k.Q,
  1044. G: k.G,
  1045. },
  1046. Y: k.Pub,
  1047. },
  1048. X: k.Priv,
  1049. }, nil
  1050. }
  1051. func unencryptedOpenSSHKey(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) {
  1052. if kdfName != "none" || cipherName != "none" {
  1053. return nil, &PassphraseMissingError{}
  1054. }
  1055. if kdfOpts != "" {
  1056. return nil, errors.New("ssh: invalid openssh private key")
  1057. }
  1058. return privKeyBlock, nil
  1059. }
  1060. func passphraseProtectedOpenSSHKey(passphrase []byte) openSSHDecryptFunc {
  1061. return func(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) {
  1062. if kdfName == "none" || cipherName == "none" {
  1063. return nil, errors.New("ssh: key is not password protected")
  1064. }
  1065. if kdfName != "bcrypt" {
  1066. return nil, fmt.Errorf("ssh: unknown KDF %q, only supports %q", kdfName, "bcrypt")
  1067. }
  1068. var opts struct {
  1069. Salt string
  1070. Rounds uint32
  1071. }
  1072. if err := Unmarshal([]byte(kdfOpts), &opts); err != nil {
  1073. return nil, err
  1074. }
  1075. k, err := bcrypt_pbkdf.Key(passphrase, []byte(opts.Salt), int(opts.Rounds), 32+16)
  1076. if err != nil {
  1077. return nil, err
  1078. }
  1079. key, iv := k[:32], k[32:]
  1080. c, err := aes.NewCipher(key)
  1081. if err != nil {
  1082. return nil, err
  1083. }
  1084. switch cipherName {
  1085. case "aes256-ctr":
  1086. ctr := cipher.NewCTR(c, iv)
  1087. ctr.XORKeyStream(privKeyBlock, privKeyBlock)
  1088. case "aes256-cbc":
  1089. if len(privKeyBlock)%c.BlockSize() != 0 {
  1090. return nil, fmt.Errorf("ssh: invalid encrypted private key length, not a multiple of the block size")
  1091. }
  1092. cbc := cipher.NewCBCDecrypter(c, iv)
  1093. cbc.CryptBlocks(privKeyBlock, privKeyBlock)
  1094. default:
  1095. return nil, fmt.Errorf("ssh: unknown cipher %q, only supports %q or %q", cipherName, "aes256-ctr", "aes256-cbc")
  1096. }
  1097. return privKeyBlock, nil
  1098. }
  1099. }
  1100. type openSSHDecryptFunc func(CipherName, KdfName, KdfOpts string, PrivKeyBlock []byte) ([]byte, error)
  1101. // parseOpenSSHPrivateKey parses an OpenSSH private key, using the decrypt
  1102. // function to unwrap the encrypted portion. unencryptedOpenSSHKey can be used
  1103. // as the decrypt function to parse an unencrypted private key. See
  1104. // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key.
  1105. func parseOpenSSHPrivateKey(key []byte, decrypt openSSHDecryptFunc) (crypto.PrivateKey, error) {
  1106. const magic = "openssh-key-v1\x00"
  1107. if len(key) < len(magic) || string(key[:len(magic)]) != magic {
  1108. return nil, errors.New("ssh: invalid openssh private key format")
  1109. }
  1110. remaining := key[len(magic):]
  1111. var w struct {
  1112. CipherName string
  1113. KdfName string
  1114. KdfOpts string
  1115. NumKeys uint32
  1116. PubKey []byte
  1117. PrivKeyBlock []byte
  1118. }
  1119. if err := Unmarshal(remaining, &w); err != nil {
  1120. return nil, err
  1121. }
  1122. if w.NumKeys != 1 {
  1123. // We only support single key files, and so does OpenSSH.
  1124. // https://github.com/openssh/openssh-portable/blob/4103a3ec7/sshkey.c#L4171
  1125. return nil, errors.New("ssh: multi-key files are not supported")
  1126. }
  1127. privKeyBlock, err := decrypt(w.CipherName, w.KdfName, w.KdfOpts, w.PrivKeyBlock)
  1128. if err != nil {
  1129. if err, ok := err.(*PassphraseMissingError); ok {
  1130. pub, errPub := ParsePublicKey(w.PubKey)
  1131. if errPub != nil {
  1132. return nil, fmt.Errorf("ssh: failed to parse embedded public key: %v", errPub)
  1133. }
  1134. err.PublicKey = pub
  1135. }
  1136. return nil, err
  1137. }
  1138. pk1 := struct {
  1139. Check1 uint32
  1140. Check2 uint32
  1141. Keytype string
  1142. Rest []byte `ssh:"rest"`
  1143. }{}
  1144. if err := Unmarshal(privKeyBlock, &pk1); err != nil || pk1.Check1 != pk1.Check2 {
  1145. if w.CipherName != "none" {
  1146. return nil, x509.IncorrectPasswordError
  1147. }
  1148. return nil, errors.New("ssh: malformed OpenSSH key")
  1149. }
  1150. switch pk1.Keytype {
  1151. case KeyAlgoRSA:
  1152. // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L2760-L2773
  1153. key := struct {
  1154. N *big.Int
  1155. E *big.Int
  1156. D *big.Int
  1157. Iqmp *big.Int
  1158. P *big.Int
  1159. Q *big.Int
  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 err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1167. return nil, err
  1168. }
  1169. pk := &rsa.PrivateKey{
  1170. PublicKey: rsa.PublicKey{
  1171. N: key.N,
  1172. E: int(key.E.Int64()),
  1173. },
  1174. D: key.D,
  1175. Primes: []*big.Int{key.P, key.Q},
  1176. }
  1177. if err := pk.Validate(); err != nil {
  1178. return nil, err
  1179. }
  1180. pk.Precompute()
  1181. return pk, nil
  1182. case KeyAlgoED25519:
  1183. key := struct {
  1184. Pub []byte
  1185. Priv []byte
  1186. Comment string
  1187. Pad []byte `ssh:"rest"`
  1188. }{}
  1189. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1190. return nil, err
  1191. }
  1192. if len(key.Priv) != ed25519.PrivateKeySize {
  1193. return nil, errors.New("ssh: private key unexpected length")
  1194. }
  1195. if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1196. return nil, err
  1197. }
  1198. pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize))
  1199. copy(pk, key.Priv)
  1200. return &pk, nil
  1201. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  1202. key := struct {
  1203. Curve string
  1204. Pub []byte
  1205. D *big.Int
  1206. Comment string
  1207. Pad []byte `ssh:"rest"`
  1208. }{}
  1209. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1210. return nil, err
  1211. }
  1212. if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1213. return nil, err
  1214. }
  1215. var curve elliptic.Curve
  1216. switch key.Curve {
  1217. case "nistp256":
  1218. curve = elliptic.P256()
  1219. case "nistp384":
  1220. curve = elliptic.P384()
  1221. case "nistp521":
  1222. curve = elliptic.P521()
  1223. default:
  1224. return nil, errors.New("ssh: unhandled elliptic curve: " + key.Curve)
  1225. }
  1226. X, Y := elliptic.Unmarshal(curve, key.Pub)
  1227. if X == nil || Y == nil {
  1228. return nil, errors.New("ssh: failed to unmarshal public key")
  1229. }
  1230. if key.D.Cmp(curve.Params().N) >= 0 {
  1231. return nil, errors.New("ssh: scalar is out of range")
  1232. }
  1233. x, y := curve.ScalarBaseMult(key.D.Bytes())
  1234. if x.Cmp(X) != 0 || y.Cmp(Y) != 0 {
  1235. return nil, errors.New("ssh: public key does not match private key")
  1236. }
  1237. return &ecdsa.PrivateKey{
  1238. PublicKey: ecdsa.PublicKey{
  1239. Curve: curve,
  1240. X: X,
  1241. Y: Y,
  1242. },
  1243. D: key.D,
  1244. }, nil
  1245. default:
  1246. return nil, errors.New("ssh: unhandled key type")
  1247. }
  1248. }
  1249. func checkOpenSSHKeyPadding(pad []byte) error {
  1250. for i, b := range pad {
  1251. if int(b) != i+1 {
  1252. return errors.New("ssh: padding not as expected")
  1253. }
  1254. }
  1255. return nil
  1256. }
  1257. // FingerprintLegacyMD5 returns the user presentation of the key's
  1258. // fingerprint as described by RFC 4716 section 4.
  1259. func FingerprintLegacyMD5(pubKey PublicKey) string {
  1260. md5sum := md5.Sum(pubKey.Marshal())
  1261. hexarray := make([]string, len(md5sum))
  1262. for i, c := range md5sum {
  1263. hexarray[i] = hex.EncodeToString([]byte{c})
  1264. }
  1265. return strings.Join(hexarray, ":")
  1266. }
  1267. // FingerprintSHA256 returns the user presentation of the key's
  1268. // fingerprint as unpadded base64 encoded sha256 hash.
  1269. // This format was introduced from OpenSSH 6.8.
  1270. // https://www.openssh.com/txt/release-6.8
  1271. // https://tools.ietf.org/html/rfc4648#section-3.2 (unpadded base64 encoding)
  1272. func FingerprintSHA256(pubKey PublicKey) string {
  1273. sha256sum := sha256.Sum256(pubKey.Marshal())
  1274. hash := base64.RawStdEncoding.EncodeToString(sha256sum[:])
  1275. return "SHA256:" + hash
  1276. }