sshcerts 0.14.0

A library for parsing, verifying, and creating SSH Certificates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
use std::fmt;
use std::fs::File;
use std::io::Read;
use std::path::Path;

use chrono::prelude::Local;
use chrono::{NaiveDate, NaiveDateTime, NaiveTime};

use super::pubkey::PublicKey;
use crate::{error::Error, Result};

/// A type to represent the different kinds of errors.
#[derive(Debug)]
pub enum AllowedSignerParsingError {
    /// Parsing failed because of double quotes
    InvalidQuotes,
    /// Parsing failed because principals was missing
    MissingPrincipals,
    /// Principals is invalid
    InvalidPrincipals,
    /// Public key data is missing
    MissingKey,
    /// Some option was specified twice
    DuplicateOptions(String),
    /// An option has invalid format
    InvalidOption(String),
    /// Invalid key
    InvalidKey,
    /// Invalid timestamp
    InvalidTimestamp,
    /// valid-before and valid-after are conflicting
    InvalidTimestamps,
    /// Unexpected end of allowed signer
    UnexpectedEnd,
}

impl fmt::Display for AllowedSignerParsingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AllowedSignerParsingError::InvalidQuotes => write!(f, "error parsing quotes"),
            AllowedSignerParsingError::MissingPrincipals => write!(f, "missing principals"),
            AllowedSignerParsingError::InvalidPrincipals => write!(f, "invalid principals"),
            AllowedSignerParsingError::MissingKey => write!(f, "missing public key data"),
            AllowedSignerParsingError::DuplicateOptions(ref v) => write!(f, "option {} specified more than once", v),
            AllowedSignerParsingError::InvalidOption(ref v) => write!(f, "invalid option {}", v),
            AllowedSignerParsingError::InvalidKey => write!(f, "invalid public key"),
            AllowedSignerParsingError::InvalidTimestamp => write!(f, "invalid timestamp"),
            AllowedSignerParsingError::InvalidTimestamps => write!(f, "conflicting valid-before and valid-after options"),
            AllowedSignerParsingError::UnexpectedEnd => write!(f, "unexpected data at the end"),
        }
    }
}

/// A type which represents an allowed signer entry.
/// Please refer to [ssh-keygen-1.ALLOWED_SIGNERS] for more details about the format.
/// [ssh-keygen-1.ALLOWED_SIGNERS]: https://man.openbsd.org/ssh-keygen.1#ALLOWED_SIGNERS
#[derive(Debug, PartialEq, Eq)]
pub struct AllowedSigner {
    /// A list of principals, each in the format USER@DOMAIN.
    pub principals: Vec<String>,

    /// Indicates that this key is accepted as a CA.
    pub cert_authority: bool,

    /// Specifies a list of namespaces that are accepted for this key.
    pub namespaces: Option<Vec<String>>,

    /// UNIX timestamp at or after which the key is valid.
    pub valid_after: Option<i64>,

    /// UNIX timestamp at or before which the key is valid.
    pub valid_before: Option<i64>,

    /// Public key of the entry.
    pub key: PublicKey,
}

/// A type which represents a collection of allowed signer entries.
/// Please refer to [ssh-keygen-1.ALLOWED_SIGNERS] for more details about the format.
/// [ssh-keygen-1.ALLOWED_SIGNERS]: https://man.openbsd.org/ssh-keygen.1#ALLOWED_SIGNERS
#[derive(Debug, PartialEq, Eq)]
pub struct AllowedSigners(pub Vec<AllowedSigner>);

