api.go 19 KB

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