4
0

api.go 20 KB

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