order.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. package api
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "net"
  9. "net/http"
  10. "strings"
  11. "time"
  12. "github.com/go-chi/chi"
  13. "go.step.sm/crypto/randutil"
  14. "github.com/smallstep/certificates/acme"
  15. "github.com/smallstep/certificates/api/render"
  16. "github.com/smallstep/certificates/authority/provisioner"
  17. )
  18. // NewOrderRequest represents the body for a NewOrder request.
  19. type NewOrderRequest struct {
  20. Identifiers []acme.Identifier `json:"identifiers"`
  21. NotBefore time.Time `json:"notBefore,omitempty"`
  22. NotAfter time.Time `json:"notAfter,omitempty"`
  23. }
  24. // Validate validates a new-order request body.
  25. func (n *NewOrderRequest) Validate() error {
  26. if len(n.Identifiers) == 0 {
  27. return acme.NewError(acme.ErrorMalformedType, "identifiers list cannot be empty")
  28. }
  29. for _, id := range n.Identifiers {
  30. if !(id.Type == acme.DNS || id.Type == acme.IP) {
  31. return acme.NewError(acme.ErrorMalformedType, "identifier type unsupported: %s", id.Type)
  32. }
  33. if id.Type == acme.IP && net.ParseIP(id.Value) == nil {
  34. return acme.NewError(acme.ErrorMalformedType, "invalid IP address: %s", id.Value)
  35. }
  36. // TODO(hs): add some validations for DNS domains?
  37. // TODO(hs): combine the errors from this with allow/deny policy, like example error in https://datatracker.ietf.org/doc/html/rfc8555#section-6.7.1
  38. }
  39. return nil
  40. }
  41. // FinalizeRequest captures the body for a Finalize order request.
  42. type FinalizeRequest struct {
  43. CSR string `json:"csr"`
  44. csr *x509.CertificateRequest
  45. }
  46. // Validate validates a finalize request body.
  47. func (f *FinalizeRequest) Validate() error {
  48. var err error
  49. csrBytes, err := base64.RawURLEncoding.DecodeString(f.CSR)
  50. if err != nil {
  51. return acme.WrapError(acme.ErrorMalformedType, err, "error base64url decoding csr")
  52. }
  53. f.csr, err = x509.ParseCertificateRequest(csrBytes)
  54. if err != nil {
  55. return acme.WrapError(acme.ErrorMalformedType, err, "unable to parse csr")
  56. }
  57. if err = f.csr.CheckSignature(); err != nil {
  58. return acme.WrapError(acme.ErrorMalformedType, err, "csr failed signature check")
  59. }
  60. return nil
  61. }
  62. var defaultOrderExpiry = time.Hour * 24
  63. var defaultOrderBackdate = time.Minute
  64. // NewOrder ACME api for creating a new order.
  65. func (h *Handler) NewOrder(w http.ResponseWriter, r *http.Request) {
  66. ctx := r.Context()
  67. acc, err := accountFromContext(ctx)
  68. if err != nil {
  69. render.Error(w, err)
  70. return
  71. }
  72. prov, err := provisionerFromContext(ctx)
  73. if err != nil {
  74. render.Error(w, err)
  75. return
  76. }
  77. payload, err := payloadFromContext(ctx)
  78. if err != nil {
  79. render.Error(w, err)
  80. return
  81. }
  82. var nor NewOrderRequest
  83. if err := json.Unmarshal(payload.value, &nor); err != nil {
  84. render.Error(w, acme.WrapError(acme.ErrorMalformedType, err,
  85. "failed to unmarshal new-order request payload"))
  86. return
  87. }
  88. if err := nor.Validate(); err != nil {
  89. render.Error(w, err)
  90. return
  91. }
  92. // TODO(hs): the policy evaluation below should also verify rules set in the Account (i.e. allowed/denied
  93. // DNS and IPs). It's probably good to connect those to the EAB credentials and management? Or
  94. // should we do it fully properly and connect them to the Account directly? The latter would allow
  95. // management of allowed/denied names based on just the name, without having bound to EAB. Still,
  96. // EAB is not illogical, because that's the way Accounts are connected to an external system and
  97. // thus make sense to also set the allowed/denied names based on that info.
  98. // TODO(hs): gather all errors, so that we can build one response with subproblems; include the nor.Validate()
  99. // error here too, like in example?
  100. eak, err := h.db.GetExternalAccountKeyByAccountID(ctx, prov.GetID(), acc.ID)
  101. fmt.Println("EAK: ", eak, err)
  102. for _, identifier := range nor.Identifiers {
  103. // evaluate the provisioner level policy
  104. orderIdentifier := provisioner.ACMEIdentifier{Type: provisioner.ACMEIdentifierType(identifier.Type), Value: identifier.Value}
  105. err = prov.AuthorizeOrderIdentifier(ctx, orderIdentifier)
  106. if err != nil {
  107. render.Error(w, acme.WrapError(acme.ErrorRejectedIdentifierType, err, "not authorized"))
  108. return
  109. }
  110. // evaluate the authority level policy
  111. err = h.ca.AreSANsAllowed(ctx, []string{identifier.Value})
  112. if err != nil {
  113. render.Error(w, acme.WrapError(acme.ErrorRejectedIdentifierType, err, "not authorized"))
  114. return
  115. }
  116. }
  117. now := clock.Now()
  118. // New order.
  119. o := &acme.Order{
  120. AccountID: acc.ID,
  121. ProvisionerID: prov.GetID(),
  122. Status: acme.StatusPending,
  123. Identifiers: nor.Identifiers,
  124. ExpiresAt: now.Add(defaultOrderExpiry),
  125. AuthorizationIDs: make([]string, len(nor.Identifiers)),
  126. NotBefore: nor.NotBefore,
  127. NotAfter: nor.NotAfter,
  128. }
  129. for i, identifier := range o.Identifiers {
  130. az := &acme.Authorization{
  131. AccountID: acc.ID,
  132. Identifier: identifier,
  133. ExpiresAt: o.ExpiresAt,
  134. Status: acme.StatusPending,
  135. }
  136. if err := h.newAuthorization(ctx, az); err != nil {
  137. render.Error(w, err)
  138. return
  139. }
  140. o.AuthorizationIDs[i] = az.ID
  141. }
  142. if o.NotBefore.IsZero() {
  143. o.NotBefore = now
  144. }
  145. if o.NotAfter.IsZero() {
  146. o.NotAfter = o.NotBefore.Add(prov.DefaultTLSCertDuration())
  147. }
  148. // If request NotBefore was empty then backdate the order.NotBefore (now)
  149. // to avoid timing issues.
  150. if nor.NotBefore.IsZero() {
  151. o.NotBefore = o.NotBefore.Add(-defaultOrderBackdate)
  152. }
  153. if err := h.db.CreateOrder(ctx, o); err != nil {
  154. render.Error(w, acme.WrapErrorISE(err, "error creating order"))
  155. return
  156. }
  157. h.linker.LinkOrder(ctx, o)
  158. w.Header().Set("Location", h.linker.GetLink(ctx, OrderLinkType, o.ID))
  159. render.JSONStatus(w, o, http.StatusCreated)
  160. }
  161. func (h *Handler) newAuthorization(ctx context.Context, az *acme.Authorization) error {
  162. if strings.HasPrefix(az.Identifier.Value, "*.") {
  163. az.Wildcard = true
  164. az.Identifier = acme.Identifier{
  165. Value: strings.TrimPrefix(az.Identifier.Value, "*."),
  166. Type: az.Identifier.Type,
  167. }
  168. }
  169. chTypes := challengeTypes(az)
  170. var err error
  171. az.Token, err = randutil.Alphanumeric(32)
  172. if err != nil {
  173. return acme.WrapErrorISE(err, "error generating random alphanumeric ID")
  174. }
  175. az.Challenges = make([]*acme.Challenge, len(chTypes))
  176. for i, typ := range chTypes {
  177. ch := &acme.Challenge{
  178. AccountID: az.AccountID,
  179. Value: az.Identifier.Value,
  180. Type: typ,
  181. Token: az.Token,
  182. Status: acme.StatusPending,
  183. }
  184. if err := h.db.CreateChallenge(ctx, ch); err != nil {
  185. return acme.WrapErrorISE(err, "error creating challenge")
  186. }
  187. az.Challenges[i] = ch
  188. }
  189. if err = h.db.CreateAuthorization(ctx, az); err != nil {
  190. return acme.WrapErrorISE(err, "error creating authorization")
  191. }
  192. return nil
  193. }
  194. // GetOrder ACME api for retrieving an order.
  195. func (h *Handler) GetOrder(w http.ResponseWriter, r *http.Request) {
  196. ctx := r.Context()
  197. acc, err := accountFromContext(ctx)
  198. if err != nil {
  199. render.Error(w, err)
  200. return
  201. }
  202. prov, err := provisionerFromContext(ctx)
  203. if err != nil {
  204. render.Error(w, err)
  205. return
  206. }
  207. o, err := h.db.GetOrder(ctx, chi.URLParam(r, "ordID"))
  208. if err != nil {
  209. render.Error(w, acme.WrapErrorISE(err, "error retrieving order"))
  210. return
  211. }
  212. if acc.ID != o.AccountID {
  213. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
  214. "account '%s' does not own order '%s'", acc.ID, o.ID))
  215. return
  216. }
  217. if prov.GetID() != o.ProvisionerID {
  218. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
  219. "provisioner '%s' does not own order '%s'", prov.GetID(), o.ID))
  220. return
  221. }
  222. if err = o.UpdateStatus(ctx, h.db); err != nil {
  223. render.Error(w, acme.WrapErrorISE(err, "error updating order status"))
  224. return
  225. }
  226. h.linker.LinkOrder(ctx, o)
  227. w.Header().Set("Location", h.linker.GetLink(ctx, OrderLinkType, o.ID))
  228. render.JSON(w, o)
  229. }
  230. // FinalizeOrder attemptst to finalize an order and create a certificate.
  231. func (h *Handler) FinalizeOrder(w http.ResponseWriter, r *http.Request) {
  232. ctx := r.Context()
  233. acc, err := accountFromContext(ctx)
  234. if err != nil {
  235. render.Error(w, err)
  236. return
  237. }
  238. prov, err := provisionerFromContext(ctx)
  239. if err != nil {
  240. render.Error(w, err)
  241. return
  242. }
  243. payload, err := payloadFromContext(ctx)
  244. if err != nil {
  245. render.Error(w, err)
  246. return
  247. }
  248. var fr FinalizeRequest
  249. if err := json.Unmarshal(payload.value, &fr); err != nil {
  250. render.Error(w, acme.WrapError(acme.ErrorMalformedType, err,
  251. "failed to unmarshal finalize-order request payload"))
  252. return
  253. }
  254. if err := fr.Validate(); err != nil {
  255. render.Error(w, err)
  256. return
  257. }
  258. o, err := h.db.GetOrder(ctx, chi.URLParam(r, "ordID"))
  259. if err != nil {
  260. render.Error(w, acme.WrapErrorISE(err, "error retrieving order"))
  261. return
  262. }
  263. if acc.ID != o.AccountID {
  264. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
  265. "account '%s' does not own order '%s'", acc.ID, o.ID))
  266. return
  267. }
  268. if prov.GetID() != o.ProvisionerID {
  269. render.Error(w, acme.NewError(acme.ErrorUnauthorizedType,
  270. "provisioner '%s' does not own order '%s'", prov.GetID(), o.ID))
  271. return
  272. }
  273. if err = o.Finalize(ctx, h.db, fr.csr, h.ca, prov); err != nil {
  274. render.Error(w, acme.WrapErrorISE(err, "error finalizing order"))
  275. return
  276. }
  277. h.linker.LinkOrder(ctx, o)
  278. w.Header().Set("Location", h.linker.GetLink(ctx, OrderLinkType, o.ID))
  279. render.JSON(w, o)
  280. }
  281. // challengeTypes determines the types of challenges that should be used
  282. // for the ACME authorization request.
  283. func challengeTypes(az *acme.Authorization) []acme.ChallengeType {
  284. var chTypes []acme.ChallengeType
  285. switch az.Identifier.Type {
  286. case acme.IP:
  287. chTypes = []acme.ChallengeType{acme.HTTP01, acme.TLSALPN01}
  288. case acme.DNS:
  289. chTypes = []acme.ChallengeType{acme.DNS01}
  290. // HTTP and TLS challenges can only be used for identifiers without wildcards.
  291. if !az.Wildcard {
  292. chTypes = append(chTypes, []acme.ChallengeType{acme.HTTP01, acme.TLSALPN01}...)
  293. }
  294. default:
  295. chTypes = []acme.ChallengeType{}
  296. }
  297. return chTypes
  298. }