impl AllowedSigner {
    /// Parse an allowed signer entry from a given string.
    ///
    /// # Example
    ///
    /// ```rust
    /// use sshcerts::ssh::AllowedSigner;
    ///
    /// let allowed_signer = AllowedSigner::from_string(concat!(
    ///     "user@domain.tld ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBGJe",
    ///     "+IDGRhlQdDp+/AIsTXGaVhWaQUbHJwqLDlQIh7V4xatO6E/4Uva+f70WzxgM7xHPGUqafqNAcxxVBP4jkx3HVDRSr7C3",
    ///     "NVBpr0ZaKXu/hFiCo/4kry4H5MGMEvKATA=="
    /// )).unwrap();
    /// println!("{:?}", allowed_signer);
    /// ```
    pub fn from_string(s: &str) -> Result<AllowedSigner> {
        let mut tokenizer = AllowedSignerSplitter::new(s);

        let principals = tokenizer.next(true)?
            .ok_or(Error::InvalidAllowedSigner(AllowedSignerParsingError::MissingPrincipals))?;
        let principals = principals.trim_matches('"');
        let principals: Vec<String> = principals.split(',')
            .map(|s| s.to_string())
            .collect();
        if principals.iter().any(|p| p.is_empty()) {
            return Err(Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidPrincipals));
        }

        let mut cert_authority = false;
        let mut namespaces = None;
        let mut valid_after = None;
        let mut valid_before = None;

        let kt = loop {
            let option = tokenizer.next(false)?
                .ok_or(Error::InvalidAllowedSigner(AllowedSignerParsingError::MissingKey))?;

            let (option_key, option_value) = match option.split_once('=') {
                Some(v) => v,
                None => (option.as_str(), ""),
            };
            let option_value = option_value.trim_matches('"');
            if option_value.contains("\"") {
                return Err(Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidQuotes));
            }

            match option_key.to_lowercase().as_str() {
                "cert-authority" => cert_authority = true,
                "namespaces" => {
                    if namespaces.is_some() {
                        return Err(
                            Error::InvalidAllowedSigner(AllowedSignerParsingError::DuplicateOptions("namespaces".to_string()))
                        );
                    }

                    let namespaces_value: Vec<&str> = option_value.split(',')
                        .filter(|e| !e.is_empty())
                        .collect();
                    namespaces = Some(
                        namespaces_value.iter()
                            .map(|s| s.to_string())
                            .collect()
                    );
                },
                "valid-after" => {
                    if valid_after.is_some() {
                        return Err(
                            Error::InvalidAllowedSigner(AllowedSignerParsingError::DuplicateOptions("valid-after".to_string()))
                        );
                    }
                    valid_after = Some(parse_timestamp(option_value)
                        .map_err(
                            |_| Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidOption("valid-after".to_string())))?
                        );
                },
                "valid-before" => {
                    if valid_before.is_some() {
                        return Err(
                            Error::InvalidAllowedSigner(AllowedSignerParsingError::DuplicateOptions("valid-before".to_string()))
                        );
                    }
                    valid_before = Some(parse_timestamp(option_value)
                        .map_err(
                            |_| Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidOption("valid-before".to_string())))?
                        );
                },
                // If option_key does not match any valid option, we test if it's the key data
                _ => break option,
            };
        };

        let key_data = tokenizer.next(false)?
            .ok_or(Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidKey))?;

        let key = PublicKey::from_string(format!("{} {}", kt, key_data).as_str())
            .map_err(|_| Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidKey))?;

        // Timestamp sanity check
        if let (Some(valid_before), Some(valid_after)) = (&valid_before, &valid_after) {
            if valid_before <= valid_after {
                return Err(
                    Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidTimestamps),
                );
            }
        }

        // After key data, there must be only comment or nothing
        if !tokenizer.is_empty_after_trim() {
            return Err(
                Error::InvalidAllowedSigner(AllowedSignerParsingError::UnexpectedEnd),
            );
        }

        Ok(AllowedSigner{
            principals,
            cert_authority,
            namespaces,
            valid_after,
            valid_before,
            key,
        })
    }
}

