order.go 9.4 KB

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