authority.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package acme
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "encoding/base64"
  8. "net"
  9. "net/http"
  10. "net/url"
  11. "time"
  12. "github.com/pkg/errors"
  13. "github.com/smallstep/certificates/authority/provisioner"
  14. database "github.com/smallstep/certificates/db"
  15. "github.com/smallstep/nosql"
  16. "go.step.sm/crypto/jose"
  17. )
  18. // Interface is the acme authority interface.
  19. type Interface interface {
  20. GetDirectory(ctx context.Context) (*Directory, error)
  21. NewNonce() (string, error)
  22. UseNonce(string) error
  23. DeactivateAccount(ctx context.Context, accID string) (*Account, error)
  24. GetAccount(ctx context.Context, accID string) (*Account, error)
  25. GetAccountByKey(ctx context.Context, key *jose.JSONWebKey) (*Account, error)
  26. NewAccount(ctx context.Context, ao AccountOptions) (*Account, error)
  27. UpdateAccount(context.Context, string, []string) (*Account, error)
  28. GetAuthz(ctx context.Context, accID string, authzID string) (*Authz, error)
  29. ValidateChallenge(ctx context.Context, accID string, chID string, key *jose.JSONWebKey) (*Challenge, error)
  30. FinalizeOrder(ctx context.Context, accID string, orderID string, csr *x509.CertificateRequest) (*Order, error)
  31. GetOrder(ctx context.Context, accID string, orderID string) (*Order, error)
  32. GetOrdersByAccount(ctx context.Context, accID string) ([]string, error)
  33. NewOrder(ctx context.Context, oo OrderOptions) (*Order, error)
  34. GetCertificate(string, string) ([]byte, error)
  35. LoadProvisionerByID(string) (provisioner.Interface, error)
  36. GetLink(ctx context.Context, linkType Link, absoluteLink bool, inputs ...string) string
  37. GetLinkExplicit(linkType Link, provName string, absoluteLink bool, baseURL *url.URL, inputs ...string) string
  38. }
  39. // Authority is the layer that handles all ACME interactions.
  40. type Authority struct {
  41. backdate provisioner.Duration
  42. db nosql.DB
  43. dir *directory
  44. signAuth SignAuthority
  45. }
  46. // AuthorityOptions required to create a new ACME Authority.
  47. type AuthorityOptions struct {
  48. Backdate provisioner.Duration
  49. // DB is the database used by nosql.
  50. DB nosql.DB
  51. // DNS the host used to generate accurate ACME links. By default the authority
  52. // will use the Host from the request, so this value will only be used if
  53. // request.Host is empty.
  54. DNS string
  55. // Prefix is a URL path prefix under which the ACME api is served. This
  56. // prefix is required to generate accurate ACME links.
  57. // E.g. https://ca.smallstep.com/acme/my-acme-provisioner/new-account --
  58. // "acme" is the prefix from which the ACME api is accessed.
  59. Prefix string
  60. }
  61. var (
  62. accountTable = []byte("acme_accounts")
  63. accountByKeyIDTable = []byte("acme_keyID_accountID_index")
  64. authzTable = []byte("acme_authzs")
  65. challengeTable = []byte("acme_challenges")
  66. nonceTable = []byte("nonces")
  67. orderTable = []byte("acme_orders")
  68. ordersByAccountIDTable = []byte("acme_account_orders_index")
  69. certTable = []byte("acme_certs")
  70. )
  71. // NewAuthority returns a new Authority that implements the ACME interface.
  72. //
  73. // Deprecated: NewAuthority exists for hitorical compatibility and should not
  74. // be used. Use acme.New() instead.
  75. func NewAuthority(db nosql.DB, dns, prefix string, signAuth SignAuthority) (*Authority, error) {
  76. return New(signAuth, AuthorityOptions{
  77. DB: db,
  78. DNS: dns,
  79. Prefix: prefix,
  80. })
  81. }
  82. // New returns a new Autohrity that implements the ACME interface.
  83. func New(signAuth SignAuthority, ops AuthorityOptions) (*Authority, error) {
  84. if _, ok := ops.DB.(*database.SimpleDB); !ok {
  85. // If it's not a SimpleDB then go ahead and bootstrap the DB with the
  86. // necessary ACME tables. SimpleDB should ONLY be used for testing.
  87. tables := [][]byte{accountTable, accountByKeyIDTable, authzTable,
  88. challengeTable, nonceTable, orderTable, ordersByAccountIDTable,
  89. certTable}
  90. for _, b := range tables {
  91. if err := ops.DB.CreateTable(b); err != nil {
  92. return nil, errors.Wrapf(err, "error creating table %s",
  93. string(b))
  94. }
  95. }
  96. }
  97. return &Authority{
  98. backdate: ops.Backdate, db: ops.DB, dir: newDirectory(ops.DNS, ops.Prefix), signAuth: signAuth,
  99. }, nil
  100. }
  101. // GetLink returns the requested link from the directory.
  102. func (a *Authority) GetLink(ctx context.Context, typ Link, abs bool, inputs ...string) string {
  103. return a.dir.getLink(ctx, typ, abs, inputs...)
  104. }
  105. // GetLinkExplicit returns the requested link from the directory.
  106. func (a *Authority) GetLinkExplicit(typ Link, provName string, abs bool, baseURL *url.URL, inputs ...string) string {
  107. return a.dir.getLinkExplicit(typ, provName, abs, baseURL, inputs...)
  108. }
  109. // GetDirectory returns the ACME directory object.
  110. func (a *Authority) GetDirectory(ctx context.Context) (*Directory, error) {
  111. return &Directory{
  112. NewNonce: a.dir.getLink(ctx, NewNonceLink, true),
  113. NewAccount: a.dir.getLink(ctx, NewAccountLink, true),
  114. NewOrder: a.dir.getLink(ctx, NewOrderLink, true),
  115. RevokeCert: a.dir.getLink(ctx, RevokeCertLink, true),
  116. KeyChange: a.dir.getLink(ctx, KeyChangeLink, true),
  117. }, nil
  118. }
  119. // LoadProvisionerByID calls out to the SignAuthority interface to load a
  120. // provisioner by ID.
  121. func (a *Authority) LoadProvisionerByID(id string) (provisioner.Interface, error) {
  122. return a.signAuth.LoadProvisionerByID(id)
  123. }
  124. // NewNonce generates, stores, and returns a new ACME nonce.
  125. func (a *Authority) NewNonce() (string, error) {
  126. n, err := newNonce(a.db)
  127. if err != nil {
  128. return "", err
  129. }
  130. return n.ID, nil
  131. }
  132. // UseNonce consumes the given nonce if it is valid, returns error otherwise.
  133. func (a *Authority) UseNonce(nonce string) error {
  134. return useNonce(a.db, nonce)
  135. }
  136. // NewAccount creates, stores, and returns a new ACME account.
  137. func (a *Authority) NewAccount(ctx context.Context, ao AccountOptions) (*Account, error) {
  138. acc, err := newAccount(a.db, ao)
  139. if err != nil {
  140. return nil, err
  141. }
  142. return acc.toACME(ctx, a.db, a.dir)
  143. }
  144. // UpdateAccount updates an ACME account.
  145. func (a *Authority) UpdateAccount(ctx context.Context, id string, contact []string) (*Account, error) {
  146. acc, err := getAccountByID(a.db, id)
  147. if err != nil {
  148. return nil, ServerInternalErr(err)
  149. }
  150. if acc, err = acc.update(a.db, contact); err != nil {
  151. return nil, err
  152. }
  153. return acc.toACME(ctx, a.db, a.dir)
  154. }
  155. // GetAccount returns an ACME account.
  156. func (a *Authority) GetAccount(ctx context.Context, id string) (*Account, error) {
  157. acc, err := getAccountByID(a.db, id)
  158. if err != nil {
  159. return nil, err
  160. }
  161. return acc.toACME(ctx, a.db, a.dir)
  162. }
  163. // DeactivateAccount deactivates an ACME account.
  164. func (a *Authority) DeactivateAccount(ctx context.Context, id string) (*Account, error) {
  165. acc, err := getAccountByID(a.db, id)
  166. if err != nil {
  167. return nil, err
  168. }
  169. if acc, err = acc.deactivate(a.db); err != nil {
  170. return nil, err
  171. }
  172. return acc.toACME(ctx, a.db, a.dir)
  173. }
  174. func keyToID(jwk *jose.JSONWebKey) (string, error) {
  175. kid, err := jwk.Thumbprint(crypto.SHA256)
  176. if err != nil {
  177. return "", ServerInternalErr(errors.Wrap(err, "error generating jwk thumbprint"))
  178. }
  179. return base64.RawURLEncoding.EncodeToString(kid), nil
  180. }
  181. // GetAccountByKey returns the ACME associated with the jwk id.
  182. func (a *Authority) GetAccountByKey(ctx context.Context, jwk *jose.JSONWebKey) (*Account, error) {
  183. kid, err := keyToID(jwk)
  184. if err != nil {
  185. return nil, err
  186. }
  187. acc, err := getAccountByKeyID(a.db, kid)
  188. if err != nil {
  189. return nil, err
  190. }
  191. return acc.toACME(ctx, a.db, a.dir)
  192. }
  193. // GetOrder returns an ACME order.
  194. func (a *Authority) GetOrder(ctx context.Context, accID, orderID string) (*Order, error) {
  195. o, err := getOrder(a.db, orderID)
  196. if err != nil {
  197. return nil, err
  198. }
  199. if accID != o.AccountID {
  200. return nil, UnauthorizedErr(errors.New("account does not own order"))
  201. }
  202. if o, err = o.updateStatus(a.db); err != nil {
  203. return nil, err
  204. }
  205. return o.toACME(ctx, a.db, a.dir)
  206. }
  207. // GetOrdersByAccount returns the list of order urls owned by the account.
  208. func (a *Authority) GetOrdersByAccount(ctx context.Context, id string) ([]string, error) {
  209. ordersByAccountMux.Lock()
  210. defer ordersByAccountMux.Unlock()
  211. var oiba = orderIDsByAccount{}
  212. oids, err := oiba.unsafeGetOrderIDsByAccount(a.db, id)
  213. if err != nil {
  214. return nil, err
  215. }
  216. var ret = []string{}
  217. for _, oid := range oids {
  218. ret = append(ret, a.dir.getLink(ctx, OrderLink, true, oid))
  219. }
  220. return ret, nil
  221. }
  222. // NewOrder generates, stores, and returns a new ACME order.
  223. func (a *Authority) NewOrder(ctx context.Context, ops OrderOptions) (*Order, error) {
  224. prov, err := ProvisionerFromContext(ctx)
  225. if err != nil {
  226. return nil, err
  227. }
  228. ops.backdate = a.backdate.Duration
  229. ops.defaultDuration = prov.DefaultTLSCertDuration()
  230. order, err := newOrder(a.db, ops)
  231. if err != nil {
  232. return nil, Wrap(err, "error creating order")
  233. }
  234. return order.toACME(ctx, a.db, a.dir)
  235. }
  236. // FinalizeOrder attempts to finalize an order and generate a new certificate.
  237. func (a *Authority) FinalizeOrder(ctx context.Context, accID, orderID string, csr *x509.CertificateRequest) (*Order, error) {
  238. prov, err := ProvisionerFromContext(ctx)
  239. if err != nil {
  240. return nil, err
  241. }
  242. o, err := getOrder(a.db, orderID)
  243. if err != nil {
  244. return nil, err
  245. }
  246. if accID != o.AccountID {
  247. return nil, UnauthorizedErr(errors.New("account does not own order"))
  248. }
  249. o, err = o.finalize(a.db, csr, a.signAuth, prov)
  250. if err != nil {
  251. return nil, Wrap(err, "error finalizing order")
  252. }
  253. return o.toACME(ctx, a.db, a.dir)
  254. }
  255. // GetAuthz retrieves and attempts to update the status on an ACME authz
  256. // before returning.
  257. func (a *Authority) GetAuthz(ctx context.Context, accID, authzID string) (*Authz, error) {
  258. az, err := getAuthz(a.db, authzID)
  259. if err != nil {
  260. return nil, err
  261. }
  262. if accID != az.getAccountID() {
  263. return nil, UnauthorizedErr(errors.New("account does not own authz"))
  264. }
  265. az, err = az.updateStatus(a.db)
  266. if err != nil {
  267. return nil, Wrap(err, "error updating authz status")
  268. }
  269. return az.toACME(ctx, a.db, a.dir)
  270. }
  271. // ValidateChallenge attempts to validate the challenge.
  272. func (a *Authority) ValidateChallenge(ctx context.Context, accID, chID string, jwk *jose.JSONWebKey) (*Challenge, error) {
  273. ch, err := getChallenge(a.db, chID)
  274. if err != nil {
  275. return nil, err
  276. }
  277. if accID != ch.getAccountID() {
  278. return nil, UnauthorizedErr(errors.New("account does not own challenge"))
  279. }
  280. client := http.Client{
  281. Timeout: time.Duration(30 * time.Second),
  282. }
  283. dialer := &net.Dialer{
  284. Timeout: 30 * time.Second,
  285. }
  286. ch, err = ch.validate(a.db, jwk, validateOptions{
  287. httpGet: client.Get,
  288. lookupTxt: net.LookupTXT,
  289. tlsDial: func(network, addr string, config *tls.Config) (*tls.Conn, error) {
  290. return tls.DialWithDialer(dialer, network, addr, config)
  291. },
  292. })
  293. if err != nil {
  294. return nil, Wrap(err, "error attempting challenge validation")
  295. }
  296. return ch.toACME(ctx, a.db, a.dir)
  297. }
  298. // GetCertificate retrieves the Certificate by ID.
  299. func (a *Authority) GetCertificate(accID, certID string) ([]byte, error) {
  300. cert, err := getCert(a.db, certID)
  301. if err != nil {
  302. return nil, err
  303. }
  304. if accID != cert.AccountID {
  305. return nil, UnauthorizedErr(errors.New("account does not own certificate"))
  306. }
  307. return cert.toACME(a.db, a.dir)
  308. }