Debian Codegraph @

src/cert.rs

raw symbols SCIP
1 use std::collections::HashMap;
2 use std::fmt;
3 use std::fs::File;
4 use std::io::Read;
5 use std::path::Path;
6
7 use super::error::{Error, ErrorKind, Result};
8 use super::keytype::KeyType;
9 use super::pubkey::PublicKey;
10 use super::reader::Reader;
11
12 use base64;
13 use base64::Engine;
14
15 /// Represents the different types a certificate can be.
16 #[derive(Debug, PartialEq)]
17 pub enum CertType {
18 /// Represents a user certificate.
19 User,
20
21 /// Represents a host certificate.
22 Host,
23 }
24
25 impl fmt::Display for CertType {
26 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27 match *self {
28 CertType::User => write!(f, "user certificate"),
29 CertType::Host => write!(f, "host certificate"),
30 }
31 }
32 }
33
34 /// A type which represents an OpenSSH certificate key.
35 /// Please refer to [PROTOCOL.certkeys] for more details about OpenSSH certificates.
36 /// [PROTOCOL.certkeys]: https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.certkeys?annotate=HEAD
37 #[derive(Debug)]
38 pub struct Certificate {
39 /// Type of key.
40 pub key_type: KeyType,
41
42 /// Cryptographic nonce.
43 pub nonce: Vec<u8>,
44
45 /// Public key part of the certificate.
46 pub key: PublicKey,
47
48 /// Serial number of certificate.
49 pub serial: u64,
50
51 /// Represents the type of the certificate.
52 pub cert_type: CertType,
53
54 /// Key identity.
55 pub key_id: String,
56
57 /// The list of valid principals for the certificate.
58 pub valid_principals: Vec<String>,
59
60 /// Time after which certificate is considered as valid.
61 pub valid_after: u64,
62
63 /// Time before which certificate is considered as valid.
64 pub valid_before: u64,
65
66 /// Critical options of the certificate. Generally used to
67 /// control features which restrict access.
68 pub critical_options: HashMap<String, String>,
69
70 /// Certificate extensions. Extensions are usually used to
71 /// enable features that grant access.
72 pub extensions: HashMap<String, String>,
73
74 /// The `reserved` field is currently unused and is ignored in this version of the protocol.
75 pub reserved: Vec<u8>,
76
77 /// Signature key contains the CA public key used to sign the certificate.
78 pub signature_key: PublicKey,
79
80 /// Signature of the certificate.
81 pub signature: Vec<u8>,
82
83 /// Associated comment, if any.
84 pub comment: Option<String>,
85 }
86
87 impl Certificate {
88 /// Reads an OpenSSH certificate from a given path.
89 ///
90 /// # Example
91 ///
92 /// ```rust
93 /// # use sshkeys;
94 /// # fn example() -> sshkeys::Result<()> {
95 /// let cert = sshkeys::Certificate::from_path("/path/to/id_ed25519-cert.pub")?;
96 /// # Ok(())
97 /// # }
98 /// ```
99 pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Certificate> {
100 let mut contents = String::new();
101 File::open(path)?.read_to_string(&mut contents)?;
102
103 Certificate::from_string(&contents)
104 }
105
106 /// Reads an OpenSSH certificate from a given string.
107 ///
108 /// # Example
109 ///
110 /// ```rust
111 /// # use sshkeys;
112 /// # fn example() -> sshkeys::Result<()> {
113 /// let cert = sshkeys::Certificate::from_string("ssh-rsa AAAAB3NzaC1yc2EAAAA...")?;
114 /// # Ok(())
115 /// # }
116 /// ```
117 pub fn from_string(s: &str) -> Result<Certificate> {
118 let mut iter = s.split_whitespace();
119
120 let kt_name = iter
121 .next()
122 .ok_or(Error::with_kind(ErrorKind::InvalidFormat))?;
123
124 let kt = KeyType::from_name(&kt_name)?;
125 if !kt.is_cert {
126 return Err(Error::with_kind(ErrorKind::NotCertificate));
127 }
128
129 let data = iter
130 .next()
131 .ok_or(Error::with_kind(ErrorKind::InvalidFormat))?;
132
133 let comment = iter.next().map(|v| String::from(v));
134 let decoded = base64::engine::general_purpose::STANDARD.decode(&data)?;
135 let mut reader = Reader::new(&decoded);
136
137 // Validate key types before reading the rest of the data
138 let kt_from_reader = reader.read_string()?;
139 if kt_name != kt_from_reader {
140 return Err(Error::with_kind(ErrorKind::KeyTypeMismatch));
141 }
142
143 let nonce = reader.read_bytes()?;
144 let key = PublicKey::from_reader(&kt_name, &mut reader)?;
145 let serial = reader.read_u64()?;
146
147 let cert_type = match reader.read_u32()? {
148 1 => CertType::User,
149 2 => CertType::Host,
150 n => return Err(Error::with_kind(ErrorKind::InvalidCertType(n))),
151 };
152
153 let key_id = reader.read_string()?;
154 let principals = reader.read_bytes().and_then(|v| read_principals(&v))?;
155 let valid_after = reader.read_u64()?;
156 let valid_before = reader.read_u64()?;
157 let critical_options = reader.read_bytes().and_then(|v| read_options(&v))?;
158 let extensions = reader.read_bytes().and_then(|v| read_options(&v))?;
159 let reserved = reader.read_bytes()?;
160 let signature_key = reader
161 .read_bytes()
162 .and_then(|v| PublicKey::from_bytes(&v))?;
163 let signature = reader.read_bytes()?;
164
165 let cert = Certificate {
166 key_type: kt,
167 nonce: nonce,
168 key: key,
169 serial: serial,
170 cert_type: cert_type,
171 key_id: key_id,
172 valid_principals: principals,
173 valid_after: valid_after,
174 valid_before: valid_before,
175 critical_options: critical_options,
176 extensions: extensions,
177 reserved: reserved,
178 signature_key: signature_key,
179 signature: signature,
180 comment: comment,
181 };
182
183 Ok(cert)
184 }
185 }
186
187 // Reads `option` values from a byte sequence.
188 // The `option` values are used to represent the `critical options` and
189 // `extensions` in an OpenSSH certificate key, which are represented as tuples
190 // containing the `name` and `data` values of type `string`.
191 // Some `options` are `flags` only (e.g. the certificate extensions) and the
192 // associated value with them is the empty string (""), while others are `string`
193 // options and have an associated value, which is a `string`.
194 // The `critical options` of a certificate are always `string` options, since they
195 // have an associated `string` value, which is embedded in a separate buffer, so
196 // in order to extract the associated value we need to read the buffer first and then
197 // read the `string` value itself.
198 fn read_options(buf: &[u8]) -> Result<HashMap<String, String>> {
199 let mut reader = Reader::new(&buf);
200 let mut options = HashMap::new();
201
202 // Use a `Reader` and loop until EOF is reached, so that we can
203 // read all options from the provided byte slice.
204 loop {
205 let name = match reader.read_string() {
206 Ok(v) => v,
207 Err(e) => match e.kind {
208 ErrorKind::UnexpectedEof => break,
209 _ => return Err(e),
210 },
211 };
212
213 // If we have a `string` option extract the value from the buffer,
214 // otherwise we have a `flag` option which is the `empty` string.
215 let value_buf = reader.read_bytes()?;
216 let value = if value_buf.len() > 0 {
217 Reader::new(&value_buf).read_string()?
218 } else {
219 "".to_string()
220 };
221
222 options.insert(name, value);
223 }
224
225 Ok(options)
226 }
227
228 // Reads the `valid principals` field of a certificate key.
229 // The `valid principals` are represented as a sequence of `string` values
230 // embedded in a buffer.
231 // This function reads the whole byte slice until EOF is reached in order to
232 // ensure all principals are read from the byte slice.
233 fn read_principals(buf: &[u8]) -> Result<Vec<String>> {
234 let mut reader = Reader::new(&buf);
235 let mut items = Vec::new();
236
237 loop {
238 let principal = match reader.read_string() {
239 Ok(v) => v,
240 Err(e) => match e.kind {
241 ErrorKind::UnexpectedEof => break,
242 _ => return Err(e),
243 },
244 };
245
246 items.push(principal);
247 }
248
249 Ok(items)
250 }