Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

certs.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. "errors"
  8. "fmt"
  9. "io"
  10. "net"
  11. "sort"
  12. "time"
  13. )
  14. // These constants from [PROTOCOL.certkeys] represent the algorithm names
  15. // for certificate types supported by this package.
  16. const (
  17. CertAlgoRSAv01 = "ssh-rsa-cert-v01@openssh.com"
  18. CertAlgoDSAv01 = "ssh-dss-cert-v01@openssh.com"
  19. CertAlgoECDSA256v01 = "ecdsa-sha2-nistp256-cert-v01@openssh.com"
  20. CertAlgoECDSA384v01 = "ecdsa-sha2-nistp384-cert-v01@openssh.com"
  21. CertAlgoECDSA521v01 = "ecdsa-sha2-nistp521-cert-v01@openssh.com"
  22. CertAlgoED25519v01 = "ssh-ed25519-cert-v01@openssh.com"
  23. )
  24. // Certificate types distinguish between host and user
  25. // certificates. The values can be set in the CertType field of
  26. // Certificate.
  27. const (
  28. UserCert = 1
  29. HostCert = 2
  30. )
  31. // Signature represents a cryptographic signature.
  32. type Signature struct {
  33. Format string
  34. Blob []byte
  35. }
  36. // CertTimeInfinity can be used for OpenSSHCertV01.ValidBefore to indicate that
  37. // a certificate does not expire.
  38. const CertTimeInfinity = 1<<64 - 1
  39. // An Certificate represents an OpenSSH certificate as defined in
  40. // [PROTOCOL.certkeys]?rev=1.8. The Certificate type implements the
  41. // PublicKey interface, so it can be unmarshaled using
  42. // ParsePublicKey.
  43. type Certificate struct {
  44. Nonce []byte
  45. Key PublicKey
  46. Serial uint64
  47. CertType uint32
  48. KeyId string
  49. ValidPrincipals []string
  50. ValidAfter uint64
  51. ValidBefore uint64
  52. Permissions
  53. Reserved []byte
  54. SignatureKey PublicKey
  55. Signature *Signature
  56. }
  57. // genericCertData holds the key-independent part of the certificate data.
  58. // Overall, certificates contain an nonce, public key fields and
  59. // key-independent fields.
  60. type genericCertData struct {
  61. Serial uint64
  62. CertType uint32
  63. KeyId string
  64. ValidPrincipals []byte
  65. ValidAfter uint64
  66. ValidBefore uint64
  67. CriticalOptions []byte
  68. Extensions []byte
  69. Reserved []byte
  70. SignatureKey []byte
  71. Signature []byte
  72. }
  73. func marshalStringList(namelist []string) []byte {
  74. var to []byte
  75. for _, name := range namelist {
  76. s := struct{ N string }{name}
  77. to = append(to, Marshal(&s)...)
  78. }
  79. return to
  80. }
  81. type optionsTuple struct {
  82. Key string
  83. Value []byte
  84. }
  85. type optionsTupleValue struct {
  86. Value string
  87. }
  88. // serialize a map of critical options or extensions
  89. // issue #10569 - per [PROTOCOL.certkeys] and SSH implementation,
  90. // we need two length prefixes for a non-empty string value
  91. func marshalTuples(tups map[string]string) []byte {
  92. keys := make([]string, 0, len(tups))
  93. for key := range tups {
  94. keys = append(keys, key)
  95. }
  96. sort.Strings(keys)
  97. var ret []byte
  98. for _, key := range keys {
  99. s := optionsTuple{Key: key}
  100. if value := tups[key]; len(value) > 0 {
  101. s.Value = Marshal(&optionsTupleValue{value})
  102. }
  103. ret = append(ret, Marshal(&s)...)
  104. }
  105. return ret
  106. }
  107. // issue #10569 - per [PROTOCOL.certkeys] and SSH implementation,
  108. // we need two length prefixes for a non-empty option value
  109. func parseTuples(in []byte) (map[string]string, error) {
  110. tups := map[string]string{}
  111. var lastKey string
  112. var haveLastKey bool
  113. for len(in) > 0 {
  114. var key, val, extra []byte
  115. var ok bool
  116. if key, in, ok = parseString(in); !ok {
  117. return nil, errShortRead
  118. }
  119. keyStr := string(key)
  120. // according to [PROTOCOL.certkeys], the names must be in
  121. // lexical order.
  122. if haveLastKey && keyStr <= lastKey {
  123. return nil, fmt.Errorf("ssh: certificate options are not in lexical order")
  124. }
  125. lastKey, haveLastKey = keyStr, true
  126. // the next field is a data field, which if non-empty has a string embedded
  127. if val, in, ok = parseString(in); !ok {
  128. return nil, errShortRead
  129. }
  130. if len(val) > 0 {
  131. val, extra, ok = parseString(val)
  132. if !ok {
  133. return nil, errShortRead
  134. }
  135. if len(extra) > 0 {
  136. return nil, fmt.Errorf("ssh: unexpected trailing data after certificate option value")
  137. }
  138. tups[keyStr] = string(val)
  139. } else {
  140. tups[keyStr] = ""
  141. }
  142. }
  143. return tups, nil
  144. }
  145. func parseCert(in []byte, privAlgo string) (*Certificate, error) {
  146. nonce, rest, ok := parseString(in)
  147. if !ok {
  148. return nil, errShortRead
  149. }
  150. key, rest, err := parsePubKey(rest, privAlgo)
  151. if err != nil {
  152. return nil, err
  153. }
  154. var g genericCertData
  155. if err := Unmarshal(rest, &g); err != nil {
  156. return nil, err
  157. }
  158. c := &Certificate{
  159. Nonce: nonce,
  160. Key: key,
  161. Serial: g.Serial,
  162. CertType: g.CertType,
  163. KeyId: g.KeyId,
  164. ValidAfter: g.ValidAfter,
  165. ValidBefore: g.ValidBefore,
  166. }
  167. for principals := g.ValidPrincipals; len(principals) > 0; {
  168. principal, rest, ok := parseString(principals)
  169. if !ok {
  170. return nil, errShortRead
  171. }
  172. c.ValidPrincipals = append(c.ValidPrincipals, string(principal))
  173. principals = rest
  174. }
  175. c.CriticalOptions, err = parseTuples(g.CriticalOptions)
  176. if err != nil {
  177. return nil, err
  178. }
  179. c.Extensions, err = parseTuples(g.Extensions)
  180. if err != nil {
  181. return nil, err
  182. }
  183. c.Reserved = g.Reserved
  184. k, err := ParsePublicKey(g.SignatureKey)
  185. if err != nil {
  186. return nil, err
  187. }
  188. c.SignatureKey = k
  189. c.Signature, rest, ok = parseSignatureBody(g.Signature)
  190. if !ok || len(rest) > 0 {
  191. return nil, errors.New("ssh: signature parse error")
  192. }
  193. return c, nil
  194. }
  195. type openSSHCertSigner struct {
  196. pub *Certificate
  197. signer Signer
  198. }
  199. type algorithmOpenSSHCertSigner struct {
  200. *openSSHCertSigner
  201. algorithmSigner AlgorithmSigner
  202. }
  203. // NewCertSigner returns a Signer that signs with the given Certificate, whose
  204. // private key is held by signer. It returns an error if the public key in cert
  205. // doesn't match the key used by signer.
  206. func NewCertSigner(cert *Certificate, signer Signer) (Signer, error) {
  207. if bytes.Compare(cert.Key.Marshal(), signer.PublicKey().Marshal()) != 0 {
  208. return nil, errors.New("ssh: signer and cert have different public key")
  209. }
  210. if algorithmSigner, ok := signer.(AlgorithmSigner); ok {
  211. return &algorithmOpenSSHCertSigner{
  212. &openSSHCertSigner{cert, signer}, algorithmSigner}, nil
  213. } else {
  214. return &openSSHCertSigner{cert, signer}, nil
  215. }
  216. }
  217. func (s *openSSHCertSigner) Sign(rand io.Reader, data []byte) (*Signature, error) {
  218. return s.signer.Sign(rand, data)
  219. }
  220. func (s *openSSHCertSigner) PublicKey() PublicKey {
  221. return s.pub
  222. }
  223. func (s *algorithmOpenSSHCertSigner) SignWithAlgorithm(rand io.Reader, data []byte, algorithm string) (*Signature, error) {
  224. return s.algorithmSigner.SignWithAlgorithm(rand, data, algorithm)
  225. }
  226. const sourceAddressCriticalOption = "source-address"
  227. // CertChecker does the work of verifying a certificate. Its methods
  228. // can be plugged into ClientConfig.HostKeyCallback and
  229. // ServerConfig.PublicKeyCallback. For the CertChecker to work,
  230. // minimally, the IsAuthority callback should be set.
  231. type CertChecker struct {
  232. // SupportedCriticalOptions lists the CriticalOptions that the
  233. // server application layer understands. These are only used
  234. // for user certificates.
  235. SupportedCriticalOptions []string
  236. // IsUserAuthority should return true if the key is recognized as an
  237. // authority for the given user certificate. This allows for
  238. // certificates to be signed by other certificates. This must be set
  239. // if this CertChecker will be checking user certificates.
  240. IsUserAuthority func(auth PublicKey) bool
  241. // IsHostAuthority should report whether the key is recognized as
  242. // an authority for this host. This allows for certificates to be
  243. // signed by other keys, and for those other keys to only be valid
  244. // signers for particular hostnames. This must be set if this
  245. // CertChecker will be checking host certificates.
  246. IsHostAuthority func(auth PublicKey, address string) bool
  247. // Clock is used for verifying time stamps. If nil, time.Now
  248. // is used.
  249. Clock func() time.Time
  250. // UserKeyFallback is called when CertChecker.Authenticate encounters a
  251. // public key that is not a certificate. It must implement validation
  252. // of user keys or else, if nil, all such keys are rejected.
  253. UserKeyFallback func(conn ConnMetadata, key PublicKey) (*Permissions, error)
  254. // HostKeyFallback is called when CertChecker.CheckHostKey encounters a
  255. // public key that is not a certificate. It must implement host key
  256. // validation or else, if nil, all such keys are rejected.
  257. HostKeyFallback HostKeyCallback
  258. // IsRevoked is called for each certificate so that revocation checking
  259. // can be implemented. It should return true if the given certificate
  260. // is revoked and false otherwise. If nil, no certificates are
  261. // considered to have been revoked.
  262. IsRevoked func(cert *Certificate) bool
  263. }
  264. // CheckHostKey checks a host key certificate. This method can be
  265. // plugged into ClientConfig.HostKeyCallback.
  266. func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key PublicKey) error {
  267. cert, ok := key.(*Certificate)
  268. if !ok {
  269. if c.HostKeyFallback != nil {
  270. return c.HostKeyFallback(addr, remote, key)
  271. }
  272. return errors.New("ssh: non-certificate host key")
  273. }
  274. if cert.CertType != HostCert {
  275. return fmt.Errorf("ssh: certificate presented as a host key has type %d", cert.CertType)
  276. }
  277. if !c.IsHostAuthority(cert.SignatureKey, addr) {
  278. return fmt.Errorf("ssh: no authorities for hostname: %v", addr)
  279. }
  280. hostname, _, err := net.SplitHostPort(addr)
  281. if err != nil {
  282. return err
  283. }
  284. // Pass hostname only as principal for host certificates (consistent with OpenSSH)
  285. return c.CheckCert(hostname, cert)
  286. }
  287. // Authenticate checks a user certificate. Authenticate can be used as
  288. // a value for ServerConfig.PublicKeyCallback.
  289. func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error) {
  290. cert, ok := pubKey.(*Certificate)
  291. if !ok {
  292. if c.UserKeyFallback != nil {
  293. return c.UserKeyFallback(conn, pubKey)
  294. }
  295. return nil, errors.New("ssh: normal key pairs not accepted")
  296. }
  297. if cert.CertType != UserCert {
  298. return nil, fmt.Errorf("ssh: cert has type %d", cert.CertType)
  299. }
  300. if !c.IsUserAuthority(cert.SignatureKey) {
  301. return nil, fmt.Errorf("ssh: certificate signed by unrecognized authority")
  302. }
  303. if err := c.CheckCert(conn.User(), cert); err != nil {
  304. return nil, err
  305. }
  306. return &cert.Permissions, nil
  307. }
  308. // CheckCert checks CriticalOptions, ValidPrincipals, revocation, timestamp and
  309. // the signature of the certificate.
  310. func (c *CertChecker) CheckCert(principal string, cert *Certificate) error {
  311. if c.IsRevoked != nil && c.IsRevoked(cert) {
  312. return fmt.Errorf("ssh: certificate serial %d revoked", cert.Serial)
  313. }
  314. for opt := range cert.CriticalOptions {
  315. // sourceAddressCriticalOption will be enforced by
  316. // serverAuthenticate
  317. if opt == sourceAddressCriticalOption {
  318. continue
  319. }
  320. found := false
  321. for _, supp := range c.SupportedCriticalOptions {
  322. if supp == opt {
  323. found = true
  324. break
  325. }
  326. }
  327. if !found {
  328. return fmt.Errorf("ssh: unsupported critical option %q in certificate", opt)
  329. }
  330. }
  331. if len(cert.ValidPrincipals) > 0 {
  332. // By default, certs are valid for all users/hosts.
  333. found := false
  334. for _, p := range cert.ValidPrincipals {
  335. if p == principal {
  336. found = true
  337. break
  338. }
  339. }
  340. if !found {
  341. return fmt.Errorf("ssh: principal %q not in the set of valid principals for given certificate: %q", principal, cert.ValidPrincipals)
  342. }
  343. }
  344. clock := c.Clock
  345. if clock == nil {
  346. clock = time.Now
  347. }
  348. unixNow := clock().Unix()
  349. if after := int64(cert.ValidAfter); after < 0 || unixNow < int64(cert.ValidAfter) {
  350. return fmt.Errorf("ssh: cert is not yet valid")
  351. }
  352. if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(CertTimeInfinity) && (unixNow >= before || before < 0) {
  353. return fmt.Errorf("ssh: cert has expired")
  354. }
  355. if err := cert.SignatureKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil {
  356. return fmt.Errorf("ssh: certificate signature does not verify")
  357. }
  358. return nil
  359. }
  360. // SignCert sets c.SignatureKey to the authority's public key and stores a
  361. // Signature, by authority, in the certificate.
  362. func (c *Certificate) SignCert(rand io.Reader, authority Signer) error {
  363. c.Nonce = make([]byte, 32)
  364. if _, err := io.ReadFull(rand, c.Nonce); err != nil {
  365. return err
  366. }
  367. c.SignatureKey = authority.PublicKey()
  368. sig, err := authority.Sign(rand, c.bytesForSigning())
  369. if err != nil {
  370. return err
  371. }
  372. c.Signature = sig
  373. return nil
  374. }
  375. var certAlgoNames = map[string]string{
  376. KeyAlgoRSA: CertAlgoRSAv01,
  377. KeyAlgoDSA: CertAlgoDSAv01,
  378. KeyAlgoECDSA256: CertAlgoECDSA256v01,
  379. KeyAlgoECDSA384: CertAlgoECDSA384v01,
  380. KeyAlgoECDSA521: CertAlgoECDSA521v01,
  381. KeyAlgoED25519: CertAlgoED25519v01,
  382. }
  383. // certToPrivAlgo returns the underlying algorithm for a certificate algorithm.
  384. // Panics if a non-certificate algorithm is passed.
  385. func certToPrivAlgo(algo string) string {
  386. for privAlgo, pubAlgo := range certAlgoNames {
  387. if pubAlgo == algo {
  388. return privAlgo
  389. }
  390. }
  391. panic("unknown cert algorithm")
  392. }
  393. func (cert *Certificate) bytesForSigning() []byte {
  394. c2 := *cert
  395. c2.Signature = nil
  396. out := c2.Marshal()
  397. // Drop trailing signature length.
  398. return out[:len(out)-4]
  399. }
  400. // Marshal serializes c into OpenSSH's wire format. It is part of the
  401. // PublicKey interface.
  402. func (c *Certificate) Marshal() []byte {
  403. generic := genericCertData{
  404. Serial: c.Serial,
  405. CertType: c.CertType,
  406. KeyId: c.KeyId,
  407. ValidPrincipals: marshalStringList(c.ValidPrincipals),
  408. ValidAfter: uint64(c.ValidAfter),
  409. ValidBefore: uint64(c.ValidBefore),
  410. CriticalOptions: marshalTuples(c.CriticalOptions),
  411. Extensions: marshalTuples(c.Extensions),
  412. Reserved: c.Reserved,
  413. SignatureKey: c.SignatureKey.Marshal(),
  414. }
  415. if c.Signature != nil {
  416. generic.Signature = Marshal(c.Signature)
  417. }
  418. genericBytes := Marshal(&generic)
  419. keyBytes := c.Key.Marshal()
  420. _, keyBytes, _ = parseString(keyBytes)
  421. prefix := Marshal(&struct {
  422. Name string
  423. Nonce []byte
  424. Key []byte `ssh:"rest"`
  425. }{c.Type(), c.Nonce, keyBytes})
  426. result := make([]byte, 0, len(prefix)+len(genericBytes))
  427. result = append(result, prefix...)
  428. result = append(result, genericBytes...)
  429. return result
  430. }
  431. // Type returns the key name. It is part of the PublicKey interface.
  432. func (c *Certificate) Type() string {
  433. algo, ok := certAlgoNames[c.Key.Type()]
  434. if !ok {
  435. panic("unknown cert key type " + c.Key.Type())
  436. }
  437. return algo
  438. }
  439. // Verify verifies a signature against the certificate's public
  440. // key. It is part of the PublicKey interface.
  441. func (c *Certificate) Verify(data []byte, sig *Signature) error {
  442. return c.Key.Verify(data, sig)
  443. }
  444. func parseSignatureBody(in []byte) (out *Signature, rest []byte, ok bool) {
  445. format, in, ok := parseString(in)
  446. if !ok {
  447. return
  448. }
  449. out = &Signature{
  450. Format: string(format),
  451. }
  452. if out.Blob, in, ok = parseString(in); !ok {
  453. return
  454. }
  455. return out, in, ok
  456. }
  457. func parseSignature(in []byte) (out *Signature, rest []byte, ok bool) {
  458. sigBytes, rest, ok := parseString(in)
  459. if !ok {
  460. return
  461. }
  462. out, trailing, ok := parseSignatureBody(sigBytes)
  463. if !ok || len(trailing) > 0 {
  464. return nil, nil, false
  465. }
  466. return
  467. }