initca.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Package initca implements the HTTP handler for the CA initialization command
  2. package initca
  3. import (
  4. "encoding/json"
  5. "io/ioutil"
  6. "net/http"
  7. "github.com/cloudflare/cfssl/api"
  8. "github.com/cloudflare/cfssl/csr"
  9. "github.com/cloudflare/cfssl/errors"
  10. "github.com/cloudflare/cfssl/initca"
  11. "github.com/cloudflare/cfssl/log"
  12. )
  13. // A NewCA contains a private key and certificate suitable for serving
  14. // as the root key for a new certificate authority.
  15. type NewCA struct {
  16. Key string `json:"private_key"`
  17. Cert string `json:"certificate"`
  18. }
  19. // initialCAHandler is an HTTP handler that accepts a JSON blob in the
  20. // same format as the CSR endpoint; this blob should contain the
  21. // identity information for the CA's root key. This endpoint is not
  22. // suitable for creating intermediate certificates.
  23. func initialCAHandler(w http.ResponseWriter, r *http.Request) error {
  24. log.Info("setting up initial CA handler")
  25. body, err := ioutil.ReadAll(r.Body)
  26. if err != nil {
  27. log.Warningf("failed to read request body: %v", err)
  28. return errors.NewBadRequest(err)
  29. }
  30. r.Body.Close()
  31. req := new(csr.CertificateRequest)
  32. req.KeyRequest = csr.NewBasicKeyRequest()
  33. err = json.Unmarshal(body, req)
  34. if err != nil {
  35. log.Warningf("failed to unmarshal request: %v", err)
  36. return errors.NewBadRequest(err)
  37. }
  38. cert, _, key, err := initca.New(req)
  39. if err != nil {
  40. log.Warningf("failed to initialise new CA: %v", err)
  41. return err
  42. }
  43. response := api.NewSuccessResponse(&NewCA{string(key), string(cert)})
  44. enc := json.NewEncoder(w)
  45. err = enc.Encode(response)
  46. return err
  47. }
  48. // NewHandler returns a new http.Handler that handles request to
  49. // initialize a CA.
  50. func NewHandler() http.Handler {
  51. return api.HTTPHandler{Handler: api.HandlerFunc(initialCAHandler), Methods: []string{"POST"}}
  52. }