order.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. package acme
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/json"
  6. "sort"
  7. "strings"
  8. "time"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/authority/provisioner"
  11. "github.com/smallstep/nosql"
  12. )
  13. var defaultOrderExpiry = time.Hour * 24
  14. // Order contains order metadata for the ACME protocol order type.
  15. type Order struct {
  16. Status string `json:"status"`
  17. Expires string `json:"expires,omitempty"`
  18. Identifiers []Identifier `json:"identifiers"`
  19. NotBefore string `json:"notBefore,omitempty"`
  20. NotAfter string `json:"notAfter,omitempty"`
  21. Error interface{} `json:"error,omitempty"`
  22. Authorizations []string `json:"authorizations"`
  23. Finalize string `json:"finalize"`
  24. Certificate string `json:"certificate,omitempty"`
  25. ID string `json:"-"`
  26. }
  27. // ToLog enables response logging.
  28. func (o *Order) ToLog() (interface{}, error) {
  29. b, err := json.Marshal(o)
  30. if err != nil {
  31. return nil, ServerInternalErr(errors.Wrap(err, "error marshaling order for logging"))
  32. }
  33. return string(b), nil
  34. }
  35. // GetID returns the Order ID.
  36. func (o *Order) GetID() string {
  37. return o.ID
  38. }
  39. // OrderOptions options with which to create a new Order.
  40. type OrderOptions struct {
  41. AccountID string `json:"accID"`
  42. Identifiers []Identifier `json:"identifiers"`
  43. NotBefore time.Time `json:"notBefore"`
  44. NotAfter time.Time `json:"notAfter"`
  45. backdate time.Duration
  46. defaultDuration time.Duration
  47. }
  48. type order struct {
  49. ID string `json:"id"`
  50. AccountID string `json:"accountID"`
  51. Created time.Time `json:"created"`
  52. Expires time.Time `json:"expires,omitempty"`
  53. Status string `json:"status"`
  54. Identifiers []Identifier `json:"identifiers"`
  55. NotBefore time.Time `json:"notBefore,omitempty"`
  56. NotAfter time.Time `json:"notAfter,omitempty"`
  57. Error *Error `json:"error,omitempty"`
  58. Authorizations []string `json:"authorizations"`
  59. Certificate string `json:"certificate,omitempty"`
  60. }
  61. // newOrder returns a new Order type.
  62. func newOrder(db nosql.DB, ops OrderOptions) (*order, error) {
  63. id, err := randID()
  64. if err != nil {
  65. return nil, err
  66. }
  67. authzs := make([]string, len(ops.Identifiers))
  68. for i, identifier := range ops.Identifiers {
  69. az, err := newAuthz(db, ops.AccountID, identifier)
  70. if err != nil {
  71. return nil, err
  72. }
  73. authzs[i] = az.getID()
  74. }
  75. now := clock.Now()
  76. var backdate time.Duration
  77. nbf := ops.NotBefore
  78. if nbf.IsZero() {
  79. nbf = now
  80. backdate = -1 * ops.backdate
  81. }
  82. naf := ops.NotAfter
  83. if naf.IsZero() {
  84. naf = nbf.Add(ops.defaultDuration)
  85. }
  86. o := &order{
  87. ID: id,
  88. AccountID: ops.AccountID,
  89. Created: now,
  90. Status: StatusPending,
  91. Expires: now.Add(defaultOrderExpiry),
  92. Identifiers: ops.Identifiers,
  93. NotBefore: nbf.Add(backdate),
  94. NotAfter: naf,
  95. Authorizations: authzs,
  96. }
  97. if err := o.save(db, nil); err != nil {
  98. return nil, err
  99. }
  100. // Update the "order IDs by account ID" index //
  101. oids, err := getOrderIDsByAccount(db, ops.AccountID)
  102. if err != nil {
  103. return nil, err
  104. }
  105. newOids := append(oids, o.ID)
  106. if err = orderIDs(newOids).save(db, oids, o.AccountID); err != nil {
  107. db.Del(orderTable, []byte(o.ID))
  108. return nil, err
  109. }
  110. return o, nil
  111. }
  112. type orderIDs []string
  113. // save is used to update the list of orderIDs keyed by ACME account ID
  114. // stored in the database.
  115. //
  116. // This method always converts empty lists to 'nil' when storing to the DB. We
  117. // do this to avoid any confusion between an empty list and a nil value in the
  118. // db.
  119. func (oids orderIDs) save(db nosql.DB, old orderIDs, accID string) error {
  120. var (
  121. err error
  122. oldb []byte
  123. newb []byte
  124. )
  125. if len(old) == 0 {
  126. oldb = nil
  127. } else {
  128. oldb, err = json.Marshal(old)
  129. if err != nil {
  130. return ServerInternalErr(errors.Wrap(err, "error marshaling old order IDs slice"))
  131. }
  132. }
  133. if len(oids) == 0 {
  134. newb = nil
  135. } else {
  136. newb, err = json.Marshal(oids)
  137. if err != nil {
  138. return ServerInternalErr(errors.Wrap(err, "error marshaling new order IDs slice"))
  139. }
  140. }
  141. _, swapped, err := db.CmpAndSwap(ordersByAccountIDTable, []byte(accID), oldb, newb)
  142. switch {
  143. case err != nil:
  144. return ServerInternalErr(errors.Wrapf(err, "error storing order IDs for account %s", accID))
  145. case !swapped:
  146. return ServerInternalErr(errors.Errorf("error storing order IDs "+
  147. "for account %s; order IDs changed since last read", accID))
  148. default:
  149. return nil
  150. }
  151. }
  152. func (o *order) save(db nosql.DB, old *order) error {
  153. var (
  154. err error
  155. oldB []byte
  156. )
  157. if old == nil {
  158. oldB = nil
  159. } else {
  160. if oldB, err = json.Marshal(old); err != nil {
  161. return ServerInternalErr(errors.Wrap(err, "error marshaling old acme order"))
  162. }
  163. }
  164. newB, err := json.Marshal(o)
  165. if err != nil {
  166. return ServerInternalErr(errors.Wrap(err, "error marshaling new acme order"))
  167. }
  168. _, swapped, err := db.CmpAndSwap(orderTable, []byte(o.ID), oldB, newB)
  169. switch {
  170. case err != nil:
  171. return ServerInternalErr(errors.Wrap(err, "error storing order"))
  172. case !swapped:
  173. return ServerInternalErr(errors.New("error storing order; " +
  174. "value has changed since last read"))
  175. default:
  176. return nil
  177. }
  178. }
  179. // updateStatus updates order status if necessary.
  180. func (o *order) updateStatus(db nosql.DB) (*order, error) {
  181. _newOrder := *o
  182. newOrder := &_newOrder
  183. now := time.Now().UTC()
  184. switch o.Status {
  185. case StatusInvalid:
  186. return o, nil
  187. case StatusValid:
  188. return o, nil
  189. case StatusReady:
  190. // check expiry
  191. if now.After(o.Expires) {
  192. newOrder.Status = StatusInvalid
  193. newOrder.Error = MalformedErr(errors.New("order has expired"))
  194. break
  195. }
  196. return o, nil
  197. case StatusPending:
  198. // check expiry
  199. if now.After(o.Expires) {
  200. newOrder.Status = StatusInvalid
  201. newOrder.Error = MalformedErr(errors.New("order has expired"))
  202. break
  203. }
  204. var count = map[string]int{
  205. StatusValid: 0,
  206. StatusInvalid: 0,
  207. StatusPending: 0,
  208. }
  209. for _, azID := range o.Authorizations {
  210. az, err := getAuthz(db, azID)
  211. if err != nil {
  212. return nil, err
  213. }
  214. if az, err = az.updateStatus(db); err != nil {
  215. return nil, err
  216. }
  217. st := az.getStatus()
  218. count[st]++
  219. }
  220. switch {
  221. case count[StatusInvalid] > 0:
  222. newOrder.Status = StatusInvalid
  223. // No change in the order status, so just return the order as is -
  224. // without writing any changes.
  225. case count[StatusPending] > 0:
  226. return newOrder, nil
  227. case count[StatusValid] == len(o.Authorizations):
  228. newOrder.Status = StatusReady
  229. default:
  230. return nil, ServerInternalErr(errors.New("unexpected authz status"))
  231. }
  232. default:
  233. return nil, ServerInternalErr(errors.Errorf("unrecognized order status: %s", o.Status))
  234. }
  235. if err := newOrder.save(db, o); err != nil {
  236. return nil, err
  237. }
  238. return newOrder, nil
  239. }
  240. // finalize signs a certificate if the necessary conditions for Order completion
  241. // have been met.
  242. func (o *order) finalize(db nosql.DB, csr *x509.CertificateRequest, auth SignAuthority, p Provisioner) (*order, error) {
  243. var err error
  244. if o, err = o.updateStatus(db); err != nil {
  245. return nil, err
  246. }
  247. switch o.Status {
  248. case StatusInvalid:
  249. return nil, OrderNotReadyErr(errors.Errorf("order %s has been abandoned", o.ID))
  250. case StatusValid:
  251. return o, nil
  252. case StatusPending:
  253. return nil, OrderNotReadyErr(errors.Errorf("order %s is not ready", o.ID))
  254. case StatusReady:
  255. break
  256. default:
  257. return nil, ServerInternalErr(errors.Errorf("unexpected status %s for order %s", o.Status, o.ID))
  258. }
  259. // RFC8555: The CSR MUST indicate the exact same set of requested
  260. // identifiers as the initial newOrder request. Identifiers of type "dns"
  261. // MUST appear either in the commonName portion of the requested subject
  262. // name or in an extensionRequest attribute [RFC2985] requesting a
  263. // subjectAltName extension, or both.
  264. if csr.Subject.CommonName != "" {
  265. csr.DNSNames = append(csr.DNSNames, csr.Subject.CommonName)
  266. }
  267. csr.DNSNames = uniqueLowerNames(csr.DNSNames)
  268. orderNames := make([]string, len(o.Identifiers))
  269. for i, n := range o.Identifiers {
  270. orderNames[i] = n.Value
  271. }
  272. orderNames = uniqueLowerNames(orderNames)
  273. // Validate identifier names against CSR alternative names.
  274. if len(csr.DNSNames) != len(orderNames) {
  275. return nil, BadCSRErr(errors.Errorf("CSR names do not match identifiers exactly: CSR names = %v, Order names = %v", csr.DNSNames, orderNames))
  276. }
  277. for i := range csr.DNSNames {
  278. if csr.DNSNames[i] != orderNames[i] {
  279. return nil, BadCSRErr(errors.Errorf("CSR names do not match identifiers exactly: CSR names = %v, Order names = %v", csr.DNSNames, orderNames))
  280. }
  281. }
  282. if len(csr.IPAddresses) > 0 {
  283. return nil, BadCSRErr(errors.Errorf("CSR contains IP Address SANs, but should only contain DNS Names"))
  284. }
  285. if len(csr.EmailAddresses) > 0 {
  286. return nil, BadCSRErr(errors.Errorf("CSR contains Email Address SANs, but should only contain DNS Names"))
  287. }
  288. if len(csr.URIs) > 0 {
  289. return nil, BadCSRErr(errors.Errorf("CSR contains URI SANs, but should only contain DNS Names"))
  290. }
  291. // Get authorizations from the ACME provisioner.
  292. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignMethod)
  293. signOps, err := p.AuthorizeSign(ctx, "")
  294. if err != nil {
  295. return nil, ServerInternalErr(errors.Wrapf(err, "error retrieving authorization options from ACME provisioner"))
  296. }
  297. // Create and store a new certificate.
  298. certChain, err := auth.Sign(csr, provisioner.Options{
  299. NotBefore: provisioner.NewTimeDuration(o.NotBefore),
  300. NotAfter: provisioner.NewTimeDuration(o.NotAfter),
  301. }, signOps...)
  302. if err != nil {
  303. return nil, ServerInternalErr(errors.Wrapf(err, "error generating certificate for order %s", o.ID))
  304. }
  305. cert, err := newCert(db, CertOptions{
  306. AccountID: o.AccountID,
  307. OrderID: o.ID,
  308. Leaf: certChain[0],
  309. Intermediates: certChain[1:],
  310. })
  311. if err != nil {
  312. return nil, err
  313. }
  314. _newOrder := *o
  315. newOrder := &_newOrder
  316. newOrder.Certificate = cert.ID
  317. newOrder.Status = StatusValid
  318. if err := newOrder.save(db, o); err != nil {
  319. return nil, err
  320. }
  321. return newOrder, nil
  322. }
  323. // getOrder retrieves and unmarshals an ACME Order type from the database.
  324. func getOrder(db nosql.DB, id string) (*order, error) {
  325. b, err := db.Get(orderTable, []byte(id))
  326. if nosql.IsErrNotFound(err) {
  327. return nil, MalformedErr(errors.Wrapf(err, "order %s not found", id))
  328. } else if err != nil {
  329. return nil, ServerInternalErr(errors.Wrapf(err, "error loading order %s", id))
  330. }
  331. var o order
  332. if err := json.Unmarshal(b, &o); err != nil {
  333. return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling order"))
  334. }
  335. return &o, nil
  336. }
  337. // toACME converts the internal Order type into the public acmeOrder type for
  338. // presentation in the ACME protocol.
  339. func (o *order) toACME(ctx context.Context, db nosql.DB, dir *directory) (*Order, error) {
  340. azs := make([]string, len(o.Authorizations))
  341. for i, aid := range o.Authorizations {
  342. azs[i] = dir.getLink(ctx, AuthzLink, true, aid)
  343. }
  344. ao := &Order{
  345. Status: o.Status,
  346. Expires: o.Expires.Format(time.RFC3339),
  347. Identifiers: o.Identifiers,
  348. NotBefore: o.NotBefore.Format(time.RFC3339),
  349. NotAfter: o.NotAfter.Format(time.RFC3339),
  350. Authorizations: azs,
  351. Finalize: dir.getLink(ctx, FinalizeLink, true, o.ID),
  352. ID: o.ID,
  353. }
  354. if o.Certificate != "" {
  355. ao.Certificate = dir.getLink(ctx, CertificateLink, true, o.Certificate)
  356. }
  357. return ao, nil
  358. }
  359. // uniqueLowerNames returns the set of all unique names in the input after all
  360. // of them are lowercased. The returned names will be in their lowercased form
  361. // and sorted alphabetically.
  362. func uniqueLowerNames(names []string) (unique []string) {
  363. nameMap := make(map[string]int, len(names))
  364. for _, name := range names {
  365. nameMap[strings.ToLower(name)] = 1
  366. }
  367. unique = make([]string, 0, len(nameMap))
  368. for name := range nameMap {
  369. unique = append(unique, name)
  370. }
  371. sort.Strings(unique)
  372. return
  373. }