pem_common.c
Go to the documentation of this file.
1 /**
2  * @file pem_common.c
3  * @brief PEM common definitions
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2025 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneCRYPTO 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.5.2
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL CRYPTO_TRACE_LEVEL
33 
34 //Dependencies
35 #include "core/crypto.h"
36 #include "pkix/pem_common.h"
37 #include "encoding/oid.h"
38 #include "encoding/base64.h"
40 #include "debug.h"
41 
42 //Check crypto library configuration
43 #if (PEM_SUPPORT == ENABLED)
44 
45 
46 /**
47  * @brief Convert PEM container to ASN.1 format
48  * @param[in] input PEM string to decode
49  * @param[in] inputLen Length of the PEM string to decode
50  * @param[in] label Label indicating the type of data
51  * @param[out] output ASN.1 data (optional parameter)
52  * @param[out] outputLen Length of the ASN.1 data
53  * @param[out] header PEM encapsulated header (optional parameter)
54  * @param[out] consumed Total number of characters that have been consumed
55  * (optional parameter)
56  **/
57 
58 error_t pemDecodeFile(const char_t *input, size_t inputLen, const char_t *label,
59  uint8_t *output, size_t *outputLen, PemHeader *header, size_t *consumed)
60 {
61  error_t error;
62  int_t i;
63  int_t j;
64  size_t n;
65 
66  //Check parameters
67  if(input == NULL || label == NULL || outputLen == NULL)
69 
70  //The PEM container begins with a "-----BEGIN " line
71  i = pemFindTag(input, inputLen, "-----BEGIN ", label, "-----");
72  //Pre-encapsulation boundary not found?
73  if(i < 0)
74  return ERROR_END_OF_FILE;
75 
76  //Skip the pre-encapsulation boundary
77  i += osStrlen("-----BEGIN -----") + osStrlen(label);
78 
79  //The PEM container ends with a "-----END " line
80  j = pemFindTag(input + i, inputLen - i, "-----END ", label, "-----");
81  //Post-encapsulation boundary not found?
82  if(j < 0)
83  return ERROR_INVALID_SYNTAX;
84 
85  //Parse PEM encapsulated header
86  error = pemParseHeader(input + i, j, header, &n);
87  //Any error to report?
88  if(error)
89  return error;
90 
91  //The contents of the PEM file is Base64-encoded
92  error = base64Decode(input + i + n, j - n, output, outputLen);
93  //Failed to decode the file?
94  if(error)
95  return error;
96 
97  //Sanity check
98  if(*outputLen == 0)
99  return ERROR_INVALID_SYNTAX;
100 
101  //The last parameter is optional
102  if(consumed != NULL)
103  {
104  //Total number of characters that have been consumed
105  *consumed = i + j + osStrlen("-----END -----") + osStrlen(label);
106  }
107 
108  //Successful processing
109  return NO_ERROR;
110 }
111 
112 
113 /**
114  * @brief Convert ASN.1 data to PEM encoding
115  * @param[in] input ASN.1 data to encode
116  * @param[in] inputLen Length of the ASN.1 data to encode
117  * @param[in] label Label indicating the type of data
118  * @param[out] output Buffer where to store the PEM string (optional parameter)
119  * @param[out] outputLen Length of the resulting PEM string
120  **/
121 
122 error_t pemEncodeFile(const void *input, size_t inputLen, const char_t *label,
123  char_t *output, size_t *outputLen)
124 {
125  size_t n;
126  size_t labelLen;
127  char_t *p;
128 
129  //Check parameters
130  if(label == NULL || outputLen == NULL)
132 
133  //Sanity check
134  if(input == NULL && output != NULL)
136 
137  //Calculate the length of the label
138  labelLen = osStrlen(label);
139 
140  //Generators must wrap the Base64-encoded lines so that each line consists
141  //of exactly 64 characters except for the final line, which will encode the
142  //remainder of the data (refer to RFC 7468, section 2)
143  base64EncodeMultiline(input, inputLen, output, &n, 64);
144 
145  //If the output parameter is NULL, then the function calculates the length
146  //of the resulting PEM file without copying any data
147  if(output != NULL)
148  {
149  //A PEM file starts with a pre-encapsulation boundary
150  p = output + osStrlen("-----BEGIN -----\r\n") + labelLen;
151 
152  //Make room for the pre-encapsulation boundary
153  osMemmove(p, output, n);
154 
155  //The type of data encoded is labeled depending on the type label in
156  //the "-----BEGIN " line (refer to RFC 7468, section 2)
157  osStrcpy(output, "-----BEGIN ");
158  osStrcpy(output + 11, label);
159  osMemcpy(p - 7, "-----\r\n", 7);
160 
161  //Generators must put the same label on the "-----END " line as the
162  //corresponding "-----BEGIN " line
163  osStrcpy(p + n, "\r\n-----END ");
164  osStrcpy(p + n + 11, label);
165  osStrcpy(p + n + labelLen + 11, "-----\r\n");
166  }
167 
168  //Consider the length of the PEM encapsulation boundaries
169  n += osStrlen("-----BEGIN -----\r\n") + labelLen;
170  n += osStrlen("\r\n-----END -----\r\n") + labelLen;
171 
172  //Return the length of the PEM string (excluding the terminating NULL)
173  *outputLen = n;
174 
175  //Successful processing
176  return NO_ERROR;
177 }
178 
179 
180 /**
181  * @brief Parse PEM encapsulated header
182  * @param[in] input PEM message body
183  * @param[in] inputLen Length of the PEM message body
184  * @param[in] header PEM encapsulated header (optional parameter)
185  * @param[out] consumed Total number of bytes that have been consumed
186  * @return Error code
187  **/
188 
189 error_t pemParseHeader(const char_t *input, size_t inputLen,
190  PemHeader *header, size_t *consumed)
191 {
192  size_t n;
193  const char_t *end;
194  PemString line;
195 
196  //The header parameter is optional
197  if(header != NULL)
198  {
199  //Clear header fields
200  osMemset(header, 0, sizeof(PemHeader));
201  }
202 
203  //Total number of bytes that have been consumed
204  *consumed = 0;
205 
206  //Parse PEM encapsulated header
207  while(1)
208  {
209  //Extract a line from the PEM message body
210  end = osMemchr(input, '\n', inputLen);
211  //No end of line character detected?
212  if(end == NULL)
213  break;
214 
215  //Calculate the length of the line
216  n = end - input + 1;
217 
218  //Point to the current line
219  line.value = input;
220  line.length = n;
221 
222  //Removes all leading and trailing whitespace from a string
223  pemTrimWhitespace(&line);
224 
225  //Discard empty lines
226  if(!pemCompareString(&line, ""))
227  {
228  //Each header field consists of a field name followed by a colon,
229  //optional leading whitespace, and the field value
230  if(pemFindChar(&line, ':') >= 0)
231  {
232  //Parse header field
233  pemParseHeaderField(&line, header);
234  }
235  else
236  {
237  //We are done
238  break;
239  }
240  }
241 
242  //Point to the next line
243  input += n;
244  inputLen -= n;
245  *consumed += n;
246  }
247 
248  //Sucessful processing
249  return NO_ERROR;
250 }
251 
252 
253 /**
254  * @brief Parse header field
255  * @param[in] line Header field
256  * @param[in] header PEM encapsulated header (optional parameter)
257  **/
258 
260 {
261  PemString name;
262  PemString arg1;
263  PemString arg2;
264 
265  //Each header field consists of a field name followed by a colon,
266  //optional leading whitespace, and the field value
267  pemTokenizeString(line, ':', &name);
268 
269  //Removes all leading and trailing whitespace from the name
271 
272  //Check header field name
273  if(pemCompareString(&name, "Proc-Type"))
274  {
275  //The "Proc-Type" encapsulated header field, required for all PEM
276  //messages, identifies the type of processing performed on the
277  //transmitted message (refer to RFC 1421, section 4.6.1.1)
278  if(pemTokenizeString(line, ',', &arg1) &&
279  pemTokenizeString(line, ',', &arg2))
280  {
281  //Removes all leading and trailing whitespace characters
282  pemTrimWhitespace(&arg1);
283  pemTrimWhitespace(&arg2);
284 
285  //Save arguments
286  if(header != NULL)
287  {
288  header->procType.version = arg1;
289  header->procType.type = arg2;
290  }
291  }
292  }
293  else if(pemCompareString(&name, "DEK-Info"))
294  {
295  //The "DEK-Info" encapsulated header field identifies the message text
296  //encryption algorithm and mode, and also carries the IV used for message
297  //encryption (refer to RFC 1421, section 4.6.1.3)
298  if(pemTokenizeString(line, ',', &arg1) &&
299  pemTokenizeString(line, ',', &arg2))
300  {
301  //Removes all leading and trailing whitespace characters
302  pemTrimWhitespace(&arg1);
303  pemTrimWhitespace(&arg2);
304 
305  //Save arguments
306  if(header != NULL)
307  {
308  header->dekInfo.algo = arg1;
309  header->dekInfo.iv = arg2;
310  }
311  }
312  }
313  else
314  {
315  //Unknown header field name
316  }
317 }
318 
319 
320 /**
321  * @brief Search a string for a given tag
322  * @param[in] input String to search
323  * @param[in] inputLen Length of the string to search
324  * @param[in] tag1 First part of the tag (NULL-terminated string)
325  * @param[in] tag2 Second part of the tag (NULL-terminated string)
326  * @param[in] tag3 Third part of the tag (NULL-terminated string)
327  * @return The index of the first occurrence of the tag in the string,
328  * or -1 if the tag does not appear in the string
329  **/
330 
331 int_t pemFindTag(const char_t *input, size_t inputLen, const char_t *tag1,
332  const char_t *tag2, const char_t *tag3)
333 {
334  size_t i;
335  size_t j;
336  size_t n1;
337  size_t n2;
338  size_t n3;
339  int_t index;
340 
341  //Initialize index
342  index = -1;
343 
344  //Calculate the length of the tag
345  n1 = osStrlen(tag1);
346  n2 = osStrlen(tag2);
347  n3 = osStrlen(tag3);
348 
349  //Parse input string
350  for(i = 0; (i + n1 + n2 + n3) <= inputLen; i++)
351  {
352  //Compare current substring with the given tag
353  for(j = 0; j < (n1 + n2 + n3); j++)
354  {
355  if(j < n1)
356  {
357  if(input[i + j] != tag1[j])
358  break;
359  }
360  else if(j < (n1 + n2))
361  {
362  if(input[i + j] != tag2[j - n1])
363  break;
364  }
365  else
366  {
367  if(input[i + j] != tag3[j - n1 - n2])
368  break;
369  }
370  }
371 
372  //Check whether the tag has been found
373  if(j == (n1 + n2 + n3))
374  {
375  index = i;
376  break;
377  }
378  }
379 
380  //Return the index of the first occurrence of the tag in the string
381  return index;
382 }
383 
384 
385 /**
386  * @brief Search a string for a given character
387  * @param[in] s String to be scanned
388  * @param[in] c Character to be searched
389  * @return Index of the first occurrence of the character
390  **/
391 
393 {
394  int_t index;
395  char_t *p;
396 
397  //Search the string for the specified character
398  p = osMemchr(s->value, c, s->length);
399 
400  //Character found?
401  if(p != NULL)
402  {
403  index = p - s->value;
404  }
405  else
406  {
407  index = -1;
408  }
409 
410  //Return the index of the first occurrence of the character
411  return index;
412 }
413 
414 
415 /**
416  * @brief Compare a string against the supplied value
417  * @param[in] string String to be compared
418  * @param[in] value NULL-terminated string
419  * @return Comparison result
420  **/
421 
423 {
424  bool_t res;
425  size_t n;
426 
427  //Initialize flag
428  res = FALSE;
429 
430  //Valid NULL-terminated string?
431  if(value != NULL)
432  {
433  //Determine the length of the string
434  n = osStrlen(value);
435 
436  //Check the length of the string
437  if(string->value != NULL && string->length == n)
438  {
439  //Perform string comparison
440  if(osStrncmp(string->value, value, n) == 0)
441  {
442  res = TRUE;
443  }
444  }
445  }
446 
447  //Return comparison result
448  return res;
449 }
450 
451 
452 /**
453  * @brief Split a string into tokens
454  * @param[in,out] s String to be split
455  * @param[in] c Delimiter character
456  * @param[out] token Resulting token
457  * @return TRUE if a token has been found, else FALSE
458  **/
459 
461 {
462  char_t *p;
463  size_t n;
464  bool_t found;
465 
466  //Search the string for the specified delimiter character
467  p = osMemchr(s->value, c, s->length);
468 
469  //Delimiter character found?
470  if(p != NULL)
471  {
472  //Retrieve the length of the token
473  n = p - s->value;
474 
475  //Extract the token from the string
476  token->value = s->value;
477  token->length = n;
478 
479  //Point to the next token
480  s->value += n + 1;
481  s->length -= n + 1;
482 
483  //A token has been found
484  found = TRUE;
485  }
486  else if(s->length > 0)
487  {
488  //This is the last token
489  token->value = s->value;
490  token->length = s->length;
491 
492  //A token has been found
493  found = TRUE;
494  }
495  else
496  {
497  //The end of the string has been reached
498  found = FALSE;
499  }
500 
501  //Return TRUE if a token has been found, else FALSE
502  return found;
503 }
504 
505 
506 /**
507  * @brief Removes all leading and trailing whitespace from a string
508  * @param[in] s String to be trimmed
509  **/
510 
512 {
513  //Trim whitespace from the beginning
514  while(s->length > 0 && osIsspace(s->value[0]))
515  {
516  s->value++;
517  s->length--;
518  }
519 
520  //Trim whitespace from the end
521  while(s->length > 0 && osIsspace(s->value[s->length - 1]))
522  {
523  s->length--;
524  }
525 }
526 
527 #endif
String representation.
Definition: pem_common.h:48
int bool_t
Definition: compiler_port.h:61
signed int int_t
Definition: compiler_port.h:56
#define osMemchr(p, c, length)
Definition: os_port.h:162
OID (Object Identifier)
uint8_t p
Definition: ndp.h:300
error_t pemDecodeFile(const char_t *input, size_t inputLen, const char_t *label, uint8_t *output, size_t *outputLen, PemHeader *header, size_t *consumed)
Convert PEM container to ASN.1 format.
Definition: pem_common.c:58
#define TRUE
Definition: os_port.h:50
Collection of AEAD algorithms.
char_t name[]
#define osStrlen(s)
Definition: os_port.h:168
PEM common definitions.
void base64EncodeMultiline(const void *input, size_t inputLen, char_t *output, size_t *outputLen, size_t lineWidth)
Base64 multiline encoding.
Definition: base64.c:79
bool_t pemCompareString(const PemString *string, const char_t *value)
Compare a string against the supplied value.
Definition: pem_common.c:422
const uint8_t res[]
bool_t pemTokenizeString(PemString *s, char_t c, PemString *token)
Split a string into tokens.
Definition: pem_common.c:460
PEM encapsulated header.
Definition: pem_common.h:81
PemString version
Definition: pem_common.h:60
error_t base64Decode(const char_t *input, size_t inputLen, void *output, size_t *outputLen)
Base64 decoding algorithm.
Definition: base64.c:258
#define FALSE
Definition: os_port.h:46
void pemTrimWhitespace(PemString *s)
Removes all leading and trailing whitespace from a string.
Definition: pem_common.c:511
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
#define osMemcpy(dest, src, length)
Definition: os_port.h:144
error_t
Error codes.
Definition: error.h:43
PemDekInfo dekInfo
Definition: pem_common.h:83
error_t pemEncodeFile(const void *input, size_t inputLen, const char_t *label, char_t *output, size_t *outputLen)
Convert ASN.1 data to PEM encoding.
Definition: pem_common.c:122
#define osIsspace(c)
Definition: os_port.h:294
@ ERROR_END_OF_FILE
Definition: error.h:160
General definitions for cryptographic algorithms.
PemString iv
Definition: pem_common.h:72
Base64 encoding scheme.
PemString type
Definition: pem_common.h:61
PemString algo
Definition: pem_common.h:71
int_t pemFindChar(const PemString *s, char_t c)
Search a string for a given character.
Definition: pem_common.c:392
char char_t
Definition: compiler_port.h:55
uint8_t n
size_t length
Definition: pem_common.h:50
uint8_t value[]
Definition: tcp.h:376
int_t pemFindTag(const char_t *input, size_t inputLen, const char_t *tag1, const char_t *tag2, const char_t *tag3)
Search a string for a given tag.
Definition: pem_common.c:331
const char_t * value
Definition: pem_common.h:49
@ ERROR_INVALID_SYNTAX
Definition: error.h:68
error_t pemParseHeader(const char_t *input, size_t inputLen, PemHeader *header, size_t *consumed)
Parse PEM encapsulated header.
Definition: pem_common.c:189
uint8_t s
Definition: igmp_common.h:234
PemProcType procType
Definition: pem_common.h:82
#define osStrncmp(s1, s2, length)
Definition: os_port.h:180
void pemParseHeaderField(PemString *line, PemHeader *header)
Parse header field.
Definition: pem_common.c:259
#define osMemset(p, value, length)
Definition: os_port.h:138
#define osStrcpy(s1, s2)
Definition: os_port.h:210
@ NO_ERROR
Success.
Definition: error.h:44
uint8_t c
Definition: ndp.h:514
Debugging facilities.
#define osMemmove(dest, src, length)
Definition: os_port.h:150
uint8_t token[]
Definition: coap_common.h:181