keys.go 47 KB

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