keys.go 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  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. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/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. // Signatures in PKCS1v15 must match the key's modulus in
  434. // length. However with SSH, some signers provide RSA
  435. // signatures which are missing the MSB 0's of the bignum
  436. // represented. With ssh-rsa signatures, this is encouraged by
  437. // the spec (even though e.g. OpenSSH will give the full
  438. // length unconditionally). With rsa-sha2-* signatures, the
  439. // verifier is allowed to support these, even though they are
  440. // out of spec. See RFC 4253 Section 6.6 for ssh-rsa and RFC
  441. // 8332 Section 3 for rsa-sha2-* details.
  442. //
  443. // In practice:
  444. // * OpenSSH always allows "short" signatures:
  445. // https://github.com/openssh/openssh-portable/blob/V_9_8_P1/ssh-rsa.c#L526
  446. // but always generates padded signatures:
  447. // https://github.com/openssh/openssh-portable/blob/V_9_8_P1/ssh-rsa.c#L439
  448. //
  449. // * PuTTY versions 0.81 and earlier will generate short
  450. // signatures for all RSA signature variants. Note that
  451. // PuTTY is embedded in other software, such as WinSCP and
  452. // FileZilla. At the time of writing, a patch has been
  453. // applied to PuTTY to generate padded signatures for
  454. // rsa-sha2-*, but not yet released:
  455. // https://git.tartarus.org/?p=simon/putty.git;a=commitdiff;h=a5bcf3d384e1bf15a51a6923c3724cbbee022d8e
  456. //
  457. // * SSH.NET versions 2024.0.0 and earlier will generate short
  458. // signatures for all RSA signature variants, fixed in 2024.1.0:
  459. // https://github.com/sshnet/SSH.NET/releases/tag/2024.1.0
  460. //
  461. // As a result, we pad these up to the key size by inserting
  462. // leading 0's.
  463. //
  464. // Note that support for short signatures with rsa-sha2-* may
  465. // be removed in the future due to such signatures not being
  466. // allowed by the spec.
  467. blob := sig.Blob
  468. keySize := (*rsa.PublicKey)(r).Size()
  469. if len(blob) < keySize {
  470. padded := make([]byte, keySize)
  471. copy(padded[keySize-len(blob):], blob)
  472. blob = padded
  473. }
  474. return rsa.VerifyPKCS1v15((*rsa.PublicKey)(r), hash, digest, blob)
  475. }
  476. func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  477. return (*rsa.PublicKey)(r)
  478. }
  479. type dsaPublicKey dsa.PublicKey
  480. func (k *dsaPublicKey) Type() string {
  481. return "ssh-dss"
  482. }
  483. func checkDSAParams(param *dsa.Parameters) error {
  484. // SSH specifies FIPS 186-2, which only provided a single size
  485. // (1024 bits) DSA key. FIPS 186-3 allows for larger key
  486. // sizes, which would confuse SSH.
  487. if l := param.P.BitLen(); l != 1024 {
  488. return fmt.Errorf("ssh: unsupported DSA key size %d", l)
  489. }
  490. return nil
  491. }
  492. // parseDSA parses an DSA key according to RFC 4253, section 6.6.
  493. func parseDSA(in []byte) (out PublicKey, rest []byte, err error) {
  494. var w struct {
  495. P, Q, G, Y *big.Int
  496. Rest []byte `ssh:"rest"`
  497. }
  498. if err := Unmarshal(in, &w); err != nil {
  499. return nil, nil, err
  500. }
  501. param := dsa.Parameters{
  502. P: w.P,
  503. Q: w.Q,
  504. G: w.G,
  505. }
  506. if err := checkDSAParams(&param); err != nil {
  507. return nil, nil, err
  508. }
  509. key := &dsaPublicKey{
  510. Parameters: param,
  511. Y: w.Y,
  512. }
  513. return key, w.Rest, nil
  514. }
  515. func (k *dsaPublicKey) Marshal() []byte {
  516. // DSA publickey struct layout should match the struct used by
  517. // parseDSACert in the x/crypto/ssh/agent package.
  518. w := struct {
  519. Name string
  520. P, Q, G, Y *big.Int
  521. }{
  522. k.Type(),
  523. k.P,
  524. k.Q,
  525. k.G,
  526. k.Y,
  527. }
  528. return Marshal(&w)
  529. }
  530. func (k *dsaPublicKey) Verify(data []byte, sig *Signature) error {
  531. if sig.Format != k.Type() {
  532. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  533. }
  534. h := hashFuncs[sig.Format].New()
  535. h.Write(data)
  536. digest := h.Sum(nil)
  537. // Per RFC 4253, section 6.6,
  538. // The value for 'dss_signature_blob' is encoded as a string containing
  539. // r, followed by s (which are 160-bit integers, without lengths or
  540. // padding, unsigned, and in network byte order).
  541. // For DSS purposes, sig.Blob should be exactly 40 bytes in length.
  542. if len(sig.Blob) != 40 {
  543. return errors.New("ssh: DSA signature parse error")
  544. }
  545. r := new(big.Int).SetBytes(sig.Blob[:20])
  546. s := new(big.Int).SetBytes(sig.Blob[20:])
  547. if dsa.Verify((*dsa.PublicKey)(k), digest, r, s) {
  548. return nil
  549. }
  550. return errors.New("ssh: signature did not verify")
  551. }
  552. func (k *dsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  553. return (*dsa.PublicKey)(k)
  554. }
  555. type dsaPrivateKey struct {
  556. *dsa.PrivateKey
  557. }
  558. func (k *dsaPrivateKey) PublicKey() PublicKey {
  559. return (*dsaPublicKey)(&k.PrivateKey.PublicKey)
  560. }
  561. func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) {
  562. return k.SignWithAlgorithm(rand, data, k.PublicKey().Type())
  563. }
  564. func (k *dsaPrivateKey) Algorithms() []string {
  565. return []string{k.PublicKey().Type()}
  566. }
  567. func (k *dsaPrivateKey) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  568. if algorithm != "" && algorithm != k.PublicKey().Type() {
  569. return nil, fmt.Errorf("ssh: unsupported signature algorithm %s", algorithm)
  570. }
  571. h := hashFuncs[k.PublicKey().Type()].New()
  572. h.Write(data)
  573. digest := h.Sum(nil)
  574. r, s, err := dsa.Sign(rand, k.PrivateKey, digest)
  575. if err != nil {
  576. return nil, err
  577. }
  578. sig := make([]byte, 40)
  579. rb := r.Bytes()
  580. sb := s.Bytes()
  581. copy(sig[20-len(rb):20], rb)
  582. copy(sig[40-len(sb):], sb)
  583. return &Signature{
  584. Format: k.PublicKey().Type(),
  585. Blob: sig,
  586. }, nil
  587. }
  588. type ecdsaPublicKey ecdsa.PublicKey
  589. func (k *ecdsaPublicKey) Type() string {
  590. return "ecdsa-sha2-" + k.nistID()
  591. }
  592. func (k *ecdsaPublicKey) nistID() string {
  593. switch k.Params().BitSize {
  594. case 256:
  595. return "nistp256"
  596. case 384:
  597. return "nistp384"
  598. case 521:
  599. return "nistp521"
  600. }
  601. panic("ssh: unsupported ecdsa key size")
  602. }
  603. type ed25519PublicKey ed25519.PublicKey
  604. func (k ed25519PublicKey) Type() string {
  605. return KeyAlgoED25519
  606. }
  607. func parseED25519(in []byte) (out PublicKey, rest []byte, err error) {
  608. var w struct {
  609. KeyBytes []byte
  610. Rest []byte `ssh:"rest"`
  611. }
  612. if err := Unmarshal(in, &w); err != nil {
  613. return nil, nil, err
  614. }
  615. if l := len(w.KeyBytes); l != ed25519.PublicKeySize {
  616. return nil, nil, fmt.Errorf("invalid size %d for Ed25519 public key", l)
  617. }
  618. return ed25519PublicKey(w.KeyBytes), w.Rest, nil
  619. }
  620. func (k ed25519PublicKey) Marshal() []byte {
  621. w := struct {
  622. Name string
  623. KeyBytes []byte
  624. }{
  625. KeyAlgoED25519,
  626. []byte(k),
  627. }
  628. return Marshal(&w)
  629. }
  630. func (k ed25519PublicKey) Verify(b []byte, sig *Signature) error {
  631. if sig.Format != k.Type() {
  632. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  633. }
  634. if l := len(k); l != ed25519.PublicKeySize {
  635. return fmt.Errorf("ssh: invalid size %d for Ed25519 public key", l)
  636. }
  637. if ok := ed25519.Verify(ed25519.PublicKey(k), b, sig.Blob); !ok {
  638. return errors.New("ssh: signature did not verify")
  639. }
  640. return nil
  641. }
  642. func (k ed25519PublicKey) CryptoPublicKey() crypto.PublicKey {
  643. return ed25519.PublicKey(k)
  644. }
  645. func supportedEllipticCurve(curve elliptic.Curve) bool {
  646. return curve == elliptic.P256() || curve == elliptic.P384() || curve == elliptic.P521()
  647. }
  648. // parseECDSA parses an ECDSA key according to RFC 5656, section 3.1.
  649. func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  650. var w struct {
  651. Curve string
  652. KeyBytes []byte
  653. Rest []byte `ssh:"rest"`
  654. }
  655. if err := Unmarshal(in, &w); err != nil {
  656. return nil, nil, err
  657. }
  658. key := new(ecdsa.PublicKey)
  659. switch w.Curve {
  660. case "nistp256":
  661. key.Curve = elliptic.P256()
  662. case "nistp384":
  663. key.Curve = elliptic.P384()
  664. case "nistp521":
  665. key.Curve = elliptic.P521()
  666. default:
  667. return nil, nil, errors.New("ssh: unsupported curve")
  668. }
  669. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  670. if key.X == nil || key.Y == nil {
  671. return nil, nil, errors.New("ssh: invalid curve point")
  672. }
  673. return (*ecdsaPublicKey)(key), w.Rest, nil
  674. }
  675. func (k *ecdsaPublicKey) Marshal() []byte {
  676. // See RFC 5656, section 3.1.
  677. keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y)
  678. // ECDSA publickey struct layout should match the struct used by
  679. // parseECDSACert in the x/crypto/ssh/agent package.
  680. w := struct {
  681. Name string
  682. ID string
  683. Key []byte
  684. }{
  685. k.Type(),
  686. k.nistID(),
  687. keyBytes,
  688. }
  689. return Marshal(&w)
  690. }
  691. func (k *ecdsaPublicKey) Verify(data []byte, sig *Signature) error {
  692. if sig.Format != k.Type() {
  693. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  694. }
  695. h := hashFuncs[sig.Format].New()
  696. h.Write(data)
  697. digest := h.Sum(nil)
  698. // Per RFC 5656, section 3.1.2,
  699. // The ecdsa_signature_blob value has the following specific encoding:
  700. // mpint r
  701. // mpint s
  702. var ecSig struct {
  703. R *big.Int
  704. S *big.Int
  705. }
  706. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  707. return err
  708. }
  709. if ecdsa.Verify((*ecdsa.PublicKey)(k), digest, ecSig.R, ecSig.S) {
  710. return nil
  711. }
  712. return errors.New("ssh: signature did not verify")
  713. }
  714. func (k *ecdsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  715. return (*ecdsa.PublicKey)(k)
  716. }
  717. // skFields holds the additional fields present in U2F/FIDO2 signatures.
  718. // See openssh/PROTOCOL.u2f 'SSH U2F Signatures' for details.
  719. type skFields struct {
  720. // Flags contains U2F/FIDO2 flags such as 'user present'
  721. Flags byte
  722. // Counter is a monotonic signature counter which can be
  723. // used to detect concurrent use of a private key, should
  724. // it be extracted from hardware.
  725. Counter uint32
  726. }
  727. type skECDSAPublicKey struct {
  728. // application is a URL-like string, typically "ssh:" for SSH.
  729. // see openssh/PROTOCOL.u2f for details.
  730. application string
  731. ecdsa.PublicKey
  732. }
  733. func (k *skECDSAPublicKey) Type() string {
  734. return KeyAlgoSKECDSA256
  735. }
  736. func (k *skECDSAPublicKey) nistID() string {
  737. return "nistp256"
  738. }
  739. func parseSKECDSA(in []byte) (out PublicKey, rest []byte, err error) {
  740. var w struct {
  741. Curve string
  742. KeyBytes []byte
  743. Application string
  744. Rest []byte `ssh:"rest"`
  745. }
  746. if err := Unmarshal(in, &w); err != nil {
  747. return nil, nil, err
  748. }
  749. key := new(skECDSAPublicKey)
  750. key.application = w.Application
  751. if w.Curve != "nistp256" {
  752. return nil, nil, errors.New("ssh: unsupported curve")
  753. }
  754. key.Curve = elliptic.P256()
  755. key.X, key.Y = elliptic.Unmarshal(key.Curve, w.KeyBytes)
  756. if key.X == nil || key.Y == nil {
  757. return nil, nil, errors.New("ssh: invalid curve point")
  758. }
  759. return key, w.Rest, nil
  760. }
  761. func (k *skECDSAPublicKey) Marshal() []byte {
  762. // See RFC 5656, section 3.1.
  763. keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y)
  764. w := struct {
  765. Name string
  766. ID string
  767. Key []byte
  768. Application string
  769. }{
  770. k.Type(),
  771. k.nistID(),
  772. keyBytes,
  773. k.application,
  774. }
  775. return Marshal(&w)
  776. }
  777. func (k *skECDSAPublicKey) Verify(data []byte, sig *Signature) error {
  778. if sig.Format != k.Type() {
  779. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  780. }
  781. h := hashFuncs[sig.Format].New()
  782. h.Write([]byte(k.application))
  783. appDigest := h.Sum(nil)
  784. h.Reset()
  785. h.Write(data)
  786. dataDigest := h.Sum(nil)
  787. var ecSig struct {
  788. R *big.Int
  789. S *big.Int
  790. }
  791. if err := Unmarshal(sig.Blob, &ecSig); err != nil {
  792. return err
  793. }
  794. var skf skFields
  795. if err := Unmarshal(sig.Rest, &skf); err != nil {
  796. return err
  797. }
  798. blob := struct {
  799. ApplicationDigest []byte `ssh:"rest"`
  800. Flags byte
  801. Counter uint32
  802. MessageDigest []byte `ssh:"rest"`
  803. }{
  804. appDigest,
  805. skf.Flags,
  806. skf.Counter,
  807. dataDigest,
  808. }
  809. original := Marshal(blob)
  810. h.Reset()
  811. h.Write(original)
  812. digest := h.Sum(nil)
  813. if ecdsa.Verify((*ecdsa.PublicKey)(&k.PublicKey), digest, ecSig.R, ecSig.S) {
  814. return nil
  815. }
  816. return errors.New("ssh: signature did not verify")
  817. }
  818. func (k *skECDSAPublicKey) CryptoPublicKey() crypto.PublicKey {
  819. return &k.PublicKey
  820. }
  821. type skEd25519PublicKey struct {
  822. // application is a URL-like string, typically "ssh:" for SSH.
  823. // see openssh/PROTOCOL.u2f for details.
  824. application string
  825. ed25519.PublicKey
  826. }
  827. func (k *skEd25519PublicKey) Type() string {
  828. return KeyAlgoSKED25519
  829. }
  830. func parseSKEd25519(in []byte) (out PublicKey, rest []byte, err error) {
  831. var w struct {
  832. KeyBytes []byte
  833. Application string
  834. Rest []byte `ssh:"rest"`
  835. }
  836. if err := Unmarshal(in, &w); err != nil {
  837. return nil, nil, err
  838. }
  839. if l := len(w.KeyBytes); l != ed25519.PublicKeySize {
  840. return nil, nil, fmt.Errorf("invalid size %d for Ed25519 public key", l)
  841. }
  842. key := new(skEd25519PublicKey)
  843. key.application = w.Application
  844. key.PublicKey = ed25519.PublicKey(w.KeyBytes)
  845. return key, w.Rest, nil
  846. }
  847. func (k *skEd25519PublicKey) Marshal() []byte {
  848. w := struct {
  849. Name string
  850. KeyBytes []byte
  851. Application string
  852. }{
  853. KeyAlgoSKED25519,
  854. []byte(k.PublicKey),
  855. k.application,
  856. }
  857. return Marshal(&w)
  858. }
  859. func (k *skEd25519PublicKey) Verify(data []byte, sig *Signature) error {
  860. if sig.Format != k.Type() {
  861. return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type())
  862. }
  863. if l := len(k.PublicKey); l != ed25519.PublicKeySize {
  864. return fmt.Errorf("invalid size %d for Ed25519 public key", l)
  865. }
  866. h := hashFuncs[sig.Format].New()
  867. h.Write([]byte(k.application))
  868. appDigest := h.Sum(nil)
  869. h.Reset()
  870. h.Write(data)
  871. dataDigest := h.Sum(nil)
  872. var edSig struct {
  873. Signature []byte `ssh:"rest"`
  874. }
  875. if err := Unmarshal(sig.Blob, &edSig); err != nil {
  876. return err
  877. }
  878. var skf skFields
  879. if err := Unmarshal(sig.Rest, &skf); err != nil {
  880. return err
  881. }
  882. blob := struct {
  883. ApplicationDigest []byte `ssh:"rest"`
  884. Flags byte
  885. Counter uint32
  886. MessageDigest []byte `ssh:"rest"`
  887. }{
  888. appDigest,
  889. skf.Flags,
  890. skf.Counter,
  891. dataDigest,
  892. }
  893. original := Marshal(blob)
  894. if ok := ed25519.Verify(k.PublicKey, original, edSig.Signature); !ok {
  895. return errors.New("ssh: signature did not verify")
  896. }
  897. return nil
  898. }
  899. func (k *skEd25519PublicKey) CryptoPublicKey() crypto.PublicKey {
  900. return k.PublicKey
  901. }
  902. // NewSignerFromKey takes an *rsa.PrivateKey, *dsa.PrivateKey,
  903. // *ecdsa.PrivateKey or any other crypto.Signer and returns a
  904. // corresponding Signer instance. ECDSA keys must use P-256, P-384 or
  905. // P-521. DSA keys must use parameter size L1024N160.
  906. func NewSignerFromKey(key interface{}) (Signer, error) {
  907. switch key := key.(type) {
  908. case crypto.Signer:
  909. return NewSignerFromSigner(key)
  910. case *dsa.PrivateKey:
  911. return newDSAPrivateKey(key)
  912. default:
  913. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  914. }
  915. }
  916. func newDSAPrivateKey(key *dsa.PrivateKey) (Signer, error) {
  917. if err := checkDSAParams(&key.PublicKey.Parameters); err != nil {
  918. return nil, err
  919. }
  920. return &dsaPrivateKey{key}, nil
  921. }
  922. type rsaSigner struct {
  923. AlgorithmSigner
  924. defaultAlgorithm string
  925. }
  926. func (s *rsaSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  927. return s.AlgorithmSigner.SignWithAlgorithm(rand, data, s.defaultAlgorithm)
  928. }
  929. type wrappedSigner struct {
  930. signer crypto.Signer
  931. pubKey PublicKey
  932. }
  933. // NewSignerFromSigner takes any crypto.Signer implementation and
  934. // returns a corresponding Signer interface. This can be used, for
  935. // example, with keys kept in hardware modules.
  936. func NewSignerFromSigner(signer crypto.Signer) (Signer, error) {
  937. pubKey, err := NewPublicKey(signer.Public())
  938. if err != nil {
  939. return nil, err
  940. }
  941. return &wrappedSigner{signer, pubKey}, nil
  942. }
  943. func (s *wrappedSigner) PublicKey() PublicKey {
  944. return s.pubKey
  945. }
  946. func (s *wrappedSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  947. return s.SignWithAlgorithm(rand, data, s.pubKey.Type())
  948. }
  949. func (s *wrappedSigner) Algorithms() []string {
  950. return algorithmsForKeyFormat(s.pubKey.Type())
  951. }
  952. func (s *wrappedSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  953. if algorithm == "" {
  954. algorithm = s.pubKey.Type()
  955. }
  956. if !contains(s.Algorithms(), algorithm) {
  957. return nil, fmt.Errorf("ssh: unsupported signature algorithm %q for key format %q", algorithm, s.pubKey.Type())
  958. }
  959. hashFunc := hashFuncs[algorithm]
  960. var digest []byte
  961. if hashFunc != 0 {
  962. h := hashFunc.New()
  963. h.Write(data)
  964. digest = h.Sum(nil)
  965. } else {
  966. digest = data
  967. }
  968. signature, err := s.signer.Sign(rand, digest, hashFunc)
  969. if err != nil {
  970. return nil, err
  971. }
  972. // crypto.Signer.Sign is expected to return an ASN.1-encoded signature
  973. // for ECDSA and DSA, but that's not the encoding expected by SSH, so
  974. // re-encode.
  975. switch s.pubKey.(type) {
  976. case *ecdsaPublicKey, *dsaPublicKey:
  977. type asn1Signature struct {
  978. R, S *big.Int
  979. }
  980. asn1Sig := new(asn1Signature)
  981. _, err := asn1.Unmarshal(signature, asn1Sig)
  982. if err != nil {
  983. return nil, err
  984. }
  985. switch s.pubKey.(type) {
  986. case *ecdsaPublicKey:
  987. signature = Marshal(asn1Sig)
  988. case *dsaPublicKey:
  989. signature = make([]byte, 40)
  990. r := asn1Sig.R.Bytes()
  991. s := asn1Sig.S.Bytes()
  992. copy(signature[20-len(r):20], r)
  993. copy(signature[40-len(s):40], s)
  994. }
  995. }
  996. return &Signature{
  997. Format: algorithm,
  998. Blob: signature,
  999. }, nil
  1000. }
  1001. // NewPublicKey takes an *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
  1002. // or ed25519.PublicKey returns a corresponding PublicKey instance.
  1003. // ECDSA keys must use P-256, P-384 or P-521.
  1004. func NewPublicKey(key interface{}) (PublicKey, error) {
  1005. switch key := key.(type) {
  1006. case *rsa.PublicKey:
  1007. return (*rsaPublicKey)(key), nil
  1008. case *ecdsa.PublicKey:
  1009. if !supportedEllipticCurve(key.Curve) {
  1010. return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported")
  1011. }
  1012. return (*ecdsaPublicKey)(key), nil
  1013. case *dsa.PublicKey:
  1014. return (*dsaPublicKey)(key), nil
  1015. case ed25519.PublicKey:
  1016. if l := len(key); l != ed25519.PublicKeySize {
  1017. return nil, fmt.Errorf("ssh: invalid size %d for Ed25519 public key", l)
  1018. }
  1019. return ed25519PublicKey(key), nil
  1020. default:
  1021. return nil, fmt.Errorf("ssh: unsupported key type %T", key)
  1022. }
  1023. }
  1024. // ParsePrivateKey returns a Signer from a PEM encoded private key. It supports
  1025. // the same keys as ParseRawPrivateKey. If the private key is encrypted, it
  1026. // will return a PassphraseMissingError.
  1027. func ParsePrivateKey(pemBytes []byte) (Signer, error) {
  1028. key, err := ParseRawPrivateKey(pemBytes)
  1029. if err != nil {
  1030. return nil, err
  1031. }
  1032. return NewSignerFromKey(key)
  1033. }
  1034. // ParsePrivateKeyWithPassphrase returns a Signer from a PEM encoded private
  1035. // key and passphrase. It supports the same keys as
  1036. // ParseRawPrivateKeyWithPassphrase.
  1037. func ParsePrivateKeyWithPassphrase(pemBytes, passphrase []byte) (Signer, error) {
  1038. key, err := ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase)
  1039. if err != nil {
  1040. return nil, err
  1041. }
  1042. return NewSignerFromKey(key)
  1043. }
  1044. // encryptedBlock tells whether a private key is
  1045. // encrypted by examining its Proc-Type header
  1046. // for a mention of ENCRYPTED
  1047. // according to RFC 1421 Section 4.6.1.1.
  1048. func encryptedBlock(block *pem.Block) bool {
  1049. return strings.Contains(block.Headers["Proc-Type"], "ENCRYPTED")
  1050. }
  1051. // A PassphraseMissingError indicates that parsing this private key requires a
  1052. // passphrase. Use ParsePrivateKeyWithPassphrase.
  1053. type PassphraseMissingError struct {
  1054. // PublicKey will be set if the private key format includes an unencrypted
  1055. // public key along with the encrypted private key.
  1056. PublicKey PublicKey
  1057. }
  1058. func (*PassphraseMissingError) Error() string {
  1059. return "ssh: this private key is passphrase protected"
  1060. }
  1061. // ParseRawPrivateKey returns a private key from a PEM encoded private key. It supports
  1062. // RSA, DSA, ECDSA, and Ed25519 private keys in PKCS#1, PKCS#8, OpenSSL, and OpenSSH
  1063. // formats. If the private key is encrypted, it will return a PassphraseMissingError.
  1064. func ParseRawPrivateKey(pemBytes []byte) (interface{}, error) {
  1065. block, _ := pem.Decode(pemBytes)
  1066. if block == nil {
  1067. return nil, errors.New("ssh: no key found")
  1068. }
  1069. if encryptedBlock(block) {
  1070. return nil, &PassphraseMissingError{}
  1071. }
  1072. switch block.Type {
  1073. case "RSA PRIVATE KEY":
  1074. return x509.ParsePKCS1PrivateKey(block.Bytes)
  1075. // RFC5208 - https://tools.ietf.org/html/rfc5208
  1076. case "PRIVATE KEY":
  1077. return x509.ParsePKCS8PrivateKey(block.Bytes)
  1078. case "EC PRIVATE KEY":
  1079. return x509.ParseECPrivateKey(block.Bytes)
  1080. case "DSA PRIVATE KEY":
  1081. return ParseDSAPrivateKey(block.Bytes)
  1082. case "OPENSSH PRIVATE KEY":
  1083. return parseOpenSSHPrivateKey(block.Bytes, unencryptedOpenSSHKey)
  1084. default:
  1085. return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
  1086. }
  1087. }
  1088. // ParseRawPrivateKeyWithPassphrase returns a private key decrypted with
  1089. // passphrase from a PEM encoded private key. If the passphrase is wrong, it
  1090. // will return x509.IncorrectPasswordError.
  1091. func ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase []byte) (interface{}, error) {
  1092. block, _ := pem.Decode(pemBytes)
  1093. if block == nil {
  1094. return nil, errors.New("ssh: no key found")
  1095. }
  1096. if block.Type == "OPENSSH PRIVATE KEY" {
  1097. return parseOpenSSHPrivateKey(block.Bytes, passphraseProtectedOpenSSHKey(passphrase))
  1098. }
  1099. if !encryptedBlock(block) || !x509.IsEncryptedPEMBlock(block) {
  1100. return nil, errors.New("ssh: not an encrypted key")
  1101. }
  1102. buf, err := x509.DecryptPEMBlock(block, passphrase)
  1103. if err != nil {
  1104. if err == x509.IncorrectPasswordError {
  1105. return nil, err
  1106. }
  1107. return nil, fmt.Errorf("ssh: cannot decode encrypted private keys: %v", err)
  1108. }
  1109. var result interface{}
  1110. switch block.Type {
  1111. case "RSA PRIVATE KEY":
  1112. result, err = x509.ParsePKCS1PrivateKey(buf)
  1113. case "EC PRIVATE KEY":
  1114. result, err = x509.ParseECPrivateKey(buf)
  1115. case "DSA PRIVATE KEY":
  1116. result, err = ParseDSAPrivateKey(buf)
  1117. default:
  1118. err = fmt.Errorf("ssh: unsupported key type %q", block.Type)
  1119. }
  1120. // Because of deficiencies in the format, DecryptPEMBlock does not always
  1121. // detect an incorrect password. In these cases decrypted DER bytes is
  1122. // random noise. If the parsing of the key returns an asn1.StructuralError
  1123. // we return x509.IncorrectPasswordError.
  1124. if _, ok := err.(asn1.StructuralError); ok {
  1125. return nil, x509.IncorrectPasswordError
  1126. }
  1127. return result, err
  1128. }
  1129. // ParseDSAPrivateKey returns a DSA private key from its ASN.1 DER encoding, as
  1130. // specified by the OpenSSL DSA man page.
  1131. func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) {
  1132. var k struct {
  1133. Version int
  1134. P *big.Int
  1135. Q *big.Int
  1136. G *big.Int
  1137. Pub *big.Int
  1138. Priv *big.Int
  1139. }
  1140. rest, err := asn1.Unmarshal(der, &k)
  1141. if err != nil {
  1142. return nil, errors.New("ssh: failed to parse DSA key: " + err.Error())
  1143. }
  1144. if len(rest) > 0 {
  1145. return nil, errors.New("ssh: garbage after DSA key")
  1146. }
  1147. return &dsa.PrivateKey{
  1148. PublicKey: dsa.PublicKey{
  1149. Parameters: dsa.Parameters{
  1150. P: k.P,
  1151. Q: k.Q,
  1152. G: k.G,
  1153. },
  1154. Y: k.Pub,
  1155. },
  1156. X: k.Priv,
  1157. }, nil
  1158. }
  1159. func unencryptedOpenSSHKey(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) {
  1160. if kdfName != "none" || cipherName != "none" {
  1161. return nil, &PassphraseMissingError{}
  1162. }
  1163. if kdfOpts != "" {
  1164. return nil, errors.New("ssh: invalid openssh private key")
  1165. }
  1166. return privKeyBlock, nil
  1167. }
  1168. func passphraseProtectedOpenSSHKey(passphrase []byte) openSSHDecryptFunc {
  1169. return func(cipherName, kdfName, kdfOpts string, privKeyBlock []byte) ([]byte, error) {
  1170. if kdfName == "none" || cipherName == "none" {
  1171. return nil, errors.New("ssh: key is not password protected")
  1172. }
  1173. if kdfName != "bcrypt" {
  1174. return nil, fmt.Errorf("ssh: unknown KDF %q, only supports %q", kdfName, "bcrypt")
  1175. }
  1176. var opts struct {
  1177. Salt string
  1178. Rounds uint32
  1179. }
  1180. if err := Unmarshal([]byte(kdfOpts), &opts); err != nil {
  1181. return nil, err
  1182. }
  1183. k, err := bcrypt_pbkdf.Key(passphrase, []byte(opts.Salt), int(opts.Rounds), 32+16)
  1184. if err != nil {
  1185. return nil, err
  1186. }
  1187. key, iv := k[:32], k[32:]
  1188. c, err := aes.NewCipher(key)
  1189. if err != nil {
  1190. return nil, err
  1191. }
  1192. switch cipherName {
  1193. case "aes256-ctr":
  1194. ctr := cipher.NewCTR(c, iv)
  1195. ctr.XORKeyStream(privKeyBlock, privKeyBlock)
  1196. case "aes256-cbc":
  1197. if len(privKeyBlock)%c.BlockSize() != 0 {
  1198. return nil, fmt.Errorf("ssh: invalid encrypted private key length, not a multiple of the block size")
  1199. }
  1200. cbc := cipher.NewCBCDecrypter(c, iv)
  1201. cbc.CryptBlocks(privKeyBlock, privKeyBlock)
  1202. default:
  1203. return nil, fmt.Errorf("ssh: unknown cipher %q, only supports %q or %q", cipherName, "aes256-ctr", "aes256-cbc")
  1204. }
  1205. return privKeyBlock, nil
  1206. }
  1207. }
  1208. func unencryptedOpenSSHMarshaler(privKeyBlock []byte) ([]byte, string, string, string, error) {
  1209. key := generateOpenSSHPadding(privKeyBlock, 8)
  1210. return key, "none", "none", "", nil
  1211. }
  1212. func passphraseProtectedOpenSSHMarshaler(passphrase []byte) openSSHEncryptFunc {
  1213. return func(privKeyBlock []byte) ([]byte, string, string, string, error) {
  1214. salt := make([]byte, 16)
  1215. if _, err := rand.Read(salt); err != nil {
  1216. return nil, "", "", "", err
  1217. }
  1218. opts := struct {
  1219. Salt []byte
  1220. Rounds uint32
  1221. }{salt, 16}
  1222. // Derive key to encrypt the private key block.
  1223. k, err := bcrypt_pbkdf.Key(passphrase, salt, int(opts.Rounds), 32+aes.BlockSize)
  1224. if err != nil {
  1225. return nil, "", "", "", err
  1226. }
  1227. // Add padding matching the block size of AES.
  1228. keyBlock := generateOpenSSHPadding(privKeyBlock, aes.BlockSize)
  1229. // Encrypt the private key using the derived secret.
  1230. dst := make([]byte, len(keyBlock))
  1231. key, iv := k[:32], k[32:]
  1232. block, err := aes.NewCipher(key)
  1233. if err != nil {
  1234. return nil, "", "", "", err
  1235. }
  1236. stream := cipher.NewCTR(block, iv)
  1237. stream.XORKeyStream(dst, keyBlock)
  1238. return dst, "aes256-ctr", "bcrypt", string(Marshal(opts)), nil
  1239. }
  1240. }
  1241. const privateKeyAuthMagic = "openssh-key-v1\x00"
  1242. type openSSHDecryptFunc func(CipherName, KdfName, KdfOpts string, PrivKeyBlock []byte) ([]byte, error)
  1243. type openSSHEncryptFunc func(PrivKeyBlock []byte) (ProtectedKeyBlock []byte, cipherName, kdfName, kdfOptions string, err error)
  1244. type openSSHEncryptedPrivateKey struct {
  1245. CipherName string
  1246. KdfName string
  1247. KdfOpts string
  1248. NumKeys uint32
  1249. PubKey []byte
  1250. PrivKeyBlock []byte
  1251. }
  1252. type openSSHPrivateKey struct {
  1253. Check1 uint32
  1254. Check2 uint32
  1255. Keytype string
  1256. Rest []byte `ssh:"rest"`
  1257. }
  1258. type openSSHRSAPrivateKey struct {
  1259. N *big.Int
  1260. E *big.Int
  1261. D *big.Int
  1262. Iqmp *big.Int
  1263. P *big.Int
  1264. Q *big.Int
  1265. Comment string
  1266. Pad []byte `ssh:"rest"`
  1267. }
  1268. type openSSHEd25519PrivateKey struct {
  1269. Pub []byte
  1270. Priv []byte
  1271. Comment string
  1272. Pad []byte `ssh:"rest"`
  1273. }
  1274. type openSSHECDSAPrivateKey struct {
  1275. Curve string
  1276. Pub []byte
  1277. D *big.Int
  1278. Comment string
  1279. Pad []byte `ssh:"rest"`
  1280. }
  1281. // parseOpenSSHPrivateKey parses an OpenSSH private key, using the decrypt
  1282. // function to unwrap the encrypted portion. unencryptedOpenSSHKey can be used
  1283. // as the decrypt function to parse an unencrypted private key. See
  1284. // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key.
  1285. func parseOpenSSHPrivateKey(key []byte, decrypt openSSHDecryptFunc) (crypto.PrivateKey, error) {
  1286. if len(key) < len(privateKeyAuthMagic) || string(key[:len(privateKeyAuthMagic)]) != privateKeyAuthMagic {
  1287. return nil, errors.New("ssh: invalid openssh private key format")
  1288. }
  1289. remaining := key[len(privateKeyAuthMagic):]
  1290. var w openSSHEncryptedPrivateKey
  1291. if err := Unmarshal(remaining, &w); err != nil {
  1292. return nil, err
  1293. }
  1294. if w.NumKeys != 1 {
  1295. // We only support single key files, and so does OpenSSH.
  1296. // https://github.com/openssh/openssh-portable/blob/4103a3ec7/sshkey.c#L4171
  1297. return nil, errors.New("ssh: multi-key files are not supported")
  1298. }
  1299. privKeyBlock, err := decrypt(w.CipherName, w.KdfName, w.KdfOpts, w.PrivKeyBlock)
  1300. if err != nil {
  1301. if err, ok := err.(*PassphraseMissingError); ok {
  1302. pub, errPub := ParsePublicKey(w.PubKey)
  1303. if errPub != nil {
  1304. return nil, fmt.Errorf("ssh: failed to parse embedded public key: %v", errPub)
  1305. }
  1306. err.PublicKey = pub
  1307. }
  1308. return nil, err
  1309. }
  1310. var pk1 openSSHPrivateKey
  1311. if err := Unmarshal(privKeyBlock, &pk1); err != nil || pk1.Check1 != pk1.Check2 {
  1312. if w.CipherName != "none" {
  1313. return nil, x509.IncorrectPasswordError
  1314. }
  1315. return nil, errors.New("ssh: malformed OpenSSH key")
  1316. }
  1317. switch pk1.Keytype {
  1318. case KeyAlgoRSA:
  1319. var key openSSHRSAPrivateKey
  1320. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1321. return nil, err
  1322. }
  1323. if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1324. return nil, err
  1325. }
  1326. pk := &rsa.PrivateKey{
  1327. PublicKey: rsa.PublicKey{
  1328. N: key.N,
  1329. E: int(key.E.Int64()),
  1330. },
  1331. D: key.D,
  1332. Primes: []*big.Int{key.P, key.Q},
  1333. }
  1334. if err := pk.Validate(); err != nil {
  1335. return nil, err
  1336. }
  1337. pk.Precompute()
  1338. return pk, nil
  1339. case KeyAlgoED25519:
  1340. var key openSSHEd25519PrivateKey
  1341. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1342. return nil, err
  1343. }
  1344. if len(key.Priv) != ed25519.PrivateKeySize {
  1345. return nil, errors.New("ssh: private key unexpected length")
  1346. }
  1347. if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1348. return nil, err
  1349. }
  1350. pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize))
  1351. copy(pk, key.Priv)
  1352. return &pk, nil
  1353. case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
  1354. var key openSSHECDSAPrivateKey
  1355. if err := Unmarshal(pk1.Rest, &key); err != nil {
  1356. return nil, err
  1357. }
  1358. if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
  1359. return nil, err
  1360. }
  1361. var curve elliptic.Curve
  1362. switch key.Curve {
  1363. case "nistp256":
  1364. curve = elliptic.P256()
  1365. case "nistp384":
  1366. curve = elliptic.P384()
  1367. case "nistp521":
  1368. curve = elliptic.P521()
  1369. default:
  1370. return nil, errors.New("ssh: unhandled elliptic curve: " + key.Curve)
  1371. }
  1372. X, Y := elliptic.Unmarshal(curve, key.Pub)
  1373. if X == nil || Y == nil {
  1374. return nil, errors.New("ssh: failed to unmarshal public key")
  1375. }
  1376. if key.D.Cmp(curve.Params().N) >= 0 {
  1377. return nil, errors.New("ssh: scalar is out of range")
  1378. }
  1379. x, y := curve.ScalarBaseMult(key.D.Bytes())
  1380. if x.Cmp(X) != 0 || y.Cmp(Y) != 0 {
  1381. return nil, errors.New("ssh: public key does not match private key")
  1382. }
  1383. return &ecdsa.PrivateKey{
  1384. PublicKey: ecdsa.PublicKey{
  1385. Curve: curve,
  1386. X: X,
  1387. Y: Y,
  1388. },
  1389. D: key.D,
  1390. }, nil
  1391. default:
  1392. return nil, errors.New("ssh: unhandled key type")
  1393. }
  1394. }
  1395. func marshalOpenSSHPrivateKey(key crypto.PrivateKey, comment string, encrypt openSSHEncryptFunc) (*pem.Block, error) {
  1396. var w openSSHEncryptedPrivateKey
  1397. var pk1 openSSHPrivateKey
  1398. // Random check bytes.
  1399. var check uint32
  1400. if err := binary.Read(rand.Reader, binary.BigEndian, &check); err != nil {
  1401. return nil, err
  1402. }
  1403. pk1.Check1 = check
  1404. pk1.Check2 = check
  1405. w.NumKeys = 1
  1406. // Use a []byte directly on ed25519 keys.
  1407. if k, ok := key.(*ed25519.PrivateKey); ok {
  1408. key = *k
  1409. }
  1410. switch k := key.(type) {
  1411. case *rsa.PrivateKey:
  1412. E := new(big.Int).SetInt64(int64(k.PublicKey.E))
  1413. // Marshal public key:
  1414. // E and N are in reversed order in the public and private key.
  1415. pubKey := struct {
  1416. KeyType string
  1417. E *big.Int
  1418. N *big.Int
  1419. }{
  1420. KeyAlgoRSA,
  1421. E, k.PublicKey.N,
  1422. }
  1423. w.PubKey = Marshal(pubKey)
  1424. // Marshal private key.
  1425. key := openSSHRSAPrivateKey{
  1426. N: k.PublicKey.N,
  1427. E: E,
  1428. D: k.D,
  1429. Iqmp: k.Precomputed.Qinv,
  1430. P: k.Primes[0],
  1431. Q: k.Primes[1],
  1432. Comment: comment,
  1433. }
  1434. pk1.Keytype = KeyAlgoRSA
  1435. pk1.Rest = Marshal(key)
  1436. case ed25519.PrivateKey:
  1437. pub := make([]byte, ed25519.PublicKeySize)
  1438. priv := make([]byte, ed25519.PrivateKeySize)
  1439. copy(pub, k[32:])
  1440. copy(priv, k)
  1441. // Marshal public key.
  1442. pubKey := struct {
  1443. KeyType string
  1444. Pub []byte
  1445. }{
  1446. KeyAlgoED25519, pub,
  1447. }
  1448. w.PubKey = Marshal(pubKey)
  1449. // Marshal private key.
  1450. key := openSSHEd25519PrivateKey{
  1451. Pub: pub,
  1452. Priv: priv,
  1453. Comment: comment,
  1454. }
  1455. pk1.Keytype = KeyAlgoED25519
  1456. pk1.Rest = Marshal(key)
  1457. case *ecdsa.PrivateKey:
  1458. var curve, keyType string
  1459. switch name := k.Curve.Params().Name; name {
  1460. case "P-256":
  1461. curve = "nistp256"
  1462. keyType = KeyAlgoECDSA256
  1463. case "P-384":
  1464. curve = "nistp384"
  1465. keyType = KeyAlgoECDSA384
  1466. case "P-521":
  1467. curve = "nistp521"
  1468. keyType = KeyAlgoECDSA521
  1469. default:
  1470. return nil, errors.New("ssh: unhandled elliptic curve " + name)
  1471. }
  1472. pub := elliptic.Marshal(k.Curve, k.PublicKey.X, k.PublicKey.Y)
  1473. // Marshal public key.
  1474. pubKey := struct {
  1475. KeyType string
  1476. Curve string
  1477. Pub []byte
  1478. }{
  1479. keyType, curve, pub,
  1480. }
  1481. w.PubKey = Marshal(pubKey)
  1482. // Marshal private key.
  1483. key := openSSHECDSAPrivateKey{
  1484. Curve: curve,
  1485. Pub: pub,
  1486. D: k.D,
  1487. Comment: comment,
  1488. }
  1489. pk1.Keytype = keyType
  1490. pk1.Rest = Marshal(key)
  1491. default:
  1492. return nil, fmt.Errorf("ssh: unsupported key type %T", k)
  1493. }
  1494. var err error
  1495. // Add padding and encrypt the key if necessary.
  1496. w.PrivKeyBlock, w.CipherName, w.KdfName, w.KdfOpts, err = encrypt(Marshal(pk1))
  1497. if err != nil {
  1498. return nil, err
  1499. }
  1500. b := Marshal(w)
  1501. block := &pem.Block{
  1502. Type: "OPENSSH PRIVATE KEY",
  1503. Bytes: append([]byte(privateKeyAuthMagic), b...),
  1504. }
  1505. return block, nil
  1506. }
  1507. func checkOpenSSHKeyPadding(pad []byte) error {
  1508. for i, b := range pad {
  1509. if int(b) != i+1 {
  1510. return errors.New("ssh: padding not as expected")
  1511. }
  1512. }
  1513. return nil
  1514. }
  1515. func generateOpenSSHPadding(block []byte, blockSize int) []byte {
  1516. for i, l := 0, len(block); (l+i)%blockSize != 0; i++ {
  1517. block = append(block, byte(i+1))
  1518. }
  1519. return block
  1520. }
  1521. // FingerprintLegacyMD5 returns the user presentation of the key's
  1522. // fingerprint as described by RFC 4716 section 4.
  1523. func FingerprintLegacyMD5(pubKey PublicKey) string {
  1524. md5sum := md5.Sum(pubKey.Marshal())
  1525. hexarray := make([]string, len(md5sum))
  1526. for i, c := range md5sum {
  1527. hexarray[i] = hex.EncodeToString([]byte{c})
  1528. }
  1529. return strings.Join(hexarray, ":")
  1530. }
  1531. // FingerprintSHA256 returns the user presentation of the key's
  1532. // fingerprint as unpadded base64 encoded sha256 hash.
  1533. // This format was introduced from OpenSSH 6.8.
  1534. // https://www.openssh.com/txt/release-6.8
  1535. // https://tools.ietf.org/html/rfc4648#section-3.2 (unpadded base64 encoding)
  1536. func FingerprintSHA256(pubKey PublicKey) string {
  1537. sha256sum := sha256.Sum256(pubKey.Marshal())
  1538. hash := base64.RawStdEncoding.EncodeToString(sha256sum[:])
  1539. return "SHA256:" + hash
  1540. }