certs.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. return c.CheckCert(addr, cert)
  264. }
  265. // Authenticate checks a user certificate. Authenticate can be used as
  266. // a value for ServerConfig.PublicKeyCallback.
  267. func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permissions, error) {
  268. cert, ok := pubKey.(*Certificate)
  269. if !ok {
  270. if c.UserKeyFallback != nil {
  271. return c.UserKeyFallback(conn, pubKey)
  272. }
  273. return nil, errors.New("ssh: normal key pairs not accepted")
  274. }
  275. if cert.CertType != UserCert {
  276. return nil, fmt.Errorf("ssh: cert has type %d", cert.CertType)
  277. }
  278. if err := c.CheckCert(conn.User(), cert); err != nil {
  279. return nil, err
  280. }
  281. return &cert.Permissions, nil
  282. }
  283. // CheckCert checks CriticalOptions, ValidPrincipals, revocation, timestamp and
  284. // the signature of the certificate.
  285. func (c *CertChecker) CheckCert(principal string, cert *Certificate) error {
  286. if c.IsRevoked != nil && c.IsRevoked(cert) {
  287. return fmt.Errorf("ssh: certicate serial %d revoked", cert.Serial)
  288. }
  289. for opt, _ := range cert.CriticalOptions {
  290. // sourceAddressCriticalOption will be enforced by
  291. // serverAuthenticate
  292. if opt == sourceAddressCriticalOption {
  293. continue
  294. }
  295. found := false
  296. for _, supp := range c.SupportedCriticalOptions {
  297. if supp == opt {
  298. found = true
  299. break
  300. }
  301. }
  302. if !found {
  303. return fmt.Errorf("ssh: unsupported critical option %q in certificate", opt)
  304. }
  305. }
  306. if len(cert.ValidPrincipals) > 0 {
  307. // By default, certs are valid for all users/hosts.
  308. found := false
  309. for _, p := range cert.ValidPrincipals {
  310. if p == principal {
  311. found = true
  312. break
  313. }
  314. }
  315. if !found {
  316. return fmt.Errorf("ssh: principal %q not in the set of valid principals for given certificate: %q", principal, cert.ValidPrincipals)
  317. }
  318. }
  319. // if this is a host cert, principal is the remote hostname as passed
  320. // to CheckHostCert.
  321. if cert.CertType == HostCert && !c.IsHostAuthority(cert.SignatureKey, principal) {
  322. return fmt.Errorf("ssh: no authorities for hostname: %v", principal)
  323. }
  324. if cert.CertType == UserCert && !c.IsUserAuthority(cert.SignatureKey) {
  325. return fmt.Errorf("ssh: certificate signed by unrecognized authority")
  326. }
  327. clock := c.Clock
  328. if clock == nil {
  329. clock = time.Now
  330. }
  331. unixNow := clock().Unix()
  332. if after := int64(cert.ValidAfter); after < 0 || unixNow < int64(cert.ValidAfter) {
  333. return fmt.Errorf("ssh: cert is not yet valid")
  334. }
  335. if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(CertTimeInfinity) && (unixNow >= before || before < 0) {
  336. return fmt.Errorf("ssh: cert has expired")
  337. }
  338. if err := cert.SignatureKey.Verify(cert.bytesForSigning(), cert.Signature); err != nil {
  339. return fmt.Errorf("ssh: certificate signature does not verify")
  340. }
  341. return nil
  342. }
  343. // SignCert sets c.SignatureKey to the authority's public key and stores a
  344. // Signature, by authority, in the certificate.
  345. func (c *Certificate) SignCert(rand io.Reader, authority Signer) error {
  346. c.Nonce = make([]byte, 32)
  347. if _, err := io.ReadFull(rand, c.Nonce); err != nil {
  348. return err
  349. }
  350. c.SignatureKey = authority.PublicKey()
  351. sig, err := authority.Sign(rand, c.bytesForSigning())
  352. if err != nil {
  353. return err
  354. }
  355. c.Signature = sig
  356. return nil
  357. }
  358. var certAlgoNames = map[string]string{
  359. KeyAlgoRSA: CertAlgoRSAv01,
  360. KeyAlgoDSA: CertAlgoDSAv01,
  361. KeyAlgoECDSA256: CertAlgoECDSA256v01,
  362. KeyAlgoECDSA384: CertAlgoECDSA384v01,
  363. KeyAlgoECDSA521: CertAlgoECDSA521v01,
  364. KeyAlgoED25519: CertAlgoED25519v01,
  365. }
  366. // certToPrivAlgo returns the underlying algorithm for a certificate algorithm.
  367. // Panics if a non-certificate algorithm is passed.
  368. func certToPrivAlgo(algo string) string {
  369. for privAlgo, pubAlgo := range certAlgoNames {
  370. if pubAlgo == algo {
  371. return privAlgo
  372. }
  373. }
  374. panic("unknown cert algorithm")
  375. }
  376. func (cert *Certificate) bytesForSigning() []byte {
  377. c2 := *cert
  378. c2.Signature = nil
  379. out := c2.Marshal()
  380. // Drop trailing signature length.
  381. return out[:len(out)-4]
  382. }
  383. // Marshal serializes c into OpenSSH's wire format. It is part of the
  384. // PublicKey interface.
  385. func (c *Certificate) Marshal() []byte {
  386. generic := genericCertData{
  387. Serial: c.Serial,
  388. CertType: c.CertType,
  389. KeyId: c.KeyId,
  390. ValidPrincipals: marshalStringList(c.ValidPrincipals),
  391. ValidAfter: uint64(c.ValidAfter),
  392. ValidBefore: uint64(c.ValidBefore),
  393. CriticalOptions: marshalTuples(c.CriticalOptions),
  394. Extensions: marshalTuples(c.Extensions),
  395. Reserved: c.Reserved,
  396. SignatureKey: c.SignatureKey.Marshal(),
  397. }
  398. if c.Signature != nil {
  399. generic.Signature = Marshal(c.Signature)
  400. }
  401. genericBytes := Marshal(&generic)
  402. keyBytes := c.Key.Marshal()
  403. _, keyBytes, _ = parseString(keyBytes)
  404. prefix := Marshal(&struct {
  405. Name string
  406. Nonce []byte
  407. Key []byte `ssh:"rest"`
  408. }{c.Type(), c.Nonce, keyBytes})
  409. result := make([]byte, 0, len(prefix)+len(genericBytes))
  410. result = append(result, prefix...)
  411. result = append(result, genericBytes...)
  412. return result
  413. }
  414. // Type returns the key name. It is part of the PublicKey interface.
  415. func (c *Certificate) Type() string {
  416. algo, ok := certAlgoNames[c.Key.Type()]
  417. if !ok {
  418. panic("unknown cert key type " + c.Key.Type())
  419. }
  420. return algo
  421. }
  422. // Verify verifies a signature against the certificate's public
  423. // key. It is part of the PublicKey interface.
  424. func (c *Certificate) Verify(data []byte, sig *Signature) error {
  425. return c.Key.Verify(data, sig)
  426. }
  427. func parseSignatureBody(in []byte) (out *Signature, rest []byte, ok bool) {
  428. format, in, ok := parseString(in)
  429. if !ok {
  430. return
  431. }
  432. out = &Signature{
  433. Format: string(format),
  434. }
  435. if out.Blob, in, ok = parseString(in); !ok {
  436. return
  437. }
  438. return out, in, ok
  439. }
  440. func parseSignature(in []byte) (out *Signature, rest []byte, ok bool) {
  441. sigBytes, rest, ok := parseString(in)
  442. if !ok {
  443. return
  444. }
  445. out, trailing, ok := parseSignatureBody(sigBytes)
  446. if !ok || len(trailing) > 0 {
  447. return nil, nil, false
  448. }
  449. return
  450. }