keys.go 45 KB

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