impl fmt::Display for AllowedSigner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut output = String::new();

        output.push_str(&self.principals.join(","));
        
        if self.cert_authority {
            output.push_str(" cert-authority");
        }

        if let Some(ref namespaces) = self.namespaces {
            output.push_str(&format!(" namespaces={}", namespaces.join(",")));
        }

        if let Some(ref valid_after) = self.valid_after {
            output.push_str(&format!(" valid-after={}", valid_after));
        }

        if let Some(ref valid_before) = self.valid_before {
            output.push_str(&format!(" valid-before={}", valid_before));
        }

        output.push_str(&format!(" {}", self.key));

        write!(f, "{}", output)
    }
}

impl AllowedSigners {
    /// Reads AllowedSigners from a given path.
    ///
    /// # Example
    ///
    /// ```rust
    /// use sshcerts::ssh::AllowedSigners;
    /// fn example() {
    ///     let allowed_signers = AllowedSigners::from_path("/path/to/allowed_signers").unwrap();
    ///     println!("{:?}", allowed_signers);
    /// }
    /// ```
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<AllowedSigners> {
        let mut contents = String::new();
        File::open(path)?.read_to_string(&mut contents)?;

        AllowedSigners::from_string(&contents)
    }

    /// Parse a collection of allowed signers from a given string.
    ///
    /// # Example
    ///
    /// ```rust
    /// use sshcerts::ssh::AllowedSigners;
    ///
    /// let allowed_signers = AllowedSigners::from_string(concat!(
    ///     "user@domain.tld ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBGJe",
    ///     "+IDGRhlQdDp+/AIsTXGaVhWaQUbHJwqLDlQIh7V4xatO6E/4Uva+f70WzxgM7xHPGUqafqNAcxxVBP4jkx3HVDRSr7C3",
    ///     "NVBpr0ZaKXu/hFiCo/4kry4H5MGMEvKATA==\n",
    ///     "user@domain.tld ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBGJe",
    ///     "+IDGRhlQdDp+/AIsTXGaVhWaQUbHJwqLDlQIh7V4xatO6E/4Uva+f70WzxgM7xHPGUqafqNAcxxVBP4jkx3HVDRSr7C3",
    ///     "NVBpr0ZaKXu/hFiCo/4kry4H5MGMEvKATA==\n"
    /// )).unwrap();
    /// println!("{:?}", allowed_signers);
    /// ```
    pub fn from_string(s: &str) -> Result<AllowedSigners> {
        let mut allowed_signers = Vec::new();

        for (line_number, line) in s.lines().enumerate() {
            let line = line.trim();
            if line.is_empty() || line.starts_with("#") {
                continue;
            }
            let allowed_signer = match AllowedSigner::from_string(line) {
                Ok(v) => v,
                Err(Error::InvalidAllowedSigner(e)) => {
                    return Err(Error::InvalidAllowedSigners(e, line_number));
                },
                Err(_) => {
                    return Err(Error::ParsingError);
                },
            };
            allowed_signers.push(allowed_signer);
        }

        Ok(AllowedSigners(allowed_signers))
    }
}

/// A type used to split the allowed signer segments, abstracting out the handling of double quotes.
/// The splitter is highly aware of the allowed_signer format and will catch certain invalid
/// formats.
///
/// For example: "principals   option1=\"value1   value2\" option2 option3=value kt key_data" is split into
/// ["principals", "option1=\"value1   value2\"", "option2", "option3=value", "kt", "key_data"]
struct AllowedSignerSplitter {
    /// A buffer of remaining tokens in reverse order.
    buffer: Vec<String>,
}

impl AllowedSignerSplitter {
    /// Split the string by delimiters but keep the delimiters.
    fn new(s: &str) -> Self {
        let mut buffer = Vec::new();
        let mut last = 0;

        for (index, matched) in s.match_indices([' ', '"', '#']) {
            // Push the new text before the delimiter
            if last != index {
                buffer.push(s[last..index].to_owned());
            }
            // Push the delimiter
            buffer.push(matched.to_owned());
            last = index + matched.len();
        }

        // Push the remaining text
        if last < s.len() {
            buffer.push(s[last..].to_owned());
        }

        // We parse from left to right so reversing allow us to use Vec's last() and pop()
        buffer.reverse();

        Self { buffer }
    }

