authority.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package acme
  2. import (
  3. "crypto"
  4. "crypto/x509"
  5. "encoding/base64"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "time"
  10. "github.com/pkg/errors"
  11. "github.com/smallstep/certificates/authority/provisioner"
  12. database "github.com/smallstep/certificates/db"
  13. "github.com/smallstep/cli/jose"
  14. "github.com/smallstep/nosql"
  15. )
  16. // Interface is the acme authority interface.
  17. type Interface interface {
  18. DeactivateAccount(provisioner.Interface, string) (*Account, error)
  19. FinalizeOrder(provisioner.Interface, string, string, *x509.CertificateRequest) (*Order, error)
  20. GetAccount(provisioner.Interface, string) (*Account, error)
  21. GetAccountByKey(provisioner.Interface, *jose.JSONWebKey) (*Account, error)
  22. GetAuthz(provisioner.Interface, string, string) (*Authz, error)
  23. GetCertificate(string, string) ([]byte, error)
  24. GetDirectory(provisioner.Interface) *Directory
  25. GetLink(Link, string, bool, ...string) string
  26. GetOrder(provisioner.Interface, string, string) (*Order, error)
  27. GetOrdersByAccount(provisioner.Interface, string) ([]string, error)
  28. LoadProvisionerByID(string) (provisioner.Interface, error)
  29. NewAccount(provisioner.Interface, AccountOptions) (*Account, error)
  30. NewNonce() (string, error)
  31. NewOrder(provisioner.Interface, OrderOptions) (*Order, error)
  32. UpdateAccount(provisioner.Interface, string, []string) (*Account, error)
  33. UseNonce(string) error
  34. ValidateChallenge(provisioner.Interface, string, string, *jose.JSONWebKey) (*Challenge, error)
  35. }
  36. // Authority is the layer that handles all ACME interactions.
  37. type Authority struct {
  38. db nosql.DB
  39. dir *directory
  40. signAuth SignAuthority
  41. }
  42. var (
  43. accountTable = []byte("acme_accounts")
  44. accountByKeyIDTable = []byte("acme_keyID_accountID_index")
  45. authzTable = []byte("acme_authzs")
  46. challengeTable = []byte("acme_challenges")
  47. nonceTable = []byte("nonces")
  48. orderTable = []byte("acme_orders")
  49. ordersByAccountIDTable = []byte("acme_account_orders_index")
  50. certTable = []byte("acme_certs")
  51. )
  52. // NewAuthority returns a new Authority that implements the ACME interface.
  53. func NewAuthority(db nosql.DB, dns, prefix string, signAuth SignAuthority) (*Authority, error) {
  54. if _, ok := db.(*database.SimpleDB); !ok {
  55. // If it's not a SimpleDB then go ahead and bootstrap the DB with the
  56. // necessary ACME tables. SimpleDB should ONLY be used for testing.
  57. tables := [][]byte{accountTable, accountByKeyIDTable, authzTable,
  58. challengeTable, nonceTable, orderTable, ordersByAccountIDTable,
  59. certTable}
  60. for _, b := range tables {
  61. if err := db.CreateTable(b); err != nil {
  62. return nil, errors.Wrapf(err, "error creating table %s",
  63. string(b))
  64. }
  65. }
  66. }
  67. return &Authority{
  68. db: db, dir: newDirectory(dns, prefix), signAuth: signAuth,
  69. }, nil
  70. }
  71. // GetLink returns the requested link from the directory.
  72. func (a *Authority) GetLink(typ Link, provID string, abs bool, inputs ...string) string {
  73. return a.dir.getLink(typ, provID, abs, inputs...)
  74. }
  75. // GetDirectory returns the ACME directory object.
  76. func (a *Authority) GetDirectory(p provisioner.Interface) *Directory {
  77. name := url.PathEscape(p.GetName())
  78. return &Directory{
  79. NewNonce: a.dir.getLink(NewNonceLink, name, true),
  80. NewAccount: a.dir.getLink(NewAccountLink, name, true),
  81. NewOrder: a.dir.getLink(NewOrderLink, name, true),
  82. RevokeCert: a.dir.getLink(RevokeCertLink, name, true),
  83. KeyChange: a.dir.getLink(KeyChangeLink, name, true),
  84. }
  85. }
  86. // LoadProvisionerByID calls out to the SignAuthority interface to load a
  87. // provisioner by ID.
  88. func (a *Authority) LoadProvisionerByID(id string) (provisioner.Interface, error) {
  89. return a.signAuth.LoadProvisionerByID(id)
  90. }
  91. // NewNonce generates, stores, and returns a new ACME nonce.
  92. func (a *Authority) NewNonce() (string, error) {
  93. n, err := newNonce(a.db)
  94. if err != nil {
  95. return "", err
  96. }
  97. return n.ID, nil
  98. }
  99. // UseNonce consumes the given nonce if it is valid, returns error otherwise.
  100. func (a *Authority) UseNonce(nonce string) error {
  101. return useNonce(a.db, nonce)
  102. }
  103. // NewAccount creates, stores, and returns a new ACME account.
  104. func (a *Authority) NewAccount(p provisioner.Interface, ao AccountOptions) (*Account, error) {
  105. acc, err := newAccount(a.db, ao)
  106. if err != nil {
  107. return nil, err
  108. }
  109. return acc.toACME(a.db, a.dir, p)
  110. }
  111. // UpdateAccount updates an ACME account.
  112. func (a *Authority) UpdateAccount(p provisioner.Interface, id string, contact []string) (*Account, error) {
  113. acc, err := getAccountByID(a.db, id)
  114. if err != nil {
  115. return nil, ServerInternalErr(err)
  116. }
  117. if acc, err = acc.update(a.db, contact); err != nil {
  118. return nil, err
  119. }
  120. return acc.toACME(a.db, a.dir, p)
  121. }
  122. // GetAccount returns an ACME account.
  123. func (a *Authority) GetAccount(p provisioner.Interface, id string) (*Account, error) {
  124. acc, err := getAccountByID(a.db, id)
  125. if err != nil {
  126. return nil, err
  127. }
  128. return acc.toACME(a.db, a.dir, p)
  129. }
  130. // DeactivateAccount deactivates an ACME account.
  131. func (a *Authority) DeactivateAccount(p provisioner.Interface, id string) (*Account, error) {
  132. acc, err := getAccountByID(a.db, id)
  133. if err != nil {
  134. return nil, err
  135. }
  136. if acc, err = acc.deactivate(a.db); err != nil {
  137. return nil, err
  138. }
  139. return acc.toACME(a.db, a.dir, p)
  140. }
  141. func keyToID(jwk *jose.JSONWebKey) (string, error) {
  142. kid, err := jwk.Thumbprint(crypto.SHA256)
  143. if err != nil {
  144. return "", ServerInternalErr(errors.Wrap(err, "error generating jwk thumbprint"))
  145. }
  146. return base64.RawURLEncoding.EncodeToString(kid), nil
  147. }
  148. // GetAccountByKey returns the ACME associated with the jwk id.
  149. func (a *Authority) GetAccountByKey(p provisioner.Interface, jwk *jose.JSONWebKey) (*Account, error) {
  150. kid, err := keyToID(jwk)
  151. if err != nil {
  152. return nil, err
  153. }
  154. acc, err := getAccountByKeyID(a.db, kid)
  155. if err != nil {
  156. return nil, err
  157. }
  158. return acc.toACME(a.db, a.dir, p)
  159. }
  160. // GetOrder returns an ACME order.
  161. func (a *Authority) GetOrder(p provisioner.Interface, accID, orderID string) (*Order, error) {
  162. o, err := getOrder(a.db, orderID)
  163. if err != nil {
  164. return nil, err
  165. }
  166. if accID != o.AccountID {
  167. return nil, UnauthorizedErr(errors.New("account does not own order"))
  168. }
  169. if o, err = o.updateStatus(a.db); err != nil {
  170. return nil, err
  171. }
  172. return o.toACME(a.db, a.dir, p)
  173. }
  174. // GetOrdersByAccount returns the list of order urls owned by the account.
  175. func (a *Authority) GetOrdersByAccount(p provisioner.Interface, id string) ([]string, error) {
  176. oids, err := getOrderIDsByAccount(a.db, id)
  177. if err != nil {
  178. return nil, err
  179. }
  180. var ret = []string{}
  181. for _, oid := range oids {
  182. o, err := getOrder(a.db, oid)
  183. if err != nil {
  184. return nil, ServerInternalErr(err)
  185. }
  186. if o.Status == StatusInvalid {
  187. continue
  188. }
  189. ret = append(ret, a.dir.getLink(OrderLink, URLSafeProvisionerName(p), true, o.ID))
  190. }
  191. return ret, nil
  192. }
  193. // NewOrder generates, stores, and returns a new ACME order.
  194. func (a *Authority) NewOrder(p provisioner.Interface, ops OrderOptions) (*Order, error) {
  195. order, err := newOrder(a.db, ops)
  196. if err != nil {
  197. return nil, Wrap(err, "error creating order")
  198. }
  199. return order.toACME(a.db, a.dir, p)
  200. }
  201. // FinalizeOrder attempts to finalize an order and generate a new certificate.
  202. func (a *Authority) FinalizeOrder(p provisioner.Interface, accID, orderID string, csr *x509.CertificateRequest) (*Order, error) {
  203. o, err := getOrder(a.db, orderID)
  204. if err != nil {
  205. return nil, err
  206. }
  207. if accID != o.AccountID {
  208. return nil, UnauthorizedErr(errors.New("account does not own order"))
  209. }
  210. o, err = o.finalize(a.db, csr, a.signAuth, p)
  211. if err != nil {
  212. return nil, Wrap(err, "error finalizing order")
  213. }
  214. return o.toACME(a.db, a.dir, p)
  215. }
  216. // GetAuthz retrieves and attempts to update the status on an ACME authz
  217. // before returning.
  218. func (a *Authority) GetAuthz(p provisioner.Interface, accID, authzID string) (*Authz, error) {
  219. az, err := getAuthz(a.db, authzID)
  220. if err != nil {
  221. return nil, err
  222. }
  223. if accID != az.getAccountID() {
  224. return nil, UnauthorizedErr(errors.New("account does not own authz"))
  225. }
  226. az, err = az.updateStatus(a.db)
  227. if err != nil {
  228. return nil, Wrap(err, "error updating authz status")
  229. }
  230. return az.toACME(a.db, a.dir, p)
  231. }
  232. // ValidateChallenge attempts to validate the challenge.
  233. func (a *Authority) ValidateChallenge(p provisioner.Interface, accID, chID string, jwk *jose.JSONWebKey) (*Challenge, error) {
  234. ch, err := getChallenge(a.db, chID)
  235. if err != nil {
  236. return nil, err
  237. }
  238. if accID != ch.getAccountID() {
  239. return nil, UnauthorizedErr(errors.New("account does not own challenge"))
  240. }
  241. client := http.Client{
  242. Timeout: time.Duration(30 * time.Second),
  243. }
  244. ch, err = ch.validate(a.db, jwk, validateOptions{
  245. httpGet: client.Get,
  246. lookupTxt: net.LookupTXT,
  247. })
  248. if err != nil {
  249. return nil, Wrap(err, "error attempting challenge validation")
  250. }
  251. return ch.toACME(a.db, a.dir, p)
  252. }
  253. // GetCertificate retrieves the Certificate by ID.
  254. func (a *Authority) GetCertificate(accID, certID string) ([]byte, error) {
  255. cert, err := getCert(a.db, certID)
  256. if err != nil {
  257. return nil, err
  258. }
  259. if accID != cert.AccountID {
  260. return nil, UnauthorizedErr(errors.New("account does not own certificate"))
  261. }
  262. return cert.toACME(a.db, a.dir)
  263. }