acme_client_certificate.c
Go to the documentation of this file.
1 /**
2  * @file acme_client_certificate.c
3  * @brief Certificate management
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2019-2024 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneACME Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.4.4
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL ACME_TRACE_LEVEL
33 
34 //Dependencies
35 #include "acme/acme_client.h"
37 #include "acme/acme_client_jose.h"
38 #include "acme/acme_client_misc.h"
39 #include "pkix/pem_import.h"
40 #include "encoding/base64url.h"
41 #include "jansson.h"
42 #include "jansson_private.h"
43 #include "debug.h"
44 
45 //Check TCP/IP stack configuration
46 #if (ACME_CLIENT_SUPPORT == ENABLED)
47 
48 
49 /**
50  * @brief Send HTTP request (certificate URL)
51  * @param[in] context Pointer to the ACME client context
52  * @param[out] buffer Pointer to the buffer where to store the certificate chain
53  * @param[in] size Size of the buffer, in bytes
54  * @param[out] length Actual length of the certificate chain, in bytes
55  * @return Error code
56  **/
57 
59  char_t *buffer, size_t size, size_t *length)
60 {
61  error_t error;
62 
63  //Initialize variables
64  error = NO_ERROR;
65 
66  //Perform HTTP request
67  while(!error)
68  {
69  //Check HTTP request state
70  if(context->requestState == ACME_REQ_STATE_INIT)
71  {
72  //Debug message
73  TRACE_DEBUG("\r\n");
74  TRACE_DEBUG("###############################################################################\r\n");
75  TRACE_DEBUG("## DOWNLOAD CERTIFICATE #######################################################\r\n");
76  TRACE_DEBUG("###############################################################################\r\n");
77  TRACE_DEBUG("\r\n");
78 
79  //Update HTTP request state
80  context->requestState = ACME_REQ_STATE_FORMAT_BODY;
81  }
82  else if(context->requestState == ACME_REQ_STATE_FORMAT_BODY)
83  {
84  //Format the body of the HTTP request
85  error = acmeClientFormatDownloadCertRequest(context);
86 
87  //Check status code
88  if(!error)
89  {
90  //Update HTTP request state
91  context->requestState = ACME_REQ_STATE_FORMAT_HEADER;
92  }
93  }
94  else if(context->requestState == ACME_REQ_STATE_FORMAT_HEADER)
95  {
96  //To download the issued certificate, the client simply sends a
97  //POST-as-GET request to the certificate URL (refer to RFC 8555,
98  //section 7.4.2)
99  error = acmeClientFormatRequestHeader(context, "POST",
100  context->order.certificate);
101 
102  //Check status code
103  if(!error)
104  {
105  //Update HTTP request state
106  context->requestState = ACME_REQ_STATE_SEND_HEADER;
107  }
108  }
109  else if(context->requestState == ACME_REQ_STATE_SEND_HEADER ||
110  context->requestState == ACME_REQ_STATE_SEND_BODY ||
111  context->requestState == ACME_REQ_STATE_RECEIVE_HEADER ||
112  context->requestState == ACME_REQ_STATE_PARSE_HEADER ||
113  context->requestState == ACME_REQ_STATE_RECEIVE_BODY ||
114  context->requestState == ACME_REQ_STATE_CLOSE_BODY)
115  {
116  //Perform HTTP request/response transaction
117  error = acmeClientSendRequest(context);
118  }
119  else if(context->requestState == ACME_REQ_STATE_PARSE_BODY)
120  {
121  //Parse the body of the HTTP response
122  error = acmeClientParseDownloadCertResponse(context, buffer, size,
123  length);
124 
125  //The HTTP transaction is complete
126  context->requestState = ACME_REQ_STATE_INIT;
127  break;
128  }
129  else
130  {
131  //Invalid state
132  error = ERROR_WRONG_STATE;
133  }
134  }
135 
136  //Return status code
137  return error;
138 }
139 
140 
141 /**
142  * @brief Format HTTP request body (certificate URL)
143  * @param[in] context Pointer to the ACME client context
144  * @return Error code
145  **/
146 
148 {
149  error_t error;
150  size_t n;
151  char_t *protected;
152  const char_t *payload;
153 
154  //The payload field is empty for POST-as-GET requests
155  payload = "";
156 
157  //Point to the buffer where to format the JWS protected header
158  protected = context->buffer;
159 
160  //Format JWS protected header
161  error = acmeClientFormatJwsProtectedHeader(&context->accountKey,
162  context->account.url, context->nonce, context->order.certificate,
163  protected, &n);
164 
165  //Check status code
166  if(!error)
167  {
168  //Generate the JSON Web Signature
169  error = jwsCreate(context->prngAlgo, context->prngContext, protected,
170  payload, context->accountKey.alg, context->accountKey.crv,
171  context->accountKey.privateKey, context->buffer, &context->bufferLen);
172  }
173 
174  //Return status code
175  return error;
176 }
177 
178 
179 /**
180  * @brief Parse HTTP response (certificate URL)
181  * @param[in] context Pointer to the ACME client context
182  * @param[out] buffer Pointer to the buffer where to store the certificate chain
183  * @param[in] size Size of the buffer, in bytes
184  * @param[out] length Actual length of the certificate chain, in bytes
185  * @return Error code
186  **/
187 
189  char_t *buffer, size_t size, size_t *length)
190 {
191  error_t error;
192  size_t n;
193 
194  //Initialize variables
195  error = NO_ERROR;
196 
197  //Check HTTP status code
198  if(!HTTP_STATUS_CODE_2YZ(context->statusCode))
200 
201  //The server must include a Replay-Nonce header field in every successful
202  //response to a POST request (refer to RFC 8555, section 6.5)
203  if(context->nonce[0] == '\0')
204  return ERROR_INVALID_RESPONSE;
205 
206  //Invalid media type?
207  if(osStrcasecmp(context->contentType, "application/pem-certificate-chain") != 0)
208  return ERROR_INVALID_RESPONSE;
209 
210  //Check whether the body of the response is truncated
211  if(context->bufferLen >= ACME_CLIENT_BUFFER_SIZE)
213 
214  //The body must contain a valid PEM certificate chain
215  error = pemImportCertificate(context->buffer, context->bufferLen, NULL,
216  &n, NULL);
217  //Any error to report?
218  if(error)
219  return ERROR_INVALID_RESPONSE;
220 
221  //Make sure the output buffer is large enough to hold the certificate
222  if(context->bufferLen > size)
223  return ERROR_BUFFER_OVERFLOW;
224 
225  //Copy certificate chain
226  osMemcpy(buffer, context->buffer, context->bufferLen);
227 
228  //Return the length of the certificate chain
229  *length = context->bufferLen;
230 
231  //Return status code
232  return error;
233 }
234 
235 
236 /**
237  * @brief Send HTTP request (revokeCert URL)
238  * @param[in] context Pointer to the ACME client context
239  * @param[in] cert Certificate to be revoked (PEM format)
240  * @param[in] certLen Length of the certificate, in bytes
241  * @param[in] reason Revocation reason code
242  * @return Error code
243  **/
244 
246  const char_t *cert, size_t certLen, AcmeReasonCode reason)
247 {
248  error_t error;
249 
250  //Initialize variables
251  error = NO_ERROR;
252 
253  //Perform HTTP request
254  while(!error)
255  {
256  //Check HTTP request state
257  if(context->requestState == ACME_REQ_STATE_INIT)
258  {
259  //Debug message
260  TRACE_DEBUG("\r\n");
261  TRACE_DEBUG("###############################################################################\r\n");
262  TRACE_DEBUG("## REVOKE CERTIFICATE #########################################################\r\n");
263  TRACE_DEBUG("###############################################################################\r\n");
264  TRACE_DEBUG("\r\n");
265 
266  //Update HTTP request state
267  context->requestState = ACME_REQ_STATE_FORMAT_BODY;
268  }
269  else if(context->requestState == ACME_REQ_STATE_FORMAT_BODY)
270  {
271  //Format the body of the HTTP request
272  error = acmeClientFormatRevokeCertRequest(context, cert, certLen, reason);
273 
274  //Check status code
275  if(!error)
276  {
277  //Update HTTP request state
278  context->requestState = ACME_REQ_STATE_FORMAT_HEADER;
279  }
280  }
281  else if(context->requestState == ACME_REQ_STATE_FORMAT_HEADER)
282  {
283  //To request that a certificate be revoked, the client sends a POST
284  //request to the ACME server's revokeCert URL (refer to RFC 8555,
285  //section 7.6)
286  error = acmeClientFormatRequestHeader(context, "POST",
287  context->directory.revokeCert);
288 
289  //Check status code
290  if(!error)
291  {
292  //Update HTTP request state
293  context->requestState = ACME_REQ_STATE_SEND_HEADER;
294  }
295  }
296  else if(context->requestState == ACME_REQ_STATE_SEND_HEADER ||
297  context->requestState == ACME_REQ_STATE_SEND_BODY ||
298  context->requestState == ACME_REQ_STATE_RECEIVE_HEADER ||
299  context->requestState == ACME_REQ_STATE_PARSE_HEADER ||
300  context->requestState == ACME_REQ_STATE_RECEIVE_BODY ||
301  context->requestState == ACME_REQ_STATE_CLOSE_BODY)
302  {
303  //Perform HTTP request/response transaction
304  error = acmeClientSendRequest(context);
305  }
306  else if(context->requestState == ACME_REQ_STATE_PARSE_BODY)
307  {
308  //Parse the body of the HTTP response
309  error = acmeClientParseRevokeCertResponse(context);
310 
311  //The HTTP transaction is complete
312  context->requestState = ACME_REQ_STATE_INIT;
313  break;
314  }
315  else
316  {
317  //Invalid state
318  error = ERROR_WRONG_STATE;
319  }
320  }
321 
322  //Return status code
323  return error;
324 }
325 
326 
327 /**
328  * @brief Format HTTP request body (revokeCert URL)
329  * @param[in] context Pointer to the ACME client context
330  * @param[in] cert Certificate to be revoked (PEM format)
331  * @param[in] certLen Length of the certificate, in bytes
332  * @param[in] reason Revocation reason code
333  * @return Error code
334  **/
335 
337  const char_t *cert, size_t certLen, AcmeReasonCode reason)
338 {
339  error_t error;
340  int_t ret;
341  size_t n;
342  char_t *protected;
343  char_t *payload;
344  json_t *payloadObj;
345 
346  //Convert the PEM certificate to DER format
347  error = pemImportCertificate(cert, certLen, (uint8_t *) context->buffer,
348  &n, NULL);
349  //Any error to report?
350  if(error)
351  return error;
352 
353  //Encode the DER certificate using Base64url
354  base64urlEncode(context->buffer, n, context->buffer, &n);
355 
356  //Initialize JSON object
357  payloadObj = json_object();
358 
359  //The body of the POST contains the certificate to be revoked
360  ret = json_object_set_new(payloadObj, "certificate",
361  json_string(context->buffer));
362 
363  //The client may include a revocation reason code
364  ret |= json_object_set_new(payloadObj, "reason",
365  json_integer((json_int_t) reason));
366 
367  //JSON object successfully created?
368  if(ret == 0)
369  {
370  //Generate the JSON representation of the payload object
371  payload = json_dumps(payloadObj, JSON_COMPACT);
372  }
373  else
374  {
375  //An error occurred during processing
376  payload = NULL;
377  }
378 
379  //Valid JSON representation?
380  if(payload != NULL)
381  {
382  //Point to the buffer where to format the JWS protected header
383  protected = context->buffer;
384 
385  //Format JWS protected header
386  error = acmeClientFormatJwsProtectedHeader(&context->accountKey,
387  context->account.url, context->nonce, context->directory.revokeCert,
388  protected, &n);
389 
390  //Check status code
391  if(!error)
392  {
393  //Generate the JSON Web Signature
394  error = jwsCreate(context->prngAlgo, context->prngContext, protected,
395  payload, context->accountKey.alg, context->accountKey.crv,
396  context->accountKey.privateKey, context->buffer, &context->bufferLen);
397  }
398 
399  //Release JSON string
400  jsonp_free(payload);
401  }
402  else
403  {
404  //Report an error
405  error = ERROR_FAILURE;
406  }
407 
408  //Release JSON object
409  json_decref(payloadObj);
410 
411  //Return status code
412  return error;
413 }
414 
415 
416 /**
417  * @brief Parse HTTP response (certificate URL)
418  * @param[in] context Pointer to the ACME client context
419  * @return Error code
420  **/
421 
423 {
424  //Check HTTP status code
425  if(!HTTP_STATUS_CODE_2YZ(context->statusCode))
427 
428  //The server must include a Replay-Nonce header field in every successful
429  //response to a POST request (refer to RFC 8555, section 6.5)
430  if(context->nonce[0] == '\0')
431  return ERROR_INVALID_RESPONSE;
432 
433  //Successful processing
434  return NO_ERROR;
435 }
436 
437 #endif
error_t acmeClientSendDownloadCertRequest(AcmeClientContext *context, char_t *buffer, size_t size, size_t *length)
Send HTTP request (certificate URL)
signed int int_t
Definition: compiler_port.h:49
@ ERROR_BUFFER_OVERFLOW
Definition: error.h:142
#define HTTP_STATUS_CODE_2YZ(code)
Definition: http_common.h:44
Helper functions for ACME client.
AcmeReasonCode
Revocation reason codes.
Definition: acme_client.h:378
@ ACME_REQ_STATE_PARSE_BODY
Definition: acme_client.h:297
#define ACME_CLIENT_BUFFER_SIZE
Definition: acme_client.h:166
JOSE (JSON Object Signing and Encryption)
@ ERROR_WRONG_STATE
Definition: error.h:209
@ ACME_REQ_STATE_FORMAT_HEADER
Definition: acme_client.h:290
error_t acmeClientSendRequest(AcmeClientContext *context)
Send HTTP request.
error_t pemImportCertificate(const char_t *input, size_t inputLen, uint8_t *output, size_t *outputLen, size_t *consumed)
Decode a PEM file containing a certificate.
Definition: pem_import.c:61
PEM file import functions.
@ ERROR_UNEXPECTED_STATUS
Definition: error.h:283
#define osMemcpy(dest, src, length)
Definition: os_port.h:141
error_t acmeClientFormatRequestHeader(AcmeClientContext *context, const char_t *method, const char_t *url)
Format HTTP request header.
error_t
Error codes.
Definition: error.h:43
Certificate management.
void base64urlEncode(const void *input, size_t inputLen, char_t *output, size_t *outputLen)
Base64url encoding algorithm.
Definition: base64url.c:72
error_t acmeClientParseRevokeCertResponse(AcmeClientContext *context)
Parse HTTP response (certificate URL)
error_t acmeClientFormatJwsProtectedHeader(const AcmeKeyPair *keyPair, const char_t *kid, const char_t *nonce, const char_t *url, char_t *buffer, size_t *written)
Format JWS protected header.
@ ERROR_RESPONSE_TOO_LARGE
Definition: error.h:284
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
@ ACME_REQ_STATE_CLOSE_BODY
Definition: acme_client.h:298
#define osStrcasecmp(s1, s2)
Definition: os_port.h:183
Base64url encoding scheme.
@ ACME_REQ_STATE_INIT
Definition: acme_client.h:289
error_t acmeClientFormatDownloadCertRequest(AcmeClientContext *context)
Format HTTP request body (certificate URL)
uint8_t length
Definition: tcp.h:368
@ ACME_REQ_STATE_FORMAT_BODY
Definition: acme_client.h:292
@ ACME_REQ_STATE_RECEIVE_HEADER
Definition: acme_client.h:294
#define TRACE_DEBUG(...)
Definition: debug.h:107
char char_t
Definition: compiler_port.h:48
#define AcmeClientContext
Definition: acme_client.h:248
error_t jwsCreate(const PrngAlgo *prngAlgo, void *prngContext, const char_t *protected, const char_t *payload, const char_t *alg, const char_t *crv, const void *privateKey, char_t *buffer, size_t *written)
Create a JSON Web Signature.
uint8_t n
uint8_t payload[]
Definition: ipv6.h:286
error_t acmeClientSendRevokeCertRequest(AcmeClientContext *context, const char_t *cert, size_t certLen, AcmeReasonCode reason)
Send HTTP request (revokeCert URL)
@ ACME_REQ_STATE_SEND_HEADER
Definition: acme_client.h:291
@ ACME_REQ_STATE_PARSE_HEADER
Definition: acme_client.h:295
@ ACME_REQ_STATE_RECEIVE_BODY
Definition: acme_client.h:296
@ ACME_REQ_STATE_SEND_BODY
Definition: acme_client.h:293
@ ERROR_INVALID_RESPONSE
Definition: error.h:71
ACME client (Automatic Certificate Management Environment)
error_t acmeClientFormatRevokeCertRequest(AcmeClientContext *context, const char_t *cert, size_t certLen, AcmeReasonCode reason)
Format HTTP request body (revokeCert URL)
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
error_t acmeClientParseDownloadCertResponse(AcmeClientContext *context, char_t *buffer, size_t size, size_t *length)
Parse HTTP response (certificate URL)