    fn is_empty_after_trim(&mut self) -> bool {
        self.trim();
        return self.buffer.is_empty();
    }

    /// Get the next part that is not an option (principals, key)
    /// If opening_quotes_allowed is set to false, we reject the next token if it starts with ".
    fn next(&mut self, opening_quotes_allowed: bool) -> Result<Option<String>> {
        if self.is_empty_after_trim() {
            return Ok(None);
        }

        // If the next token starts with a double quote, then the closing double quote is also
        // the end of the token
        if self.buffer[0] == "\"" {
            if opening_quotes_allowed {
                return self.split_quote().map(|v| Some(v));
            } else {
                return Err(Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidQuotes));
            }
        }

        // If the next token doesn't start with a double quote, the token can represent an option.
        // Only an option token can contain double quotes in the middle (e.g. a="b c").
        // If we don't see any double quote in the token, we greedily parse the token until the
        // next whitespace.
        let mut s = String::new();
        while let Some(last) = self.buffer.pop() {
            if [" ", "\"", "#"].contains(&last.as_str()) {
                self.buffer.push(last);
                break;
            }

            s.push_str(&last);
        }

        // This should only apply to options
        if let Some(last) = self.buffer.last() {
            if last == "\"" {
                s.push_str(self.split_quote()?.as_str());

                // After the double quotes in the option token, there can only be nothing, a
                // whitespace, or a pound
                if let Some(last) = self.buffer.last() {
                    if ![" ", "#"].contains(&last.as_str()) {
                        return Err(Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidQuotes));
                    }
                }
            }
        }

        Ok(Some(s))
    }

    /// Trim comment and whitespaces
    fn trim(&mut self) {
        while let Some(last) = self.buffer.last(){
            match last.as_str() {
                " " => {
                    self.buffer.pop();
                },
                // Comment detected
                "#" => {
                    self.buffer.clear()
                },
                _ => break,
            };
        }
    }

    /// Extract content inside the double quotes.
    /// This function assumes buffer starst with a ".
    fn split_quote(&mut self) -> Result<String> {
        match self.buffer.pop() {
            Some(v) => {
                if v != "\"" {
                    return Err(Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidQuotes));
                }
            },
            None => return Err(Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidQuotes)),
        }

        let mut s = String::from("\"");
        loop {
            let token = self.buffer.pop()
                .ok_or(Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidQuotes))?;
            s.push_str(&token);
            if token == "\"" {
                break;
            }
        }

        Ok(s)
    }
}

/// Parse a string into a u64 representing a timestamp.
/// The timestamp has format YYYYMMDD[HHMM[SS]][Z]
/// The timestamp can be enclosed by quotation marks.
fn parse_timestamp(s: &str) -> Result<i64> {
    let mut s = s.trim_matches('"');
    let is_utc = s.ends_with('Z');
    if s.len() % 2 == 1 && !is_utc {
        return Err(Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidTimestamp));
    }
    if is_utc {
        s = s.trim_end_matches('Z');
    }
    let datetime = match s.len() {
        8 => {
            let date = NaiveDate::parse_from_str(s, "%Y%m%d")
                .map_err(|_| Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidTimestamp))?;
            date.and_time(NaiveTime::from_hms_opt(0, 0, 0).expect("initializing NaiveTime from constants should not fail"))
        },
        12 => {
            NaiveDateTime::parse_from_str(s, "%Y%m%d%H%M")
                .map_err(|_| Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidTimestamp))?
        },
        14 => {
            NaiveDateTime::parse_from_str(s, "%Y%m%d%H%M%S")
                .map_err(|_| Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidTimestamp))?
        },
        _ => return Err(Error::InvalidAllowedSigner(AllowedSignerParsingError::InvalidTimestamp)),
    };

    let timestamp = if is_utc {
        datetime.and_utc()
            .timestamp()
    } else {
        datetime.and_local_timezone(Local)
            .unwrap()
            .timestamp()
    };

    Ok(timestamp)
}