keys.go 44 KB

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