certs.go 14 KB

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