Skip to content

Commit

Permalink
fix: pem parsing should allow single dashes in comments
Browse files Browse the repository at this point in the history
  • Loading branch information
lrstewart committed Sep 20, 2024
1 parent 0bae2c5 commit b591b9a
Show file tree
Hide file tree
Showing 3 changed files with 463 additions and 11 deletions.
26 changes: 16 additions & 10 deletions stuffer/s2n_stuffer_pem.c
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@
#include "stuffer/s2n_stuffer.h"
#include "utils/s2n_safety.h"

#define S2N_PEM_DELIMTER_CHAR '-'
#define S2N_PEM_DELIMITER_MIN_COUNT 1
#define S2N_PEM_DELIMITER_CHAR '-'
#define S2N_PEM_DELIMITER_TOKEN "--"
#define S2N_PEM_DELIMITER_MIN_COUNT 2
#define S2N_PEM_DELIMITER_MAX_COUNT 64
#define S2N_PEM_BEGIN_TOKEN "BEGIN "
#define S2N_PEM_END_TOKEN "END "
Expand All @@ -36,21 +37,26 @@
static int s2n_stuffer_pem_read_encapsulation_line(struct s2n_stuffer *pem, const char *encap_marker,
const char *keyword)
{
/* Skip any number of Chars until a "-" is reached */
POSIX_GUARD(s2n_stuffer_skip_to_char(pem, S2N_PEM_DELIMTER_CHAR));
/* Skip any number of Chars until a "--" is reached.
* We use "--" instead of "-" to account for dashes that appear in comments.
* We do not accept comments that contain "--".
*/
POSIX_GUARD(s2n_stuffer_skip_read_until(pem, S2N_PEM_DELIMITER_TOKEN));

/* Ensure between 1 and 64 '-' chars at start of line */
POSIX_GUARD(s2n_stuffer_skip_expected_char(pem, S2N_PEM_DELIMTER_CHAR, S2N_PEM_DELIMITER_MIN_COUNT,
S2N_PEM_DELIMITER_MAX_COUNT, NULL));
/* Ensure between 2 and 64 '-' chars at start of line.
* We already read 2 '-' chars when we read the S2N_PEM_DELIMITER_TOKEN.
*/
POSIX_GUARD(s2n_stuffer_skip_expected_char(pem, S2N_PEM_DELIMITER_CHAR, 0,
S2N_PEM_DELIMITER_MAX_COUNT - 2, NULL));

/* Ensure next string in stuffer is "BEGIN " or "END " */
POSIX_GUARD(s2n_stuffer_read_expected_str(pem, encap_marker));

/* Ensure next string is stuffer is the keyword (Eg "CERTIFICATE", "PRIVATE KEY", etc) */
POSIX_GUARD(s2n_stuffer_read_expected_str(pem, keyword));

/* Ensure between 1 and 64 '-' chars at end of line */
POSIX_GUARD(s2n_stuffer_skip_expected_char(pem, S2N_PEM_DELIMTER_CHAR, S2N_PEM_DELIMITER_MIN_COUNT,
/* Ensure between 2 and 64 '-' chars at end of line */
POSIX_GUARD(s2n_stuffer_skip_expected_char(pem, S2N_PEM_DELIMITER_CHAR, S2N_PEM_DELIMITER_MIN_COUNT,
S2N_PEM_DELIMITER_MAX_COUNT, NULL));

/* Check for missing newline between dashes case: "-----END CERTIFICATE----------BEGIN CERTIFICATE-----" */
Expand All @@ -60,7 +66,7 @@ static int s2n_stuffer_pem_read_encapsulation_line(struct s2n_stuffer *pem, cons
POSIX_GUARD(s2n_stuffer_rewind_read(pem, 1));
}

/* Skip newlines and other whitepsace that may be after the dashes */
/* Skip newlines and other whitespace that may be after the dashes */
return s2n_stuffer_skip_whitespace(pem, NULL);
}

Expand Down
Loading

0 comments on commit b591b9a

Please sign in to comment.