1use alloc::format;
2use alloc::string::String;
3use alloc::vec::Vec;
4#[cfg(feature = "std")]
5use core::iter;
6#[cfg(feature = "std")]
7use std::io::{self, ErrorKind};
89use pki_types::{
10 pem, CertificateDer, CertificateRevocationListDer, CertificateSigningRequestDer,
11 PrivatePkcs1KeyDer, PrivatePkcs8KeyDer, PrivateSec1KeyDer, SubjectPublicKeyInfoDer,
12};
1314/// The contents of a single recognised block in a PEM file.
15#[non_exhaustive]
16#[derive(Debug, PartialEq)]
17pub enum Item {
18/// A DER-encoded x509 certificate.
19 ///
20 /// Appears as "CERTIFICATE" in PEM files.
21X509Certificate(CertificateDer<'static>),
2223/// A DER-encoded Subject Public Key Info; as specified in RFC 7468.
24 ///
25 /// Appears as "PUBLIC KEY" in PEM files.
26SubjectPublicKeyInfo(SubjectPublicKeyInfoDer<'static>),
2728/// A DER-encoded plaintext RSA private key; as specified in PKCS #1/RFC 3447
29 ///
30 /// Appears as "RSA PRIVATE KEY" in PEM files.
31Pkcs1Key(PrivatePkcs1KeyDer<'static>),
3233/// A DER-encoded plaintext private key; as specified in PKCS #8/RFC 5958
34 ///
35 /// Appears as "PRIVATE KEY" in PEM files.
36Pkcs8Key(PrivatePkcs8KeyDer<'static>),
3738/// A Sec1-encoded plaintext private key; as specified in RFC 5915
39 ///
40 /// Appears as "EC PRIVATE KEY" in PEM files.
41Sec1Key(PrivateSec1KeyDer<'static>),
4243/// A Certificate Revocation List; as specified in RFC 5280
44 ///
45 /// Appears as "X509 CRL" in PEM files.
46Crl(CertificateRevocationListDer<'static>),
4748/// A Certificate Signing Request; as specified in RFC 2986
49 ///
50 /// Appears as "CERTIFICATE REQUEST" in PEM files.
51Csr(CertificateSigningRequestDer<'static>),
52}
5354impl Item {
55#[cfg(feature = "std")]
56fn from_buf(rd: &mut dyn io::BufRead) -> Result<Option<Self>, pem::Error> {
57loop {
58match pem::from_buf(rd)? {
59Some((kind, data)) => match Self::from_kind(kind, data) {
60Some(item) => return Ok(Some(item)),
61None => continue,
62 },
6364None => return Ok(None),
65 }
66 }
67 }
6869fn from_slice(pem: &[u8]) -> Result<Option<(Self, &[u8])>, pem::Error> {
70let mut iter = <(pem::SectionKind, Vec<u8>) as pem::PemObject>::pem_slice_iter(pem);
7172for found in iter.by_ref() {
73match found {
74Ok((kind, data)) => match Self::from_kind(kind, data) {
75Some(item) => return Ok(Some((item, iter.remainder()))),
76None => continue,
77 },
78Err(err) => return Err(err.into()),
79 }
80 }
8182Ok(None)
83 }
8485fn from_kind(kind: pem::SectionKind, data: Vec<u8>) -> Option<Self> {
86use pem::SectionKind::*;
87match kind {
88 Certificate => Some(Self::X509Certificate(data.into())),
89 PublicKey => Some(Self::SubjectPublicKeyInfo(data.into())),
90 RsaPrivateKey => Some(Self::Pkcs1Key(data.into())),
91 PrivateKey => Some(Self::Pkcs8Key(data.into())),
92 EcPrivateKey => Some(Self::Sec1Key(data.into())),
93 Crl => Some(Self::Crl(data.into())),
94 Csr => Some(Self::Csr(data.into())),
95_ => None,
96 }
97 }
98}
99100/// Errors that may arise when parsing the contents of a PEM file
101///
102/// This differs from [`rustls_pki_types::pem::Error`] because it is `PartialEq`;
103/// it is retained for compatibility.
104#[derive(Debug, PartialEq)]
105pub enum Error {
106/// a section is missing its "END marker" line
107MissingSectionEnd {
108/// the expected "END marker" line that was not found
109end_marker: Vec<u8>,
110 },
111112/// syntax error found in the line that starts a new section
113IllegalSectionStart {
114/// line that contains the syntax error
115line: Vec<u8>,
116 },
117118/// base64 decode error
119Base64Decode(String),
120}
121122#[cfg(feature = "std")]
123impl From<Error> for io::Error {
124fn from(error: Error) -> Self {
125match error {
126 Error::MissingSectionEnd { end_marker } => io::Error::new(
127 ErrorKind::InvalidData,
128format!(
129"section end {:?} missing",
130 String::from_utf8_lossy(&end_marker)
131 ),
132 ),
133134 Error::IllegalSectionStart { line } => io::Error::new(
135 ErrorKind::InvalidData,
136format!(
137"illegal section start: {:?}",
138 String::from_utf8_lossy(&line)
139 ),
140 ),
141142 Error::Base64Decode(err) => io::Error::new(ErrorKind::InvalidData, err),
143 }
144 }
145}
146147impl From<pem::Error> for Error {
148fn from(error: pem::Error) -> Self {
149match error {
150 pem::Error::MissingSectionEnd { end_marker } => Error::MissingSectionEnd { end_marker },
151 pem::Error::IllegalSectionStart { line } => Error::IllegalSectionStart { line },
152 pem::Error::Base64Decode(str) => Error::Base64Decode(str),
153154// this is a necessary bodge to funnel any new errors into our existing type
155 // (to which we can add no new variants)
156other => Error::Base64Decode(format!("{other:?}")),
157 }
158 }
159}
160161/// Extract and decode the next PEM section from `input`
162///
163/// - `Ok(None)` is returned if there is no PEM section to read from `input`
164/// - Syntax errors and decoding errors produce a `Err(...)`
165/// - Otherwise each decoded section is returned with a `Ok(Some((Item::..., remainder)))` where
166/// `remainder` is the part of the `input` that follows the returned section
167pub fn read_one_from_slice(input: &[u8]) -> Result<Option<(Item, &[u8])>, Error> {
168 Item::from_slice(input).map_err(Into::into)
169}
170171/// Extract and decode the next PEM section from `rd`.
172///
173/// - Ok(None) is returned if there is no PEM section read from `rd`.
174/// - Underlying IO errors produce a `Err(...)`
175/// - Otherwise each decoded section is returned with a `Ok(Some(Item::...))`
176///
177/// You can use this function to build an iterator, for example:
178/// `for item in iter::from_fn(|| read_one(rd).transpose()) { ... }`
179#[cfg(feature = "std")]
180pub fn read_one(rd: &mut dyn io::BufRead) -> Result<Option<Item>, io::Error> {
181 Item::from_buf(rd).map_err(|err| match err {
182 pem::Error::Io(io) => io,
183 other => Error::from(other).into(),
184 })
185}
186187/// Extract and return all PEM sections by reading `rd`.
188#[cfg(feature = "std")]
189pub fn read_all(rd: &mut dyn io::BufRead) -> impl Iterator<Item = Result<Item, io::Error>> + '_ {
190 iter::from_fn(move || read_one(rd).transpose())
191}