account.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "github.com/go-chi/chi"
  7. "github.com/smallstep/certificates/acme"
  8. "github.com/smallstep/certificates/api"
  9. "github.com/smallstep/certificates/logging"
  10. "go.step.sm/crypto/jose"
  11. )
  12. // ExternalAccountBinding represents the ACME externalAccountBinding JWS
  13. type ExternalAccountBinding struct {
  14. Protected string `json:"protected"`
  15. Payload string `json:"payload"`
  16. Sig string `json:"signature"`
  17. }
  18. // NewAccountRequest represents the payload for a new account request.
  19. type NewAccountRequest struct {
  20. Contact []string `json:"contact"`
  21. OnlyReturnExisting bool `json:"onlyReturnExisting"`
  22. TermsOfServiceAgreed bool `json:"termsOfServiceAgreed"`
  23. ExternalAccountBinding *ExternalAccountBinding `json:"externalAccountBinding,omitempty"`
  24. }
  25. func validateContacts(cs []string) error {
  26. for _, c := range cs {
  27. if c == "" {
  28. return acme.NewError(acme.ErrorMalformedType, "contact cannot be empty string")
  29. }
  30. }
  31. return nil
  32. }
  33. // Validate validates a new-account request body.
  34. func (n *NewAccountRequest) Validate() error {
  35. if n.OnlyReturnExisting && len(n.Contact) > 0 {
  36. return acme.NewError(acme.ErrorMalformedType, "incompatible input; onlyReturnExisting must be alone")
  37. }
  38. return validateContacts(n.Contact)
  39. }
  40. // UpdateAccountRequest represents an update-account request.
  41. type UpdateAccountRequest struct {
  42. Contact []string `json:"contact"`
  43. Status acme.Status `json:"status"`
  44. }
  45. // Validate validates a update-account request body.
  46. func (u *UpdateAccountRequest) Validate() error {
  47. switch {
  48. case len(u.Status) > 0 && len(u.Contact) > 0:
  49. return acme.NewError(acme.ErrorMalformedType, "incompatible input; contact and "+
  50. "status updates are mutually exclusive")
  51. case len(u.Contact) > 0:
  52. if err := validateContacts(u.Contact); err != nil {
  53. return err
  54. }
  55. return nil
  56. case len(u.Status) > 0:
  57. if u.Status != acme.StatusDeactivated {
  58. return acme.NewError(acme.ErrorMalformedType, "cannot update account "+
  59. "status to %s, only deactivated", u.Status)
  60. }
  61. return nil
  62. default:
  63. // According to the ACME spec (https://tools.ietf.org/html/rfc8555#section-7.3.2)
  64. // accountUpdate should ignore any fields not recognized by the server.
  65. return nil
  66. }
  67. }
  68. // NewAccount is the handler resource for creating new ACME accounts.
  69. func (h *Handler) NewAccount(w http.ResponseWriter, r *http.Request) {
  70. ctx := r.Context()
  71. payload, err := payloadFromContext(ctx)
  72. if err != nil {
  73. api.WriteError(w, err)
  74. return
  75. }
  76. var nar NewAccountRequest
  77. if err := json.Unmarshal(payload.value, &nar); err != nil {
  78. api.WriteError(w, acme.WrapError(acme.ErrorMalformedType, err,
  79. "failed to unmarshal new-account request payload"))
  80. return
  81. }
  82. if err := nar.Validate(); err != nil {
  83. api.WriteError(w, err)
  84. return
  85. }
  86. prov, err := acmeProvisionerFromContext(ctx)
  87. if err != nil {
  88. api.WriteError(w, err)
  89. return
  90. }
  91. httpStatus := http.StatusCreated
  92. acc, err := accountFromContext(ctx)
  93. if err != nil {
  94. acmeErr, ok := err.(*acme.Error)
  95. if !ok || acmeErr.Status != http.StatusBadRequest {
  96. // Something went wrong ...
  97. api.WriteError(w, err)
  98. return
  99. }
  100. // Account does not exist //
  101. if nar.OnlyReturnExisting {
  102. api.WriteError(w, acme.NewError(acme.ErrorAccountDoesNotExistType,
  103. "account does not exist"))
  104. return
  105. }
  106. jwk, err := jwkFromContext(ctx)
  107. if err != nil {
  108. api.WriteError(w, err)
  109. return
  110. }
  111. eak, err := h.validateExternalAccountBinding(ctx, &nar)
  112. if err != nil {
  113. api.WriteError(w, err)
  114. return
  115. }
  116. acc = &acme.Account{
  117. Key: jwk,
  118. Contact: nar.Contact,
  119. Status: acme.StatusValid,
  120. }
  121. if err := h.db.CreateAccount(ctx, acc); err != nil {
  122. api.WriteError(w, acme.WrapErrorISE(err, "error creating account"))
  123. return
  124. }
  125. if eak != nil { // means that we have a (valid) External Account Binding key that should be bound, updated and sent in the response
  126. err := eak.BindTo(acc)
  127. if err != nil {
  128. api.WriteError(w, err)
  129. return
  130. }
  131. if err := h.db.UpdateExternalAccountKey(ctx, prov.ID, eak); err != nil {
  132. api.WriteError(w, acme.WrapErrorISE(err, "error updating external account binding key"))
  133. return
  134. }
  135. acc.ExternalAccountBinding = nar.ExternalAccountBinding
  136. }
  137. } else {
  138. // Account exists
  139. httpStatus = http.StatusOK
  140. }
  141. h.linker.LinkAccount(ctx, acc)
  142. w.Header().Set("Location", h.linker.GetLink(r.Context(), AccountLinkType, acc.ID))
  143. api.JSONStatus(w, acc, httpStatus)
  144. }
  145. // GetOrUpdateAccount is the api for updating an ACME account.
  146. func (h *Handler) GetOrUpdateAccount(w http.ResponseWriter, r *http.Request) {
  147. ctx := r.Context()
  148. acc, err := accountFromContext(ctx)
  149. if err != nil {
  150. api.WriteError(w, err)
  151. return
  152. }
  153. payload, err := payloadFromContext(ctx)
  154. if err != nil {
  155. api.WriteError(w, err)
  156. return
  157. }
  158. // If PostAsGet just respond with the account, otherwise process like a
  159. // normal Post request.
  160. if !payload.isPostAsGet {
  161. var uar UpdateAccountRequest
  162. if err := json.Unmarshal(payload.value, &uar); err != nil {
  163. api.WriteError(w, acme.WrapError(acme.ErrorMalformedType, err,
  164. "failed to unmarshal new-account request payload"))
  165. return
  166. }
  167. if err := uar.Validate(); err != nil {
  168. api.WriteError(w, err)
  169. return
  170. }
  171. if len(uar.Status) > 0 || len(uar.Contact) > 0 {
  172. if len(uar.Status) > 0 {
  173. acc.Status = uar.Status
  174. } else if len(uar.Contact) > 0 {
  175. acc.Contact = uar.Contact
  176. }
  177. if err := h.db.UpdateAccount(ctx, acc); err != nil {
  178. api.WriteError(w, acme.WrapErrorISE(err, "error updating account"))
  179. return
  180. }
  181. }
  182. }
  183. h.linker.LinkAccount(ctx, acc)
  184. w.Header().Set("Location", h.linker.GetLink(ctx, AccountLinkType, acc.ID))
  185. api.JSON(w, acc)
  186. }
  187. func logOrdersByAccount(w http.ResponseWriter, oids []string) {
  188. if rl, ok := w.(logging.ResponseLogger); ok {
  189. m := map[string]interface{}{
  190. "orders": oids,
  191. }
  192. rl.WithFields(m)
  193. }
  194. }
  195. // GetOrdersByAccountID ACME api for retrieving the list of order urls belonging to an account.
  196. func (h *Handler) GetOrdersByAccountID(w http.ResponseWriter, r *http.Request) {
  197. ctx := r.Context()
  198. acc, err := accountFromContext(ctx)
  199. if err != nil {
  200. api.WriteError(w, err)
  201. return
  202. }
  203. accID := chi.URLParam(r, "accID")
  204. if acc.ID != accID {
  205. api.WriteError(w, acme.NewError(acme.ErrorUnauthorizedType, "account ID '%s' does not match url param '%s'", acc.ID, accID))
  206. return
  207. }
  208. orders, err := h.db.GetOrdersByAccountID(ctx, acc.ID)
  209. if err != nil {
  210. api.WriteError(w, err)
  211. return
  212. }
  213. h.linker.LinkOrdersByAccountID(ctx, orders)
  214. api.JSON(w, orders)
  215. logOrdersByAccount(w, orders)
  216. }
  217. // validateExternalAccountBinding validates the externalAccountBinding property in a call to new-account.
  218. func (h *Handler) validateExternalAccountBinding(ctx context.Context, nar *NewAccountRequest) (*acme.ExternalAccountKey, error) {
  219. acmeProv, err := acmeProvisionerFromContext(ctx)
  220. if err != nil {
  221. return nil, acme.WrapErrorISE(err, "could not load ACME provisioner from context")
  222. }
  223. if !acmeProv.RequireEAB {
  224. return nil, nil
  225. }
  226. if nar.ExternalAccountBinding == nil {
  227. return nil, acme.NewError(acme.ErrorExternalAccountRequiredType, "no external account binding provided")
  228. }
  229. eabJSONBytes, err := json.Marshal(nar.ExternalAccountBinding)
  230. if err != nil {
  231. return nil, acme.WrapErrorISE(err, "error marshaling externalAccountBinding into bytes")
  232. }
  233. eabJWS, err := jose.ParseJWS(string(eabJSONBytes))
  234. if err != nil {
  235. return nil, acme.WrapErrorISE(err, "error parsing externalAccountBinding jws")
  236. }
  237. // TODO(hs): implement strategy pattern to allow for different ways of verification (i.e. webhook call) based on configuration?
  238. keyID, acmeErr := validateEABJWS(ctx, eabJWS)
  239. if acmeErr != nil {
  240. return nil, acmeErr
  241. }
  242. externalAccountKey, err := h.db.GetExternalAccountKey(ctx, acmeProv.ID, keyID)
  243. if err != nil {
  244. if _, ok := err.(*acme.Error); ok {
  245. return nil, acme.WrapError(acme.ErrorUnauthorizedType, err, "the field 'kid' references an unknown key")
  246. }
  247. return nil, acme.WrapErrorISE(err, "error retrieving external account key")
  248. }
  249. if externalAccountKey.AlreadyBound() {
  250. return nil, acme.NewError(acme.ErrorUnauthorizedType, "external account binding key with id '%s' was already bound to account '%s' on %s", keyID, externalAccountKey.AccountID, externalAccountKey.BoundAt)
  251. }
  252. payload, err := eabJWS.Verify(externalAccountKey.KeyBytes)
  253. if err != nil {
  254. return nil, acme.WrapErrorISE(err, "error verifying externalAccountBinding signature")
  255. }
  256. jwk, err := jwkFromContext(ctx)
  257. if err != nil {
  258. return nil, err
  259. }
  260. var payloadJWK *jose.JSONWebKey
  261. if err = json.Unmarshal(payload, &payloadJWK); err != nil {
  262. return nil, acme.WrapError(acme.ErrorMalformedType, err, "error unmarshaling payload into jwk")
  263. }
  264. if !keysAreEqual(jwk, payloadJWK) {
  265. return nil, acme.NewError(acme.ErrorUnauthorizedType, "keys in jws and eab payload do not match")
  266. }
  267. return externalAccountKey, nil
  268. }
  269. // keysAreEqual performs an equality check on two JWKs by comparing
  270. // the (base64 encoding) of the Key IDs.
  271. func keysAreEqual(x, y *jose.JSONWebKey) bool {
  272. if x == nil || y == nil {
  273. return false
  274. }
  275. digestX, errX := acme.KeyToID(x)
  276. digestY, errY := acme.KeyToID(y)
  277. if errX != nil || errY != nil {
  278. return false
  279. }
  280. return digestX == digestY
  281. }
  282. // validateEABJWS verifies the contents of the External Account Binding JWS.
  283. // The protected header of the JWS MUST meet the following criteria:
  284. // o The "alg" field MUST indicate a MAC-based algorithm
  285. // o The "kid" field MUST contain the key identifier provided by the CA
  286. // o The "nonce" field MUST NOT be present
  287. // o The "url" field MUST be set to the same value as the outer JWS
  288. func validateEABJWS(ctx context.Context, jws *jose.JSONWebSignature) (string, *acme.Error) {
  289. if jws == nil {
  290. return "", acme.NewErrorISE("no JWS provided")
  291. }
  292. if len(jws.Signatures) != 1 {
  293. return "", acme.NewError(acme.ErrorMalformedType, "JWS must have one signature")
  294. }
  295. header := jws.Signatures[0].Protected
  296. algorithm := header.Algorithm
  297. keyID := header.KeyID
  298. nonce := header.Nonce
  299. if !(algorithm == jose.HS256 || algorithm == jose.HS384 || algorithm == jose.HS512) {
  300. return "", acme.NewError(acme.ErrorMalformedType, "'alg' field set to invalid algorithm '%s'", algorithm)
  301. }
  302. if keyID == "" {
  303. return "", acme.NewError(acme.ErrorMalformedType, "'kid' field is required")
  304. }
  305. if nonce != "" {
  306. return "", acme.NewError(acme.ErrorMalformedType, "'nonce' must not be present")
  307. }
  308. jwsURL, ok := header.ExtraHeaders["url"]
  309. if !ok {
  310. return "", acme.NewError(acme.ErrorMalformedType, "'url' field is required")
  311. }
  312. outerJWS, err := jwsFromContext(ctx)
  313. if err != nil {
  314. return "", acme.WrapErrorISE(err, "could not retrieve outer JWS from context")
  315. }
  316. if len(outerJWS.Signatures) != 1 {
  317. return "", acme.NewError(acme.ErrorMalformedType, "outer JWS must have one signature")
  318. }
  319. outerJWSURL, ok := outerJWS.Signatures[0].Protected.ExtraHeaders["url"]
  320. if !ok {
  321. return "", acme.NewError(acme.ErrorMalformedType, "'url' field must be set in outer JWS")
  322. }
  323. if jwsURL != outerJWSURL {
  324. return "", acme.NewError(acme.ErrorMalformedType, "'url' field is not the same value as the outer JWS")
  325. }
  326. return keyID, nil
  327. }