4
0

api.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto"
  6. "crypto/dsa" //nolint:staticcheck // support legacy algorithms
  7. "crypto/ecdsa"
  8. "crypto/ed25519"
  9. "crypto/rsa"
  10. "crypto/x509"
  11. "encoding/asn1"
  12. "encoding/base64"
  13. "encoding/json"
  14. "encoding/pem"
  15. "fmt"
  16. "net/http"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "github.com/go-chi/chi/v5"
  21. "github.com/pkg/errors"
  22. "go.step.sm/crypto/mldsa"
  23. "go.step.sm/crypto/sshutil"
  24. "golang.org/x/crypto/ssh"
  25. "github.com/smallstep/certificates/api/log"
  26. "github.com/smallstep/certificates/api/models"
  27. "github.com/smallstep/certificates/api/render"
  28. "github.com/smallstep/certificates/authority"
  29. "github.com/smallstep/certificates/authority/config"
  30. "github.com/smallstep/certificates/authority/provisioner"
  31. "github.com/smallstep/certificates/errs"
  32. "github.com/smallstep/certificates/internal/cast"
  33. "github.com/smallstep/certificates/logging"
  34. )
  35. // Authority is the interface implemented by a CA authority.
  36. type Authority interface {
  37. SSHAuthority
  38. // context specifies the Authorize[Sign|Revoke|etc.] method.
  39. Authorize(ctx context.Context, ott string) ([]provisioner.SignOption, error)
  40. AuthorizeRenewToken(ctx context.Context, ott string) (*x509.Certificate, error)
  41. GetTLSOptions() *config.TLSOptions
  42. Root(shasum string) (*x509.Certificate, error)
  43. SignWithContext(ctx context.Context, cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error)
  44. Renew(peer *x509.Certificate) ([]*x509.Certificate, error)
  45. RenewContext(ctx context.Context, peer *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error)
  46. Rekey(peer *x509.Certificate, pk crypto.PublicKey) ([]*x509.Certificate, error)
  47. LoadProvisionerByCertificate(*x509.Certificate) (provisioner.Interface, error)
  48. LoadProvisionerByName(string) (provisioner.Interface, error)
  49. GetProvisioners(cursor string, limit int) (provisioner.List, string, error)
  50. Revoke(context.Context, *authority.RevokeOptions) error
  51. GetEncryptedKey(kid string) (string, error)
  52. GetRoots() ([]*x509.Certificate, error)
  53. GetIntermediateCertificates() []*x509.Certificate
  54. GetFederation() ([]*x509.Certificate, error)
  55. Version() authority.Version
  56. GetCertificateRevocationList() (*authority.CertificateRevocationListInfo, error)
  57. }
  58. // mustAuthority will be replaced on unit tests.
  59. var mustAuthority = func(ctx context.Context) Authority {
  60. return authority.MustFromContext(ctx)
  61. }
  62. // TimeDuration is an alias of provisioner.TimeDuration
  63. type TimeDuration = provisioner.TimeDuration
  64. // NewTimeDuration returns a TimeDuration with the defined time.
  65. func NewTimeDuration(t time.Time) TimeDuration {
  66. return provisioner.NewTimeDuration(t)
  67. }
  68. // ParseTimeDuration returns a new TimeDuration parsing the RFC 3339 time or
  69. // time.Duration string.
  70. func ParseTimeDuration(s string) (TimeDuration, error) {
  71. return provisioner.ParseTimeDuration(s)
  72. }
  73. // Certificate wraps a *x509.Certificate and adds the json.Marshaler interface.
  74. type Certificate struct {
  75. *x509.Certificate
  76. }
  77. // NewCertificate is a helper method that returns a Certificate from a
  78. // *x509.Certificate.
  79. func NewCertificate(cr *x509.Certificate) Certificate {
  80. return Certificate{
  81. Certificate: cr,
  82. }
  83. }
  84. // reset sets the inner x509.CertificateRequest to nil
  85. func (c *Certificate) reset() {
  86. if c != nil {
  87. c.Certificate = nil
  88. }
  89. }
  90. // MarshalJSON implements the json.Marshaler interface. The certificate is
  91. // quoted string using the PEM encoding.
  92. func (c Certificate) MarshalJSON() ([]byte, error) {
  93. if c.Certificate == nil {
  94. return []byte("null"), nil
  95. }
  96. block := pem.EncodeToMemory(&pem.Block{
  97. Type: "CERTIFICATE",
  98. Bytes: c.Raw,
  99. })
  100. return json.Marshal(string(block))
  101. }
  102. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  103. // expected to be a quoted string using the PEM encoding.
  104. func (c *Certificate) UnmarshalJSON(data []byte) error {
  105. var s string
  106. if err := json.Unmarshal(data, &s); err != nil {
  107. return errors.Wrap(err, "error decoding certificate")
  108. }
  109. // Make sure the inner x509.Certificate is nil
  110. if s == "null" || s == "" {
  111. c.reset()
  112. return nil
  113. }
  114. block, _ := pem.Decode([]byte(s))
  115. if block == nil {
  116. return errors.New("error decoding certificate")
  117. }
  118. cert, err := x509.ParseCertificate(block.Bytes)
  119. if err != nil {
  120. return errors.Wrap(err, "error decoding certificate")
  121. }
  122. c.Certificate = cert
  123. return nil
  124. }
  125. // CertificateRequest wraps a *x509.CertificateRequest and adds the
  126. // json.Unmarshaler interface.
  127. type CertificateRequest struct {
  128. *x509.CertificateRequest
  129. }
  130. // NewCertificateRequest is a helper method that returns a CertificateRequest
  131. // from a *x509.CertificateRequest.
  132. func NewCertificateRequest(cr *x509.CertificateRequest) CertificateRequest {
  133. return CertificateRequest{
  134. CertificateRequest: cr,
  135. }
  136. }
  137. // reset sets the inner x509.CertificateRequest to nil
  138. func (c *CertificateRequest) reset() {
  139. if c != nil {
  140. c.CertificateRequest = nil
  141. }
  142. }
  143. // MarshalJSON implements the json.Marshaler interface. The certificate request
  144. // is a quoted string using the PEM encoding.
  145. func (c CertificateRequest) MarshalJSON() ([]byte, error) {
  146. if c.CertificateRequest == nil {
  147. return []byte("null"), nil
  148. }
  149. block := pem.EncodeToMemory(&pem.Block{
  150. Type: "CERTIFICATE REQUEST",
  151. Bytes: c.Raw,
  152. })
  153. return json.Marshal(string(block))
  154. }
  155. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate
  156. // request is expected to be a quoted string using the PEM encoding.
  157. func (c *CertificateRequest) UnmarshalJSON(data []byte) error {
  158. var s string
  159. if err := json.Unmarshal(data, &s); err != nil {
  160. return errors.Wrap(err, "error decoding csr")
  161. }
  162. // Make sure the inner x509.CertificateRequest is nil
  163. if s == "null" || s == "" {
  164. c.reset()
  165. return nil
  166. }
  167. block, _ := pem.Decode([]byte(s))
  168. if block == nil {
  169. return errors.New("error decoding csr")
  170. }
  171. cr, err := x509.ParseCertificateRequest(block.Bytes)
  172. if err != nil {
  173. return errors.Wrap(err, "error decoding csr")
  174. }
  175. c.CertificateRequest = cr
  176. return nil
  177. }
  178. // Router defines a common router interface.
  179. type Router interface {
  180. // MethodFunc adds routes for `pattern` that matches
  181. // the `method` HTTP method.
  182. MethodFunc(method, pattern string, h http.HandlerFunc)
  183. }
  184. // RouterHandler is the interface that a HTTP handler that manages multiple
  185. // endpoints will implement.
  186. type RouterHandler interface {
  187. Route(r Router)
  188. }
  189. // VersionResponse is the response object that returns the version of the
  190. // server.
  191. type VersionResponse struct {
  192. Version string `json:"version"`
  193. RequireClientAuthentication bool `json:"requireClientAuthentication,omitempty"`
  194. }
  195. // HealthResponse is the response object that returns the health of the server.
  196. type HealthResponse struct {
  197. Status string `json:"status"`
  198. }
  199. // RootResponse is the response object that returns the PEM of a root certificate.
  200. type RootResponse struct {
  201. RootPEM Certificate `json:"ca"`
  202. }
  203. // ProvisionersResponse is the response object that returns the list of
  204. // provisioners.
  205. type ProvisionersResponse struct {
  206. Provisioners provisioner.List
  207. NextCursor string
  208. }
  209. const redacted = "*** REDACTED ***"
  210. func scepFromProvisioner(p *provisioner.SCEP) *models.SCEP {
  211. return &models.SCEP{
  212. ID: p.ID,
  213. Type: p.Type,
  214. Name: p.Name,
  215. ForceCN: p.ForceCN,
  216. ChallengePassword: redacted,
  217. Capabilities: p.Capabilities,
  218. IncludeRoot: p.IncludeRoot,
  219. ExcludeIntermediate: p.ExcludeIntermediate,
  220. MinimumPublicKeyLength: p.MinimumPublicKeyLength,
  221. DecrypterCertificate: []byte(redacted),
  222. DecrypterKeyPEM: []byte(redacted),
  223. DecrypterKeyURI: redacted,
  224. DecrypterKeyPassword: redacted,
  225. EncryptionAlgorithmIdentifier: p.EncryptionAlgorithmIdentifier,
  226. Options: p.Options,
  227. Claims: p.Claims,
  228. }
  229. }
  230. // MarshalJSON implements json.Marshaler. It marshals the ProvisionersResponse
  231. // into a byte slice.
  232. //
  233. // Special treatment is given to the SCEP provisioner, as it contains a
  234. // challenge secret that MUST NOT be leaked in (public) HTTP responses. The
  235. // challenge value is thus redacted in HTTP responses.
  236. func (p ProvisionersResponse) MarshalJSON() ([]byte, error) {
  237. var responseProvisioners provisioner.List
  238. for _, item := range p.Provisioners {
  239. scepProv, ok := item.(*provisioner.SCEP)
  240. if !ok {
  241. responseProvisioners = append(responseProvisioners, item)
  242. continue
  243. }
  244. responseProvisioners = append(responseProvisioners, scepFromProvisioner(scepProv))
  245. }
  246. var list = struct {
  247. Provisioners []provisioner.Interface `json:"provisioners"`
  248. NextCursor string `json:"nextCursor"`
  249. }{
  250. Provisioners: []provisioner.Interface(responseProvisioners),
  251. NextCursor: p.NextCursor,
  252. }
  253. return json.Marshal(list)
  254. }
  255. // ProvisionerKeyResponse is the response object that returns the encrypted key
  256. // of a provisioner.
  257. type ProvisionerKeyResponse struct {
  258. Key string `json:"key"`
  259. }
  260. // RootsResponse is the response object of the roots request.
  261. type RootsResponse struct {
  262. Certificates []Certificate `json:"crts"`
  263. }
  264. // IntermediatesResponse is the response object of the intermediates request.
  265. type IntermediatesResponse struct {
  266. Certificates []Certificate `json:"crts"`
  267. }
  268. // FederationResponse is the response object of the federation request.
  269. type FederationResponse struct {
  270. Certificates []Certificate `json:"crts"`
  271. }
  272. // caHandler is the type used to implement the different CA HTTP endpoints.
  273. type caHandler struct {
  274. Authority Authority
  275. }
  276. // Route configures the http request router.
  277. func (h *caHandler) Route(r Router) {
  278. Route(r)
  279. }
  280. // New creates a new RouterHandler with the CA endpoints.
  281. //
  282. // Deprecated: Use api.Route(r Router)
  283. func New(Authority) RouterHandler {
  284. return &caHandler{}
  285. }
  286. func Route(r Router) {
  287. r.MethodFunc("GET", "/version", Version)
  288. r.MethodFunc("GET", "/health", Health)
  289. r.MethodFunc("GET", "/root/{sha}", Root)
  290. r.MethodFunc("POST", "/sign", Sign)
  291. r.MethodFunc("POST", "/renew", Renew)
  292. r.MethodFunc("POST", "/rekey", Rekey)
  293. r.MethodFunc("POST", "/revoke", Revoke)
  294. r.MethodFunc("GET", "/crl", CRL)
  295. r.MethodFunc("GET", "/provisioners", Provisioners)
  296. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", ProvisionerKey)
  297. r.MethodFunc("GET", "/roots", Roots)
  298. r.MethodFunc("GET", "/roots.pem", RootsPEM)
  299. r.MethodFunc("GET", "/intermediates", Intermediates)
  300. r.MethodFunc("GET", "/intermediates.pem", IntermediatesPEM)
  301. r.MethodFunc("GET", "/federation", Federation)
  302. // SSH CA
  303. r.MethodFunc("POST", "/ssh/sign", SSHSign)
  304. r.MethodFunc("POST", "/ssh/renew", SSHRenew)
  305. r.MethodFunc("POST", "/ssh/revoke", SSHRevoke)
  306. r.MethodFunc("POST", "/ssh/rekey", SSHRekey)
  307. r.MethodFunc("GET", "/ssh/roots", SSHRoots)
  308. r.MethodFunc("GET", "/ssh/federation", SSHFederation)
  309. r.MethodFunc("POST", "/ssh/config", SSHConfig)
  310. r.MethodFunc("POST", "/ssh/config/{type}", SSHConfig)
  311. r.MethodFunc("POST", "/ssh/check-host", SSHCheckHost)
  312. r.MethodFunc("GET", "/ssh/hosts", SSHGetHosts)
  313. r.MethodFunc("POST", "/ssh/bastion", SSHBastion)
  314. // For compatibility with old code:
  315. r.MethodFunc("POST", "/re-sign", Renew)
  316. r.MethodFunc("POST", "/sign-ssh", SSHSign)
  317. r.MethodFunc("GET", "/ssh/get-hosts", SSHGetHosts)
  318. }
  319. // Version is an HTTP handler that returns the version of the server.
  320. func Version(w http.ResponseWriter, r *http.Request) {
  321. v := mustAuthority(r.Context()).Version()
  322. render.JSON(w, r, VersionResponse{
  323. Version: v.Version,
  324. RequireClientAuthentication: v.RequireClientAuthentication,
  325. })
  326. }
  327. // Health is an HTTP handler that returns the status of the server.
  328. func Health(w http.ResponseWriter, r *http.Request) {
  329. render.JSON(w, r, HealthResponse{Status: "ok"})
  330. }
  331. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  332. // certificate for the given SHA256.
  333. func Root(w http.ResponseWriter, r *http.Request) {
  334. sha := chi.URLParam(r, "sha")
  335. sum := strings.ToLower(strings.ReplaceAll(sha, "-", ""))
  336. // Load root certificate with the
  337. cert, err := mustAuthority(r.Context()).Root(sum)
  338. if err != nil {
  339. render.Error(w, r, errs.NotFoundErr(err, errs.WithMessage("root certificate with fingerprint %q was not found", sum)))
  340. return
  341. }
  342. render.JSON(w, r, &RootResponse{RootPEM: Certificate{cert}})
  343. }
  344. func certChainToPEM(certChain []*x509.Certificate) []Certificate {
  345. certChainPEM := make([]Certificate, 0, len(certChain))
  346. for _, c := range certChain {
  347. certChainPEM = append(certChainPEM, Certificate{c})
  348. }
  349. return certChainPEM
  350. }
  351. // Provisioners returns the list of provisioners configured in the authority.
  352. func Provisioners(w http.ResponseWriter, r *http.Request) {
  353. cursor, limit, err := ParseCursor(r)
  354. if err != nil {
  355. render.Error(w, r, err)
  356. return
  357. }
  358. p, next, err := mustAuthority(r.Context()).GetProvisioners(cursor, limit)
  359. if err != nil {
  360. render.Error(w, r, errs.InternalServerErr(err))
  361. return
  362. }
  363. render.JSON(w, r, &ProvisionersResponse{
  364. Provisioners: p,
  365. NextCursor: next,
  366. })
  367. }
  368. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  369. func ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  370. kid := chi.URLParam(r, "kid")
  371. key, err := mustAuthority(r.Context()).GetEncryptedKey(kid)
  372. if err != nil {
  373. render.Error(w, r, errs.NotFoundErr(err))
  374. return
  375. }
  376. render.JSON(w, r, &ProvisionerKeyResponse{key})
  377. }
  378. // Roots returns all the root certificates for the CA.
  379. func Roots(w http.ResponseWriter, r *http.Request) {
  380. roots, err := mustAuthority(r.Context()).GetRoots()
  381. if err != nil {
  382. render.Error(w, r, errs.ForbiddenErr(err, "error getting roots"))
  383. return
  384. }
  385. certs := make([]Certificate, len(roots))
  386. for i := range roots {
  387. certs[i] = Certificate{roots[i]}
  388. }
  389. render.JSONStatus(w, r, &RootsResponse{
  390. Certificates: certs,
  391. }, http.StatusCreated)
  392. }
  393. // RootsPEM returns all the root certificates for the CA in PEM format.
  394. func RootsPEM(w http.ResponseWriter, r *http.Request) {
  395. roots, err := mustAuthority(r.Context()).GetRoots()
  396. if err != nil {
  397. render.Error(w, r, errs.InternalServerErr(err))
  398. return
  399. }
  400. w.Header().Set("Content-Type", "application/x-pem-file")
  401. for _, root := range roots {
  402. block := pem.EncodeToMemory(&pem.Block{
  403. Type: "CERTIFICATE",
  404. Bytes: root.Raw,
  405. })
  406. if _, err := w.Write(block); err != nil {
  407. log.Error(w, r, err)
  408. return
  409. }
  410. }
  411. }
  412. // Intermediates returns all the intermediate certificates of the CA.
  413. func Intermediates(w http.ResponseWriter, r *http.Request) {
  414. intermediates := mustAuthority(r.Context()).GetIntermediateCertificates()
  415. if len(intermediates) == 0 {
  416. render.Error(w, r, errs.NotImplemented("error getting intermediates: method not implemented"))
  417. return
  418. }
  419. certs := make([]Certificate, len(intermediates))
  420. for i := range intermediates {
  421. certs[i] = Certificate{intermediates[i]}
  422. }
  423. render.JSONStatus(w, r, &IntermediatesResponse{
  424. Certificates: certs,
  425. }, http.StatusCreated)
  426. }
  427. // IntermediatesPEM returns all the intermediate certificates for the CA in PEM format.
  428. func IntermediatesPEM(w http.ResponseWriter, r *http.Request) {
  429. intermediates := mustAuthority(r.Context()).GetIntermediateCertificates()
  430. if len(intermediates) == 0 {
  431. render.Error(w, r, errs.NotImplemented("error getting intermediates: method not implemented"))
  432. return
  433. }
  434. w.Header().Set("Content-Type", "application/x-pem-file")
  435. for _, crt := range intermediates {
  436. block := pem.EncodeToMemory(&pem.Block{
  437. Type: "CERTIFICATE",
  438. Bytes: crt.Raw,
  439. })
  440. if _, err := w.Write(block); err != nil {
  441. log.Error(w, r, err)
  442. return
  443. }
  444. }
  445. }
  446. // Federation returns all the public certificates in the federation.
  447. func Federation(w http.ResponseWriter, r *http.Request) {
  448. federated, err := mustAuthority(r.Context()).GetFederation()
  449. if err != nil {
  450. render.Error(w, r, errs.ForbiddenErr(err, "error getting federated roots"))
  451. return
  452. }
  453. certs := make([]Certificate, len(federated))
  454. for i := range federated {
  455. certs[i] = Certificate{federated[i]}
  456. }
  457. render.JSONStatus(w, r, &FederationResponse{
  458. Certificates: certs,
  459. }, http.StatusCreated)
  460. }
  461. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  462. type stepProvisioner struct {
  463. Type int
  464. Name []byte
  465. CredentialID []byte
  466. }
  467. func logOtt(w http.ResponseWriter, token string) {
  468. if rl, ok := w.(logging.ResponseLogger); ok {
  469. rl.WithFields(map[string]any{
  470. "ott": token,
  471. })
  472. }
  473. }
  474. // LogCertificate adds certificate fields to the log message.
  475. func LogCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  476. if rl, ok := w.(logging.ResponseLogger); ok {
  477. m := map[string]any{
  478. "serial": cert.SerialNumber.String(),
  479. "subject": cert.Subject.CommonName,
  480. "issuer": cert.Issuer.CommonName,
  481. "sans": fmtSans(cert),
  482. "valid-from": cert.NotBefore.Format(time.RFC3339),
  483. "valid-to": cert.NotAfter.Format(time.RFC3339),
  484. "public-key": fmtPublicKey(cert),
  485. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  486. }
  487. for _, ext := range cert.Extensions {
  488. if !ext.Id.Equal(oidStepProvisioner) {
  489. continue
  490. }
  491. val := &stepProvisioner{}
  492. rest, err := asn1.Unmarshal(ext.Value, val)
  493. if err != nil || len(rest) > 0 {
  494. break
  495. }
  496. if len(val.CredentialID) > 0 {
  497. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  498. } else {
  499. m["provisioner"] = string(val.Name)
  500. }
  501. break
  502. }
  503. rl.WithFields(m)
  504. }
  505. }
  506. // LogSSHCertificate adds SSH certificate fields to the log message.
  507. func LogSSHCertificate(w http.ResponseWriter, cert *ssh.Certificate) {
  508. if rl, ok := w.(logging.ResponseLogger); ok {
  509. mak := bytes.TrimSpace(ssh.MarshalAuthorizedKey(cert))
  510. var certificate string
  511. parts := strings.Split(string(mak), " ")
  512. if len(parts) > 1 {
  513. certificate = parts[1]
  514. }
  515. var userOrHost string
  516. if cert.CertType == ssh.HostCert {
  517. userOrHost = "host"
  518. } else {
  519. userOrHost = "user"
  520. }
  521. certificateType := fmt.Sprintf("%s %s certificate", parts[0], userOrHost) // e.g. ecdsa-sha2-nistp256-cert-v01@openssh.com user certificate
  522. m := map[string]any{
  523. "serial": cert.Serial,
  524. "principals": cert.ValidPrincipals,
  525. "valid-from": time.Unix(cast.Int64(cert.ValidAfter), 0).Format(time.RFC3339),
  526. "valid-to": time.Unix(cast.Int64(cert.ValidBefore), 0).Format(time.RFC3339),
  527. "certificate": certificate,
  528. "certificate-type": certificateType,
  529. }
  530. fingerprint, err := sshutil.FormatFingerprint(mak, sshutil.DefaultFingerprint)
  531. if err == nil {
  532. fpParts := strings.Split(fingerprint, " ")
  533. if len(fpParts) > 3 {
  534. m["public-key"] = fmt.Sprintf("%s %s", fpParts[1], fpParts[len(fpParts)-1])
  535. }
  536. }
  537. rl.WithFields(m)
  538. }
  539. }
  540. // ParseCursor parses the cursor and limit from the request query params.
  541. func ParseCursor(r *http.Request) (cursor string, limit int, err error) {
  542. q := r.URL.Query()
  543. cursor = q.Get("cursor")
  544. if v := q.Get("limit"); v != "" {
  545. limit, err = strconv.Atoi(v)
  546. if err != nil {
  547. return "", 0, errs.BadRequestErr(err, "limit '%s' is not an integer", v)
  548. }
  549. }
  550. return
  551. }
  552. func fmtSans(cert *x509.Certificate) map[string][]string {
  553. sans := make(map[string][]string)
  554. if len(cert.DNSNames) > 0 {
  555. sans["dns"] = cert.DNSNames
  556. }
  557. if len(cert.EmailAddresses) > 0 {
  558. sans["email"] = cert.EmailAddresses
  559. }
  560. if size := len(cert.IPAddresses); size > 0 {
  561. ips := make([]string, size)
  562. for i, ip := range cert.IPAddresses {
  563. ips[i] = ip.String()
  564. }
  565. sans["ip"] = ips
  566. }
  567. if size := len(cert.URIs); size > 0 {
  568. uris := make([]string, size)
  569. for i, u := range cert.URIs {
  570. uris[i] = u.String()
  571. }
  572. sans["uri"] = uris
  573. }
  574. return sans
  575. }
  576. func fmtPublicKey(cert *x509.Certificate) string {
  577. var params string
  578. switch pk := cert.PublicKey.(type) {
  579. case *ecdsa.PublicKey:
  580. params = pk.Curve.Params().Name
  581. case *rsa.PublicKey:
  582. params = strconv.Itoa(pk.Size() * 8)
  583. case ed25519.PublicKey:
  584. return cert.PublicKeyAlgorithm.String()
  585. case *mldsa.PublicKey:
  586. return pk.Parameters().String()
  587. case *dsa.PublicKey:
  588. params = strconv.Itoa(pk.Q.BitLen() * 8)
  589. default:
  590. params = "unknown"
  591. }
  592. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  593. }