api.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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. func estFromProvisioner(p *provisioner.EST) *provisioner.EST {
  230. prov := *p
  231. // prov.ClientCertificateRoots = []byte(redacted)
  232. // prov.BasicAuthUsername = redacted
  233. // prov.BasicAuthPassword = redacted
  234. return &prov
  235. }
  236. // MarshalJSON implements json.Marshaler. It marshals the ProvisionersResponse
  237. // into a byte slice.
  238. //
  239. // Special treatment is given to the SCEP provisioner, as it contains a
  240. // challenge secret that MUST NOT be leaked in (public) HTTP responses. The
  241. // challenge value is thus redacted in HTTP responses. EST provisioners also
  242. // contain a shared secret and are redacted in responses.
  243. func (p ProvisionersResponse) MarshalJSON() ([]byte, error) {
  244. var responseProvisioners provisioner.List
  245. for _, item := range p.Provisioners {
  246. switch prov := item.(type) {
  247. case *provisioner.SCEP:
  248. responseProvisioners = append(responseProvisioners, scepFromProvisioner(prov))
  249. case *provisioner.EST:
  250. responseProvisioners = append(responseProvisioners, estFromProvisioner(prov))
  251. default:
  252. responseProvisioners = append(responseProvisioners, item)
  253. }
  254. }
  255. var list = struct {
  256. Provisioners []provisioner.Interface `json:"provisioners"`
  257. NextCursor string `json:"nextCursor"`
  258. }{
  259. Provisioners: []provisioner.Interface(responseProvisioners),
  260. NextCursor: p.NextCursor,
  261. }
  262. return json.Marshal(list)
  263. }
  264. // ProvisionerKeyResponse is the response object that returns the encrypted key
  265. // of a provisioner.
  266. type ProvisionerKeyResponse struct {
  267. Key string `json:"key"`
  268. }
  269. // RootsResponse is the response object of the roots request.
  270. type RootsResponse struct {
  271. Certificates []Certificate `json:"crts"`
  272. }
  273. // IntermediatesResponse is the response object of the intermediates request.
  274. type IntermediatesResponse struct {
  275. Certificates []Certificate `json:"crts"`
  276. }
  277. // FederationResponse is the response object of the federation request.
  278. type FederationResponse struct {
  279. Certificates []Certificate `json:"crts"`
  280. }
  281. // caHandler is the type used to implement the different CA HTTP endpoints.
  282. type caHandler struct {
  283. Authority Authority
  284. }
  285. // Route configures the http request router.
  286. func (h *caHandler) Route(r Router) {
  287. Route(r)
  288. }
  289. // New creates a new RouterHandler with the CA endpoints.
  290. //
  291. // Deprecated: Use api.Route(r Router)
  292. func New(Authority) RouterHandler {
  293. return &caHandler{}
  294. }
  295. func Route(r Router) {
  296. r.MethodFunc("GET", "/version", Version)
  297. r.MethodFunc("GET", "/health", Health)
  298. r.MethodFunc("GET", "/root/{sha}", Root)
  299. r.MethodFunc("POST", "/sign", Sign)
  300. r.MethodFunc("POST", "/renew", Renew)
  301. r.MethodFunc("POST", "/rekey", Rekey)
  302. r.MethodFunc("POST", "/revoke", Revoke)
  303. r.MethodFunc("GET", "/crl", CRL)
  304. r.MethodFunc("GET", "/provisioners", Provisioners)
  305. r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", ProvisionerKey)
  306. r.MethodFunc("GET", "/roots", Roots)
  307. r.MethodFunc("GET", "/roots.pem", RootsPEM)
  308. r.MethodFunc("GET", "/intermediates", Intermediates)
  309. r.MethodFunc("GET", "/intermediates.pem", IntermediatesPEM)
  310. r.MethodFunc("GET", "/federation", Federation)
  311. // SSH CA
  312. r.MethodFunc("POST", "/ssh/sign", SSHSign)
  313. r.MethodFunc("POST", "/ssh/renew", SSHRenew)
  314. r.MethodFunc("POST", "/ssh/revoke", SSHRevoke)
  315. r.MethodFunc("POST", "/ssh/rekey", SSHRekey)
  316. r.MethodFunc("GET", "/ssh/roots", SSHRoots)
  317. r.MethodFunc("GET", "/ssh/federation", SSHFederation)
  318. r.MethodFunc("POST", "/ssh/config", SSHConfig)
  319. r.MethodFunc("POST", "/ssh/config/{type}", SSHConfig)
  320. r.MethodFunc("POST", "/ssh/check-host", SSHCheckHost)
  321. r.MethodFunc("GET", "/ssh/hosts", SSHGetHosts)
  322. r.MethodFunc("POST", "/ssh/bastion", SSHBastion)
  323. // For compatibility with old code:
  324. r.MethodFunc("POST", "/re-sign", Renew)
  325. r.MethodFunc("POST", "/sign-ssh", SSHSign)
  326. r.MethodFunc("GET", "/ssh/get-hosts", SSHGetHosts)
  327. }
  328. // Version is an HTTP handler that returns the version of the server.
  329. func Version(w http.ResponseWriter, r *http.Request) {
  330. v := mustAuthority(r.Context()).Version()
  331. render.JSON(w, r, VersionResponse{
  332. Version: v.Version,
  333. RequireClientAuthentication: v.RequireClientAuthentication,
  334. })
  335. }
  336. // Health is an HTTP handler that returns the status of the server.
  337. func Health(w http.ResponseWriter, r *http.Request) {
  338. render.JSON(w, r, HealthResponse{Status: "ok"})
  339. }
  340. // Root is an HTTP handler that using the SHA256 from the URL, returns the root
  341. // certificate for the given SHA256.
  342. func Root(w http.ResponseWriter, r *http.Request) {
  343. sha := chi.URLParam(r, "sha")
  344. sum := strings.ToLower(strings.ReplaceAll(sha, "-", ""))
  345. // Load root certificate with the
  346. cert, err := mustAuthority(r.Context()).Root(sum)
  347. if err != nil {
  348. render.Error(w, r, errs.NotFoundErr(err, errs.WithMessage("root certificate with fingerprint %q was not found", sum)))
  349. return
  350. }
  351. render.JSON(w, r, &RootResponse{RootPEM: Certificate{cert}})
  352. }
  353. func certChainToPEM(certChain []*x509.Certificate) []Certificate {
  354. certChainPEM := make([]Certificate, 0, len(certChain))
  355. for _, c := range certChain {
  356. certChainPEM = append(certChainPEM, Certificate{c})
  357. }
  358. return certChainPEM
  359. }
  360. // Provisioners returns the list of provisioners configured in the authority.
  361. func Provisioners(w http.ResponseWriter, r *http.Request) {
  362. cursor, limit, err := ParseCursor(r)
  363. if err != nil {
  364. render.Error(w, r, err)
  365. return
  366. }
  367. p, next, err := mustAuthority(r.Context()).GetProvisioners(cursor, limit)
  368. if err != nil {
  369. render.Error(w, r, errs.InternalServerErr(err))
  370. return
  371. }
  372. render.JSON(w, r, &ProvisionersResponse{
  373. Provisioners: p,
  374. NextCursor: next,
  375. })
  376. }
  377. // ProvisionerKey returns the encrypted key of a provisioner by it's key id.
  378. func ProvisionerKey(w http.ResponseWriter, r *http.Request) {
  379. kid := chi.URLParam(r, "kid")
  380. key, err := mustAuthority(r.Context()).GetEncryptedKey(kid)
  381. if err != nil {
  382. render.Error(w, r, errs.NotFoundErr(err))
  383. return
  384. }
  385. render.JSON(w, r, &ProvisionerKeyResponse{key})
  386. }
  387. // Roots returns all the root certificates for the CA.
  388. func Roots(w http.ResponseWriter, r *http.Request) {
  389. roots, err := mustAuthority(r.Context()).GetRoots()
  390. if err != nil {
  391. render.Error(w, r, errs.ForbiddenErr(err, "error getting roots"))
  392. return
  393. }
  394. certs := make([]Certificate, len(roots))
  395. for i := range roots {
  396. certs[i] = Certificate{roots[i]}
  397. }
  398. render.JSONStatus(w, r, &RootsResponse{
  399. Certificates: certs,
  400. }, http.StatusCreated)
  401. }
  402. // RootsPEM returns all the root certificates for the CA in PEM format.
  403. func RootsPEM(w http.ResponseWriter, r *http.Request) {
  404. roots, err := mustAuthority(r.Context()).GetRoots()
  405. if err != nil {
  406. render.Error(w, r, errs.InternalServerErr(err))
  407. return
  408. }
  409. w.Header().Set("Content-Type", "application/x-pem-file")
  410. for _, root := range roots {
  411. block := pem.EncodeToMemory(&pem.Block{
  412. Type: "CERTIFICATE",
  413. Bytes: root.Raw,
  414. })
  415. if _, err := w.Write(block); err != nil {
  416. log.Error(w, r, err)
  417. return
  418. }
  419. }
  420. }
  421. // Intermediates returns all the intermediate certificates of the CA.
  422. func Intermediates(w http.ResponseWriter, r *http.Request) {
  423. intermediates := mustAuthority(r.Context()).GetIntermediateCertificates()
  424. if len(intermediates) == 0 {
  425. render.Error(w, r, errs.NotImplemented("error getting intermediates: method not implemented"))
  426. return
  427. }
  428. certs := make([]Certificate, len(intermediates))
  429. for i := range intermediates {
  430. certs[i] = Certificate{intermediates[i]}
  431. }
  432. render.JSONStatus(w, r, &IntermediatesResponse{
  433. Certificates: certs,
  434. }, http.StatusCreated)
  435. }
  436. // IntermediatesPEM returns all the intermediate certificates for the CA in PEM format.
  437. func IntermediatesPEM(w http.ResponseWriter, r *http.Request) {
  438. intermediates := mustAuthority(r.Context()).GetIntermediateCertificates()
  439. if len(intermediates) == 0 {
  440. render.Error(w, r, errs.NotImplemented("error getting intermediates: method not implemented"))
  441. return
  442. }
  443. w.Header().Set("Content-Type", "application/x-pem-file")
  444. for _, crt := range intermediates {
  445. block := pem.EncodeToMemory(&pem.Block{
  446. Type: "CERTIFICATE",
  447. Bytes: crt.Raw,
  448. })
  449. if _, err := w.Write(block); err != nil {
  450. log.Error(w, r, err)
  451. return
  452. }
  453. }
  454. }
  455. // Federation returns all the public certificates in the federation.
  456. func Federation(w http.ResponseWriter, r *http.Request) {
  457. federated, err := mustAuthority(r.Context()).GetFederation()
  458. if err != nil {
  459. render.Error(w, r, errs.ForbiddenErr(err, "error getting federated roots"))
  460. return
  461. }
  462. certs := make([]Certificate, len(federated))
  463. for i := range federated {
  464. certs[i] = Certificate{federated[i]}
  465. }
  466. render.JSONStatus(w, r, &FederationResponse{
  467. Certificates: certs,
  468. }, http.StatusCreated)
  469. }
  470. var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
  471. type stepProvisioner struct {
  472. Type int
  473. Name []byte
  474. CredentialID []byte
  475. }
  476. func logOtt(w http.ResponseWriter, token string) {
  477. if rl, ok := w.(logging.ResponseLogger); ok {
  478. rl.WithFields(map[string]interface{}{
  479. "ott": token,
  480. })
  481. }
  482. }
  483. // LogCertificate adds certificate fields to the log message.
  484. func LogCertificate(w http.ResponseWriter, cert *x509.Certificate) {
  485. if rl, ok := w.(logging.ResponseLogger); ok {
  486. m := map[string]interface{}{
  487. "serial": cert.SerialNumber.String(),
  488. "subject": cert.Subject.CommonName,
  489. "issuer": cert.Issuer.CommonName,
  490. "sans": fmtSans(cert),
  491. "valid-from": cert.NotBefore.Format(time.RFC3339),
  492. "valid-to": cert.NotAfter.Format(time.RFC3339),
  493. "public-key": fmtPublicKey(cert),
  494. "certificate": base64.StdEncoding.EncodeToString(cert.Raw),
  495. }
  496. for _, ext := range cert.Extensions {
  497. if !ext.Id.Equal(oidStepProvisioner) {
  498. continue
  499. }
  500. val := &stepProvisioner{}
  501. rest, err := asn1.Unmarshal(ext.Value, val)
  502. if err != nil || len(rest) > 0 {
  503. break
  504. }
  505. if len(val.CredentialID) > 0 {
  506. m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
  507. } else {
  508. m["provisioner"] = string(val.Name)
  509. }
  510. break
  511. }
  512. rl.WithFields(m)
  513. }
  514. }
  515. // LogSSHCertificate adds SSH certificate fields to the log message.
  516. func LogSSHCertificate(w http.ResponseWriter, cert *ssh.Certificate) {
  517. if rl, ok := w.(logging.ResponseLogger); ok {
  518. mak := bytes.TrimSpace(ssh.MarshalAuthorizedKey(cert))
  519. var certificate string
  520. parts := strings.Split(string(mak), " ")
  521. if len(parts) > 1 {
  522. certificate = parts[1]
  523. }
  524. var userOrHost string
  525. if cert.CertType == ssh.HostCert {
  526. userOrHost = "host"
  527. } else {
  528. userOrHost = "user"
  529. }
  530. certificateType := fmt.Sprintf("%s %s certificate", parts[0], userOrHost) // e.g. ecdsa-sha2-nistp256-cert-v01@openssh.com user certificate
  531. m := map[string]interface{}{
  532. "serial": cert.Serial,
  533. "principals": cert.ValidPrincipals,
  534. "valid-from": time.Unix(cast.Int64(cert.ValidAfter), 0).Format(time.RFC3339),
  535. "valid-to": time.Unix(cast.Int64(cert.ValidBefore), 0).Format(time.RFC3339),
  536. "certificate": certificate,
  537. "certificate-type": certificateType,
  538. }
  539. fingerprint, err := sshutil.FormatFingerprint(mak, sshutil.DefaultFingerprint)
  540. if err == nil {
  541. fpParts := strings.Split(fingerprint, " ")
  542. if len(fpParts) > 3 {
  543. m["public-key"] = fmt.Sprintf("%s %s", fpParts[1], fpParts[len(fpParts)-1])
  544. }
  545. }
  546. rl.WithFields(m)
  547. }
  548. }
  549. // ParseCursor parses the cursor and limit from the request query params.
  550. func ParseCursor(r *http.Request) (cursor string, limit int, err error) {
  551. q := r.URL.Query()
  552. cursor = q.Get("cursor")
  553. if v := q.Get("limit"); v != "" {
  554. limit, err = strconv.Atoi(v)
  555. if err != nil {
  556. return "", 0, errs.BadRequestErr(err, "limit '%s' is not an integer", v)
  557. }
  558. }
  559. return
  560. }
  561. func fmtSans(cert *x509.Certificate) map[string][]string {
  562. sans := make(map[string][]string)
  563. if len(cert.DNSNames) > 0 {
  564. sans["dns"] = cert.DNSNames
  565. }
  566. if len(cert.EmailAddresses) > 0 {
  567. sans["email"] = cert.EmailAddresses
  568. }
  569. if size := len(cert.IPAddresses); size > 0 {
  570. ips := make([]string, size)
  571. for i, ip := range cert.IPAddresses {
  572. ips[i] = ip.String()
  573. }
  574. sans["ip"] = ips
  575. }
  576. if size := len(cert.URIs); size > 0 {
  577. uris := make([]string, size)
  578. for i, u := range cert.URIs {
  579. uris[i] = u.String()
  580. }
  581. sans["uri"] = uris
  582. }
  583. return sans
  584. }
  585. func fmtPublicKey(cert *x509.Certificate) string {
  586. var params string
  587. switch pk := cert.PublicKey.(type) {
  588. case *ecdsa.PublicKey:
  589. params = pk.Curve.Params().Name
  590. case *rsa.PublicKey:
  591. params = strconv.Itoa(pk.Size() * 8)
  592. case ed25519.PublicKey:
  593. return cert.PublicKeyAlgorithm.String()
  594. case *dsa.PublicKey:
  595. params = strconv.Itoa(pk.Q.BitLen() * 8)
  596. default:
  597. params = "unknown"
  598. }
  599. return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
  600. }