4
0

order.go 14 KB

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