1use base64::{decoded_len_estimate, engine::general_purpose::STANDARD, Engine as _};
6use zeroize::Zeroizing;
7
8use crate::{PemDecodePolicy, PemDocument, PemError, PemLabel};
9
10const BEGIN_PREFIX: &str = "-----BEGIN ";
11const END_PREFIX: &str = "-----END ";
12const BOUNDARY_SUFFIX: &str = "-----";
13
14pub fn decode_pem(input: &str, policy: PemDecodePolicy<'_>) -> Result<PemDocument, PemError> {
16 if input.is_empty() || input.len() > policy.max_input_len {
17 return Err(PemError::InputTooLarge);
18 }
19 if policy.max_der_len == 0 || policy.allowed_labels.is_empty() {
20 return Err(PemError::InvalidOptions);
21 }
22
23 let normalized = Zeroizing::new(normalize_line_endings(input)?);
24 let mut lines = normalized.split('\n');
25
26 let begin_line = next_nonempty_line(&mut lines).ok_or(PemError::MissingBegin)?;
27 let begin_label = parse_boundary_label(begin_line, BEGIN_PREFIX)?;
28 let label = PemLabel::parse(begin_label)?;
29 if !policy.allowed_labels.contains(&label) {
30 return Err(PemError::UnsupportedLabel);
31 }
32
33 let encoded_limit = encoded_len_limit(policy.max_der_len)?;
34 let body_capacity = input.len().min(encoded_limit);
37 let mut body = Zeroizing::new(String::with_capacity(body_capacity));
38 let mut found_end = false;
39
40 for line in lines {
41 if line.is_empty() {
42 continue;
43 }
44 if found_end {
45 return Err(PemError::InvalidBoundary);
46 }
47 if line.starts_with(END_PREFIX) {
48 let end_label = parse_boundary_label(line, END_PREFIX)?;
49 if end_label != label.as_str() {
50 return Err(PemError::LabelMismatch);
51 }
52 found_end = true;
53 continue;
54 }
55 if line.starts_with(BEGIN_PREFIX) {
56 return Err(PemError::InvalidBoundary);
57 }
58 if !line.bytes().all(is_base64_body_byte) {
59 return Err(PemError::InvalidBody);
60 }
61 let next_len = body
62 .len()
63 .checked_add(line.len())
64 .ok_or(PemError::InvalidOptions)?;
65 if next_len > encoded_limit {
66 return Err(PemError::DerTooLarge);
67 }
68 body.push_str(line);
69 }
70
71 if !found_end {
72 return Err(PemError::MissingEnd);
73 }
74 if body.is_empty() {
75 return Err(PemError::InvalidBody);
76 }
77
78 let mut der = Zeroizing::new(vec![0_u8; decoded_len_estimate(body.len())]);
81 let decoded_length = STANDARD
82 .decode_slice(body.as_bytes(), der.as_mut_slice())
83 .map_err(|_| PemError::InvalidBase64)?;
84 der.truncate(decoded_length);
85 if der.is_empty() || der.len() > policy.max_der_len {
86 return Err(PemError::DerTooLarge);
87 }
88
89 Ok(PemDocument { label, der })
90}
91
92fn normalize_line_endings(input: &str) -> Result<String, PemError> {
93 let mut output = String::with_capacity(input.len());
97 let bytes = input.as_bytes();
98 let mut cursor = 0_usize;
99 while cursor < bytes.len() {
100 let start = cursor;
101 while cursor < bytes.len() && bytes[cursor] != b'\r' {
102 cursor = cursor.checked_add(1).ok_or(PemError::InvalidOptions)?;
103 }
104 output.push_str(&input[start..cursor]);
105 if cursor == bytes.len() {
106 break;
107 }
108 output.push('\n');
109 cursor = cursor.checked_add(1).ok_or(PemError::InvalidOptions)?;
110 if cursor < bytes.len() && bytes[cursor] == b'\n' {
111 cursor = cursor.checked_add(1).ok_or(PemError::InvalidOptions)?;
112 }
113 }
114 Ok(output)
115}
116
117fn next_nonempty_line<'a>(lines: &mut impl Iterator<Item = &'a str>) -> Option<&'a str> {
118 lines.find(|line| !line.is_empty())
119}
120
121fn parse_boundary_label<'a>(line: &'a str, prefix: &str) -> Result<&'a str, PemError> {
122 let remainder = line.strip_prefix(prefix).ok_or(PemError::InvalidBoundary)?;
123 let label = remainder
124 .strip_suffix(BOUNDARY_SUFFIX)
125 .ok_or(PemError::InvalidBoundary)?;
126 if label.is_empty() || label.as_bytes().iter().any(|byte| !is_label_byte(*byte)) {
127 return Err(PemError::InvalidBoundary);
128 }
129 Ok(label)
130}
131
132fn encoded_len_limit(max_der_len: usize) -> Result<usize, PemError> {
133 let groups = max_der_len.checked_add(2).ok_or(PemError::InvalidOptions)? / 3;
134 groups.checked_mul(4).ok_or(PemError::InvalidOptions)
135}
136
137fn is_label_byte(byte: u8) -> bool {
138 byte == b' ' || byte == b'-' || byte.is_ascii_uppercase() || byte.is_ascii_digit()
139}
140
141fn is_base64_body_byte(byte: u8) -> bool {
142 byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'=')
143}