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

keys.go 37KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  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 wrappedSigner struct {
  803. signer crypto.Signer
  804. pubKey PublicKey
  805. }
  806. // NewSignerFromSigner takes any crypto.Signer implementation and
  807. // returns a corresponding Signer interface. This can be used, for
  808. // example, with keys kept in hardware modules.
  809. func NewSignerFromSigner(signer crypto.Signer) (Signer, error) {
  810. pubKey, err := NewPublicKey(signer.Public())
  811. if err != nil {
  812. return nil, err
  813. }
  814. return &wrappedSigner{signer, pubKey}, nil
  815. }
  816. func (s *wrappedSigner) PublicKey() PublicKey {
  817. return s.pubKey
  818. }
  819. func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  820. return s.SignWithAlgorithm(rand, data, "")
  821. }
  822. func (s *wrappedSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  823. var hashFunc crypto.Hash
  824. if _, ok := s.pubKey.(*rsaPublicKey); ok {
  825. // RSA keys support a few hash functions determined by the requested signature algorithm
  826. switch algorithm {
  827. case "", SigAlgoRSA:
  828. algorithm = SigAlgoRSA
  829. hashFunc = crypto.SHA1
  830. case SigAlgoRSASHA2256:
  831. hashFunc = crypto.SHA256
  832. case SigAlgoRSASHA2512:
  833. hashFunc = crypto.SHA512
  834. default:
  835. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  836. }
  837. } else {
  838. // The only supported algorithm for all other key types is the same as the type of the key
  839. if algorithm == "" {
  840. algorithm = s.pubKey.Type()
  841. } else if algorithm != s.pubKey.Type() {
  842. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  843. }
  844. switch key := s.pubKey.(type) {
  845. case *dsaPublicKey:
  846. hashFunc = crypto.SHA1
  847. case *ecdsaPublicKey:
  848. hashFunc = ecHash(key.Curve)
  849. case ed25519PublicKey:
  850. default:
  851. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  852. }
  853. }
  854. var digest []byte
  855. if hashFunc != 0 {
  856. h := hashFunc.New()
  857. h.Write(data)
  858. digest = h.Sum(nil)
  859. } else {
  860. digest = data
  861. }
  862. signature, err := s.signer.Sign(rand, digest, hashFunc)
  863. if err != nil {
  864. return nil, err
  865. }
  866. // crypto.Signer.Sign is expected to return an ASN.1-encoded signature
  867. // for ECDSA and DSA, but that's not the encoding expected by SSH, so
  868. // re-encode.
  869. switch s.pubKey.(type) {
  870. case *ecdsaPublicKey, *dsaPublicKey:
  871. type asn1Signature struct {
  872. R, S *big.Int
  873. }
  874. asn1Sig := new(asn1Signature)
  875. _, err := asn1.Unmarshal(signature, asn1Sig)
  876. if err != nil {
  877. return nil, err
  878. }
  879. switch s.pubKey.(type) {
  880. case *ecdsaPublicKey:
  881. signature = Marshal(asn1Sig)
  882. case *dsaPublicKey:
  883. signature = make([]byte, 40)
  884. r := asn1Sig.R.Bytes()
  885. s := asn1Sig.S.Bytes()
  886. copy(signature[20-len(r):20], r)
  887. copy(signature[40-len(s):40], s)
  888. }
  889. }
  890. return &Signature{
  891. Format: algorithm,
  892. Blob: signature,
  893. }, nil
  894. }
  895. // NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
  896. // or ed25519.PublicKey returns a corresponding PublicKey instance.
  897. // ECDSA keys must use P-256, P-384 or P-521.
  898. func NewPublicKey(key interface{}) (PublicKey, error) {
  899. switch key := key.(type) {
  900. case *rsa.PublicKey:
  901. return (*rsaPublicKey)(key), nil
  902. case *ecdsa.PublicKey:
  903. if !supportedEllipticCurve(key.Curve) {
  904. return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported")
  905. }
  906. return (*ecdsaPublicKey)(key), nil
  907. case *dsa.PublicKey:
  908. return (*dsaPublicKey)(key), nil
  909. case ed25519.PublicKey:
  910. if l := len(key); l != ed25519.PublicKeySize {
  911. return nil, fmt.Errorf("ssh: invalid size %d for Ed25519 public key", l)
  912. }
  913. return ed25519PublicKey(key), nil
  914. default:
  915. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  916. }
  917. }
  918. // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports
  919. // the same keys as ParseRawPrivateKey. If the private key is encrypted, it
  920. // will return a PassphraseMissingError.
  921. func ParsePrivateKey(pemBytes []byte) (Signer, error) {
  922. key, err := ParseRawPrivateKey(pemBytes)
  923. if err != nil {
  924. return nil, err
  925. }
  926. return NewSignerFromKey(key)
  927. }
  928. // ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private
  929. // key and passphrase. It supports the same keys as
  930. // ParseRawPrivateKeyWithPassphrase.
  931. func ParsePrivateKeyWithPassphrase(pemBytes, passphrase []byte) (Signer, error) {
  932. key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase)
  933. if err != nil {
  934. return nil, err
  935. }
  936. return NewSignerFromKey(key)
  937. }
  938. // encryptedBlock tells whether a private key is
  939. // encrypted by examining its Proc-Type header
  940. // for a mention of ENCRYPTED
  941. // according to RFC 1421 Section 4.6.1.1.
  942. func encryptedBlock(block *pem.Block) bool {
  943. return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED")
  944. }
  945. // A PassphraseMissingError indicates that parsing this private key requires a
  946. // passphrase. Use ParsePrivateKeyWithPassphrase.
  947. type PassphraseMissingError struct {
  948. // PublicKey will be set if the private key format includes an unencrypted
  949. // public key along with the encrypted private key.
  950. PublicKey PublicKey
  951. }
  952. func (*PassphraseMissingError) Error() string {
  953. return "ssh: this private key is passphrase protected"
  954. }
  955. // ParseRawPrivateKey returns a private key from a PEM encoded private key. It
  956. // supports RSA (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys. If the
  957. // private key is encrypted, it will return a PassphraseMissingError.
  958. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
  959. block, _ := pem.Decode(pemBytes)
  960. if block == nil {
  961. return nil, errors.New("ssh: no key found")
  962. }
  963. if encryptedBlock(block) {
  964. return nil, &PassphraseMissingError{}
  965. }
  966. switch block.Type {
  967. case "RSA PRIVATE KEY":
  968. return x509.ParsePKCS1PrivateKey(block.Bytes)
  969. // RFC5208 - https://tools.ietf.org/html/rfc5208
  970. case "PRIVATE KEY":
  971. return x509.ParsePKCS8PrivateKey(block.Bytes)
  972. case "EC PRIVATE KEY":
  973. return x509.ParseECPrivateKey(block.Bytes)
  974. case "DSA PRIVATE KEY":
  975. return ParseDSAPrivateKey(block.Bytes)
  976. case "OPENSSH PRIVATE KEY":
  977. return parseOpenSSHPrivateKey(block.Bytes, unencryptedOpenSSHKey)
  978. default:
  979. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  980. }
  981. }
  982. // ParseRawPrivateKeyWithPassphrase returns a private key decrypted with
  983. // passphrase from a PEM encoded private key. If the passphrase is wrong, it
  984. // will return x509.IncorrectPasswordError.
  985. func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, error) {
  986. block, _ := pem.Decode(pemBytes)
  987. if block == nil {
  988. return nil, errors.New("ssh: no key found")
  989. }
  990. if block.Type == "OPENSSH PRIVATE KEY" {
  991. return parseOpenSSHPrivateKey(block.Bytes, passphraseProtectedOpenSSHKey(passphrase))
  992. }
  993. if !encryptedBlock(block) || !x509.IsEncryptedPEMBlock(block) {
  994. return nil, errors.New("ssh: not an encrypted key")
  995. }
  996. buf, err := x509.DecryptPEMBlock(block, passphrase)
  997. if err != nil {
  998. if err == x509.IncorrectPasswordError {
  999. return nil, err
  1000. }
  1001. return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err)
  1002. }
  1003. switch block.Type {
  1004. case "RSA PRIVATE KEY":
  1005. return x509.ParsePKCS1PrivateKey(buf)
  1006. case "EC PRIVATE KEY":
  1007. return x509.ParseECPrivateKey(buf)
  1008. case "DSA PRIVATE KEY":
  1009. return ParseDSAPrivateKey(buf)
  1010. default:
  1011. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  1012. }
  1013. }
  1014. // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
  1015. // specified by the OpenSSL DSA man page.
  1016. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
  1017. var k struct {
  1018. Version int
  1019. P *big.Int
  1020. Q *big.Int
  1021. G *big.Int
  1022. Pub *big.Int
  1023. Priv *big.Int
  1024. }
  1025. rest, err := asn1.Unmarshal(der, &k)
  1026. if err != nil {
  1027. return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
  1028. }
  1029. if len(rest) > 0 {
  1030. return nil, errors.New("ssh: garbage after DSA key")
  1031. }
  1032. return &dsa.PrivateKey{
  1033. PublicKey: dsa.PublicKey{
  1034. Parameters: dsa.Parameters{
  1035. P: k.P,
  1036. Q: k.Q,
  1037. G: k.G,
  1038. },
  1039. Y: k.Pub,
  1040. },
  1041. X: k.Priv,
  1042. }, nil
  1043. }
  1044. func unencryptedOpenSSHKey(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) {
  1045. if kdfName != "none" || cipherName != "none" {
  1046. return nil, &PassphraseMissingError{}
  1047. }
  1048. if kdfOpts != "" {
  1049. return nil, errors.New("ssh: invalid openssh private key")
  1050. }
  1051. return privKeyBlock, nil
  1052. }
  1053. func passphraseProtectedOpenSSHKey(passphrase []byte) openSSHDecryptFunc {
  1054. return func(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) {
  1055. if kdfName == "none" || cipherName == "none" {
  1056. return nil, errors.New("ssh: key is not password protected")
  1057. }
  1058. if kdfName != "bcrypt" {
  1059. return nil, fmt.Errorf("ssh: unknown KDF %q, only supports %q", kdfName, "bcrypt")
  1060. }
  1061. var opts struct {
  1062. Salt string
  1063. Rounds uint32
  1064. }
  1065. if err := Unmarshal([]byte(kdfOpts), &opts); err != nil {
  1066. return nil, err
  1067. }
  1068. k, err := bcrypt_pbkdf.Key(passphrase, []byte(opts.Salt), int(opts.Rounds), 32+16)
  1069. if err != nil {
  1070. return nil, err
  1071. }
  1072. key, iv := k[:32], k[32:]
  1073. c, err := aes.NewCipher(key)
  1074. if err != nil {
  1075. return nil, err
  1076. }
  1077. switch cipherName {
  1078. case "aes256-ctr":
  1079. ctr := cipher.NewCTR(c, iv)
  1080. ctr.XORKeyStream(privKeyBlock, privKeyBlock)
  1081. case "aes256-cbc":
  1082. if len(privKeyBlock)%c.BlockSize() != 0 {
  1083. return nil, fmt.Errorf("ssh: invalid encrypted private key length, not a multiple of the block size")
  1084. }
  1085. cbc := cipher.NewCBCDecrypter(c, iv)
  1086. cbc.CryptBlocks(privKeyBlock, privKeyBlock)
  1087. default:
  1088. return nil, fmt.Errorf("ssh: unknown cipher %q, only supports %q or %q", cipherName, "aes256-ctr", "aes256-cbc")
  1089. }
  1090. return privKeyBlock, nil
  1091. }
  1092. }
  1093. type openSSHDecryptFunc func(CipherName, KdfName, KdfOpts string, PrivKeyBlock []byte) ([]byte, error)
  1094. // parseOpenSSHPrivateKey parses an OpenSSH private key, using the decrypt
  1095. // function to unwrap the encrypted portion. unencryptedOpenSSHKey can be used
  1096. // as the decrypt function to parse an unencrypted private key. See
  1097. // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key.
  1098. func parseOpenSSHPrivateKey(key []byte, decrypt openSSHDecryptFunc) (crypto.PrivateKey, error) {
  1099. const magic = "openssh-key-v1\x00"
  1100. if len(key) < len(magic) || string(key[:len(magic)]) != magic {
  1101. return nil, errors.New("ssh: invalid openssh private key format")
  1102. }
  1103. remaining := key[len(magic):]
  1104. var w struct {
  1105. CipherName string
  1106. KdfName string
  1107. KdfOpts string
  1108. NumKeys uint32
  1109. PubKey []byte
  1110. PrivKeyBlock []byte
  1111. }
  1112. if err := Unmarshal(remaining, &w); err != nil {
  1113. return nil, err
  1114. }
  1115. if w.NumKeys != 1 {
  1116. // We only support single key files, and so does OpenSSH.
  1117. // https://github.com/openssh/openssh-portable/blob/4103a3ec7/sshkey.c#L4171
  1118. return nil, errors.New("ssh: multi-key files are not supported")
  1119. }
  1120. privKeyBlock, err := decrypt(w.CipherName, w.KdfName, w.KdfOpts, w.PrivKeyBlock)
  1121. if err != nil {
  1122. if err, ok := err.(*PassphraseMissingError); ok {
  1123. pub, errPub := ParsePublicKey(w.PubKey)
  1124. if errPub != nil {
  1125. return nil, fmt.Errorf("ssh: failed to parse embedded public key: %v", errPub)
  1126. }
  1127. err.PublicKey = pub
  1128. }
  1129. return nil, err
  1130. }
  1131. pk1 := struct {
  1132. Check1 uint32
  1133. Check2 uint32
  1134. Keytype string
  1135. Rest []byte `ssh:"rest"`
  1136. }{}
  1137. if err := Unmarshal(privKeyBlock, &pk1); err != nil || pk1.Check1 != pk1.Check2 {
  1138. if w.CipherName != "none" {
  1139. return nil, x509.IncorrectPasswordError
  1140. }
  1141. return nil, errors.New("ssh: malformed OpenSSH key")
  1142. }
  1143. switch pk1.Keytype {
  1144. case KeyAlgoRSA:
  1145. // https://github.com/openssh/openssh-portable/blob/master/sshkey.c#L2760-L2773
  1146. key := struct {
  1147. N *big.Int
  1148. E *big.Int
  1149. D *big.Int
  1150. Iqmp *big.Int
  1151. P *big.Int
  1152. Q *big.Int
  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 err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1160. return nil, err
  1161. }
  1162. pk := &rsa.PrivateKey{
  1163. PublicKey: rsa.PublicKey{
  1164. N: key.N,
  1165. E: int(key.E.Int64()),
  1166. },
  1167. D: key.D,
  1168. Primes: []*big.Int{key.P, key.Q},
  1169. }
  1170. if err := pk.Validate(); err != nil {
  1171. return nil, err
  1172. }
  1173. pk.Precompute()
  1174. return pk, nil
  1175. case KeyAlgoED25519:
  1176. key := struct {
  1177. Pub []byte
  1178. Priv []byte
  1179. Comment string
  1180. Pad []byte `ssh:"rest"`
  1181. }{}
  1182. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1183. return nil, err
  1184. }
  1185. if len(key.Priv) != ed25519.PrivateKeySize {
  1186. return nil, errors.New("ssh: private key unexpected length")
  1187. }
  1188. if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1189. return nil, err
  1190. }
  1191. pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize))
  1192. copy(pk, key.Priv)
  1193. return &pk, nil
  1194. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  1195. key := struct {
  1196. Curve string
  1197. Pub []byte
  1198. D *big.Int
  1199. Comment string
  1200. Pad []byte `ssh:"rest"`
  1201. }{}
  1202. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1203. return nil, err
  1204. }
  1205. if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1206. return nil, err
  1207. }
  1208. var curve elliptic.Curve
  1209. switch key.Curve {
  1210. case "nistp256":
  1211. curve = elliptic.P256()
  1212. case "nistp384":
  1213. curve = elliptic.P384()
  1214. case "nistp521":
  1215. curve = elliptic.P521()
  1216. default:
  1217. return nil, errors.New("ssh: unhandled elliptic curve: " + key.Curve)
  1218. }
  1219. X, Y := elliptic.Unmarshal(curve, key.Pub)
  1220. if X == nil || Y == nil {
  1221. return nil, errors.New("ssh: failed to unmarshal public key")
  1222. }
  1223. if key.D.Cmp(curve.Params().N) >= 0 {
  1224. return nil, errors.New("ssh: scalar is out of range")
  1225. }
  1226. x, y := curve.ScalarBaseMult(key.D.Bytes())
  1227. if x.Cmp(X) != 0 || y.Cmp(Y) != 0 {
  1228. return nil, errors.New("ssh: public key does not match private key")
  1229. }
  1230. return &ecdsa.PrivateKey{
  1231. PublicKey: ecdsa.PublicKey{
  1232. Curve: curve,
  1233. X: X,
  1234. Y: Y,
  1235. },
  1236. D: key.D,
  1237. }, nil
  1238. default:
  1239. return nil, errors.New("ssh: unhandled key type")
  1240. }
  1241. }
  1242. func checkOpenSSHKeyPadding(pad []byte) error {
  1243. for i, b := range pad {
  1244. if int(b) != i+1 {
  1245. return errors.New("ssh: padding not as expected")
  1246. }
  1247. }
  1248. return nil
  1249. }
  1250. // FingerprintLegacyMD5 returns the user presentation of the key's
  1251. // fingerprint as described by RFC 4716 section 4.
  1252. func FingerprintLegacyMD5(pubKey PublicKey) string {
  1253. md5sum := md5.Sum(pubKey.Marshal())
  1254. hexarray := make([]string, len(md5sum))
  1255. for i, c := range md5sum {
  1256. hexarray[i] = hex.EncodeToString([]byte{c})
  1257. }
  1258. return strings.Join(hexarray, ":")
  1259. }
  1260. // FingerprintSHA256 returns the user presentation of the key's
  1261. // fingerprint as unpadded base64 encoded sha256 hash.
  1262. // This format was introduced from OpenSSH 6.8.
  1263. // https://www.openssh.com/txt/release-6.8
  1264. // https://tools.ietf.org/html/rfc4648#section-3.2 (unpadded base64 encoding)
  1265. func FingerprintSHA256(pubKey PublicKey) string {
  1266. sha256sum := sha256.Sum256(pubKey.Marshal())
  1267. hash := base64.RawStdEncoding.EncodeToString(sha256sum[:])
  1268. return "SHA256:" + hash
  1269. }