Debian Codegraph @

src/pubkey.rs

raw symbols SCIP
1 use std::fmt;
2 use std::fs::File;
3 use std::io::{self, Read};
4 use std::path::Path;
5
6 use super::error::{Error, ErrorKind, Result};
7 use super::keytype::{KeyType, KeyTypeKind};
8 use super::reader::Reader;
9 use super::writer::Writer;
10
11 use base64;
12 use base64::Engine;
13
14 use sha2::{Digest, Sha256, Sha384, Sha512};
15
16 /// A type which represents the different kinds a public key can be.
17 #[derive(Clone, Debug, PartialEq)]
18 pub enum PublicKeyKind {
19 /// Represents an RSA public key.
20 Rsa(RsaPublicKey),
21
22 /// Represents a DSA public key.
23 Dsa(DsaPublicKey),
24
25 /// Represents an ECDSA public key.
26 Ecdsa(EcdsaPublicKey),
27
28 /// Represents an ED25519 public key.
29 Ed25519(Ed25519PublicKey),
30 }
31
32 /// RSA public key.
33 /// The format of RSA public keys is described in RFC 4253, section 6.6
34 #[derive(Clone, Debug, PartialEq)]
35 pub struct RsaPublicKey {
36 /// Exponent of key.
37 pub e: Vec<u8>,
38
39 /// Modulus of key.
40 pub n: Vec<u8>,
41 }
42
43 /// DSA public key.
44 /// The format of DSA public keys is described in RFC 4253, section 6.6
45 #[derive(Clone, Debug, PartialEq)]
46 pub struct DsaPublicKey {
47 /// Parameter `p`.
48 pub p: Vec<u8>,
49
50 /// Parameter `q`.
51 pub q: Vec<u8>,
52
53 /// Parameter `g`.
54 pub g: Vec<u8>,
55
56 /// Parameter `y`.
57 pub y: Vec<u8>,
58 }
59
60 /// Represents the different kinds of supported curves.
61 #[derive(Clone, Debug, PartialEq)]
62 pub enum CurveKind {
63 /// Represents a NIST P-256 curve.
64 Nistp256,
65
66 /// Represents a NIST P-384 curve.
67 Nistp384,
68
69 /// Represents a NIST P-521 curve.
70 Nistp521,
71 }
72
73 /// A type which represents a cryptographic curve.
74 #[derive(Clone, Debug, PartialEq)]
75 pub struct Curve {
76 /// The curve kind.
77 pub kind: CurveKind,
78
79 /// Curve identifier.
80 pub identifier: &'static str,
81 }
82
83 impl Curve {
84 /// Creates a new `Curve` from the given identifier.
85 ///
86 /// # Example
87 /// ```rust
88 /// # use sshkeys;
89 /// let curve = sshkeys::Curve::from_identifier("nistp256").unwrap();
90 /// assert_eq!(curve.kind, sshkeys::CurveKind::Nistp256);
91 /// ```
92 pub fn from_identifier(id: &str) -> Result<Curve> {
93 let curve = match id {
94 "nistp256" => Curve {
95 kind: CurveKind::Nistp256,
96 identifier: "nistp256",
97 },
98 "nistp384" => Curve {
99 kind: CurveKind::Nistp384,
100 identifier: "nistp384",
101 },
102 "nistp521" => Curve {
103 kind: CurveKind::Nistp521,
104 identifier: "nistp521",
105 },
106 _ => return Err(Error::with_kind(ErrorKind::UnknownCurve(id.to_string()))),
107 };
108
109 Ok(curve)
110 }
111 }
112
113 /// ECDSA public key.
114 /// The format of ECDSA public keys is described in RFC 5656, section 3.1.
115 #[derive(Clone, Debug, PartialEq)]
116 pub struct EcdsaPublicKey {
117 /// The curve being used.
118 pub curve: Curve,
119
120 /// The public key.
121 pub key: Vec<u8>,
122
123 /// Associated security key application, if any.
124 pub sk_application: Option<String>,
125 }
126
127 /// ED25519 public key.
128 /// The format of ED25519 public keys is described in https://tools.ietf.org/html/draft-bjh21-ssh-ed25519-02
129 #[derive(Clone, Debug, PartialEq)]
130 pub struct Ed25519PublicKey {
131 /// The public key.
132 pub key: Vec<u8>,
133
134 /// Associated security key application, if any.
135 pub sk_application: Option<String>,
136 }
137
138 /// A type which represents an OpenSSH public key.
139 #[derive(Clone, Debug, PartialEq)]
140 pub struct PublicKey {
141 /// Key type.
142 pub key_type: KeyType,
143
144 /// The kind of public key.
145 pub kind: PublicKeyKind,
146
147 /// Associated comment, if any.
148 pub comment: Option<String>,
149 }
150
151 impl fmt::Display for PublicKey {
152 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
153 let comment = match self.comment {
154 Some(ref c) => c,
155 None => "",
156 };
157
158 write!(
159 f,
160 "{} {} {}",
161 self.key_type,
162 base64::engine::general_purpose::STANDARD.encode(&self.encode()),
163 comment
164 )
165 }
166 }
167
168 /// The `FingerprintKind` enum represents the different fingerprint representation.
169 #[derive(Debug, PartialEq)]
170 pub enum FingerprintKind {
171 /// A kind used to represent the fingerprint using SHA256.
172 Sha256,
173
174 /// A kind used to represent the fingerprint using SHA384.
175 Sha384,
176
177 /// A kind used to represent the fingerprint using SHA512.
178 Sha512,
179 }
180
181 impl fmt::Display for FingerprintKind {
182 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
183 let kind = match *self {
184 FingerprintKind::Sha256 => "SHA256",
185 FingerprintKind::Sha384 => "SHA384",
186 FingerprintKind::Sha512 => "SHA512",
187 };
188
189 write!(f, "{}", kind)
190 }
191 }
192
193 /// A type that represents an OpenSSH public key fingerprint.
194 #[derive(Debug)]
195 pub struct Fingerprint {
196 /// The kind used to represent the fingerprint.
197 pub kind: FingerprintKind,
198
199 /// The computed fingerprint.
200 pub hash: String,
201 }
202
203 impl fmt::Display for Fingerprint {
204 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
205 write!(f, "{}:{}", self.kind, self.hash)
206 }
207 }
208
209 impl Fingerprint {
210 /// Computes the fingerprint of a byte sequence using a given fingerprint representation.
211 ///
212 /// This method computes a fingerprint the way OpenSSH does it and is generally being
213 /// used to compute the fingerprint of an already encoded OpenSSH public key.
214 ///
215 /// # Example
216 /// ```rust
217 /// # use sshkeys;
218 /// let fp = sshkeys::Fingerprint::compute(sshkeys::FingerprintKind::Sha256, "some data".as_bytes());
219 /// assert_eq!(fp.kind, sshkeys::FingerprintKind::Sha256);
220 /// assert_eq!(fp.hash, "EweZDmulyhRes16ZGCqb7EZTG8VN32VqYCx4D6AkDe4");
221 /// ```
222 pub fn compute<T: ?Sized + AsRef<[u8]>>(kind: FingerprintKind, data: &T) -> Fingerprint {
223 let digest = match kind {
224 FingerprintKind::Sha256 => Sha256::digest(&data.as_ref()).to_vec(),
225 FingerprintKind::Sha384 => Sha384::digest(&data.as_ref()).to_vec(),
226 FingerprintKind::Sha512 => Sha512::digest(&data.as_ref()).to_vec(),
227 };
228
229 let mut encoded = base64::engine::general_purpose::STANDARD.encode(&digest);
230
231 // Trim padding characters from end
232 let hash = match encoded.find('=') {
233 Some(offset) => encoded.drain(..offset).collect(),
234 None => encoded,
235 };
236
237 let fp = Fingerprint {
238 kind: kind,
239 hash: hash,
240 };
241
242 fp
243 }
244 }
245
246 impl PublicKey {
247 /// Reads an OpenSSH public key from a given path.
248 ///
249 /// # Examples
250 ///
251 /// ```rust
252 /// # fn example() -> sshkeys::Result<()> {
253 /// let key = sshkeys::PublicKey::from_path("/path/to/id_ed25519.pub")?;
254 /// # Ok(())
255 /// # }
256 /// ```
257 pub fn from_path<P: AsRef<Path>>(path: P) -> Result<PublicKey> {
258 let mut contents = String::new();
259 File::open(path)?.read_to_string(&mut contents)?;
260
261 PublicKey::from_string(&contents)
262 }
263
264 /// Reads an OpenSSH public key from a given string.
265 ///
266 /// # Examples
267 ///
268 /// ```rust
269 /// # use sshkeys;
270 /// let key = sshkeys::PublicKey::from_string("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHkbe7gwx7s0dlApEEzpUyOAPrzPLy4czEZw/sh8m8rd me@home").unwrap();
271 /// let fp = key.fingerprint();
272 /// assert_eq!(fp.hash, "ciQkdxjFUhk2E2vRkWJD9kB8pi+EneOkaCJJHNWzPC4");
273 /// ```
274 pub fn from_string(contents: &str) -> Result<PublicKey> {
275 // Ssh public keys are on a single line, so we need to remove any new lines now.
276 let contents = contents
277 .lines()
278 .next()
279 .ok_or(Error::with_kind(ErrorKind::InvalidFormat))?;
280
281 // Per man 8 sshd:
282 // """
283 // The optional comment field continues to the end of the line
284 // """
285 //
286 // This means we can't simply use str::split_whitespace since that can eat
287 // the comment field if the comment has spaces (which are valid).
288 // Additionally the function we *need* is currently nightly only.
289 //
290 // https://doc.rust-lang.org/std/str/struct.SplitWhitespace.html#method.remainder
291 //
292 // So this means we have to do this the hard way - we need to walk the string
293 // finding and splitting as we go. That's what the helper "split_whitespace" does
294 // for us.
295 let (kt_name, remainder) =
296 split_whitespace(contents).ok_or(Error::with_kind(ErrorKind::InvalidFormat))?;
297
298 // If we have the ability to split, this means we have a comment.
299 // If the split fails, this means we only have data.
300 let (data, comment) = split_whitespace(remainder)
301 .map(|(data, comment)| {
302 let comment = String::from(comment);
303
304 (data, Some(comment))
305 })
306 .unwrap_or(
307 // We need to trim the end here as the key may have trailing whitespace
308 // but no comment.
309 (remainder.trim_end(), None),
310 );
311
312 let kt = KeyType::from_name(&kt_name)?;
313
314 let decoded = base64::engine::general_purpose::STANDARD.decode(&data)?;
315 let mut reader = Reader::new(&decoded);
316
317 // Validate key type before reading rest of the data
318 let kt_from_reader = reader.read_string()?;
319 if kt_name != kt_from_reader {
320 return Err(Error::with_kind(ErrorKind::KeyTypeMismatch));
321 }
322
323 // Construct a new `PublicKey` value and preserve the `comment` value.
324 let k = PublicKey::from_reader(&kt_name, &mut reader)?;
325 let key = PublicKey {
326 key_type: kt,
327 kind: k.kind,
328 comment: comment,
329 };
330
331 Ok(key)
332 }
333
334 /// Reads a public key from a given byte sequence.
335 ///
336 /// The byte sequence is expected to be the base64 decoded body of the public key.
337 ///
338 /// # Example
339 ///
340 /// ```rust
341 /// # use sshkeys;
342 /// let data = vec![0, 0, 0, 11, 115, 115, 104, 45,
343 /// 101, 100, 50, 53, 53, 49, 57,
344 /// 0, 0, 0, 32, 121, 27, 123, 184,
345 /// 48, 199, 187, 52, 118, 80, 41, 16,
346 /// 76, 233, 83, 35, 128, 62, 188,
347 /// 207, 47, 46, 28, 204, 70, 112,
348 /// 254, 200, 124, 155, 202, 221];
349 ///
350 /// let key = sshkeys::PublicKey::from_bytes(&data).unwrap();
351 /// let fp = key.fingerprint();
352 /// assert_eq!(fp.hash, "ciQkdxjFUhk2E2vRkWJD9kB8pi+EneOkaCJJHNWzPC4");
353 /// ```
354 pub fn from_bytes<T: ?Sized + AsRef<[u8]>>(data: &T) -> Result<PublicKey> {
355 let mut reader = Reader::new(&data);
356 let kt_name = reader.read_string()?;
357
358 PublicKey::from_reader(&kt_name, &mut reader)
359 }
360
361 // This function is used for extracting a public key from an existing reader, e.g.
362 // we already have a reader for reading an OpenSSH certificate key and
363 // we want to extract the public key information from it.
364 pub(crate) fn from_reader(kt_name: &str, reader: &mut Reader) -> Result<PublicKey> {
365 let kt = KeyType::from_name(&kt_name)?;
366
367 let kind = match kt.kind {
368 KeyTypeKind::Rsa | KeyTypeKind::RsaCert => {
369 let k = RsaPublicKey {
370 e: reader.read_mpint()?,
371 n: reader.read_mpint()?,
372 };
373
374 PublicKeyKind::Rsa(k)
375 }
376 KeyTypeKind::Dsa | KeyTypeKind::DsaCert => {
377 let k = DsaPublicKey {
378 p: reader.read_mpint()?,
379 q: reader.read_mpint()?,
380 g: reader.read_mpint()?,
381 y: reader.read_mpint()?,
382 };
383
384 PublicKeyKind::Dsa(k)
385 }
386 KeyTypeKind::Ecdsa | KeyTypeKind::EcdsaCert | KeyTypeKind::EcdsaSk => {
387 let identifier = reader.read_string()?;
388 let curve = Curve::from_identifier(&identifier)?;
389 let key = reader.read_bytes()?;
390 let sk_application = match kt.kind {
391 KeyTypeKind::EcdsaSk => Some(reader.read_string()?),
392 _ => None,
393 };
394 let k = EcdsaPublicKey {
395 curve: curve,
396 key: key,
397 sk_application: sk_application,
398 };
399
400 PublicKeyKind::Ecdsa(k)
401 }
402 KeyTypeKind::Ed25519 | KeyTypeKind::Ed25519Cert | KeyTypeKind::Ed25519Sk => {
403 let key = reader.read_bytes()?;
404 let sk_application = match kt.kind {
405 KeyTypeKind::Ed25519Sk => Some(reader.read_string()?),
406 _ => None,
407 };
408 let k = Ed25519PublicKey {
409 key: key,
410 sk_application: sk_application,
411 };
412
413 PublicKeyKind::Ed25519(k)
414 }
415 };
416
417 let key = PublicKey {
418 key_type: kt,
419 kind: kind,
420 comment: None,
421 };
422
423 Ok(key)
424 }
425
426 /// Returns the number of bits of the public key.
427 ///
428 /// # Example
429 ///
430 /// ```rust
431 /// # use sshkeys;
432 /// let key = sshkeys::PublicKey::from_string("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHkbe7gwx7s0dlApEEzpUyOAPrzPLy4czEZw/sh8m8rd me@home").unwrap();
433 /// assert_eq!(key.bits(), 256);
434 /// ```
435 pub fn bits(&self) -> usize {
436 match self.kind {
437 // For RSA public key the size of the key is the number of bits of the modulus
438 PublicKeyKind::Rsa(ref k) => k.n.len() * 8,
439 // For DSA public keys the size of the key is the number of bits of the `p` parameter
440 PublicKeyKind::Dsa(ref k) => k.p.len() * 8,
441 // ECDSA key size depends on the curve
442 PublicKeyKind::Ecdsa(ref k) => match k.curve.kind {
443 CurveKind::Nistp256 => 256,
444 CurveKind::Nistp384 => 384,
445 CurveKind::Nistp521 => 521,
446 },
447 // ED25519 key size is 256 bits
448 // https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.5
449 PublicKeyKind::Ed25519(_) => 256,
450 }
451 }
452
453 /// Encodes the public key in an OpenSSH compatible format.
454 ///
455 /// # Example
456 /// ```rust
457 /// # use sshkeys;
458 /// let key = sshkeys::PublicKey::from_string("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHkbe7gwx7s0dlApEEzpUyOAPrzPLy4czEZw/sh8m8rd me@home").unwrap();
459 /// assert_eq!(key.encode(), vec![0, 0, 0, 11, 115, 115, 104, 45, 101, 100, 50, 53, 53, 49, 57, 0, 0, 0, 32, 121, 27, 123, 184, 48, 199, 187, 52, 118, 80, 41, 16, 76, 233, 83, 35, 128, 62, 188, 207, 47, 46, 28, 204, 70, 112, 254, 200, 124, 155, 202, 221]);
460 /// ```
461 pub fn encode(&self) -> Vec<u8> {
462 let mut w = Writer::new();
463
464 w.write_string(self.key_type.plain);
465 match self.kind {
466 PublicKeyKind::Rsa(ref k) => {
467 w.write_mpint(&k.e);
468 w.write_mpint(&k.n);
469 }
470 PublicKeyKind::Dsa(ref k) => {
471 w.write_mpint(&k.p);
472 w.write_mpint(&k.q);
473 w.write_mpint(&k.g);
474 w.write_mpint(&k.y);
475 }
476 PublicKeyKind::Ecdsa(ref k) => {
477 w.write_string(&k.curve.identifier);
478 w.write_bytes(&k.key);
479 if self.key_type.kind == KeyTypeKind::EcdsaSk {
480 w.write_string(&k.sk_application.as_ref().unwrap());
481 }
482 }
483 PublicKeyKind::Ed25519(ref k) => {
484 w.write_bytes(&k.key);
485 if self.key_type.kind == KeyTypeKind::Ed25519Sk {
486 w.write_string(&k.sk_application.as_ref().unwrap());
487 }
488 }
489 }
490
491 w.into_bytes()
492 }
493
494 /// Computes the fingerprint of the public key using the
495 /// default OpenSSH fingerprint representation with SHA256.
496 ///
497 /// # Example
498 ///
499 /// ```rust
500 /// # use sshkeys;
501 /// # fn example() -> sshkeys::Result<()> {
502 /// let key = sshkeys::PublicKey::from_path("/path/to/id_ed25519.pub")?;
503 /// let fp = key.fingerprint();
504 /// println!("{}", fp.hash);
505 /// # Ok(())
506 /// # }
507 /// ```
508 pub fn fingerprint(&self) -> Fingerprint {
509 self.fingerprint_with(FingerprintKind::Sha256)
510 }
511
512 /// Computes the fingerprint of the public key using a given
513 /// fingerprint representation.
514 ///
515 /// # Example
516 ///
517 /// ```rust
518 /// # use sshkeys;
519 /// # fn example() -> sshkeys::Result<()> {
520 /// let key = sshkeys::PublicKey::from_path("/path/to/id_ed25519.pub").unwrap();
521 /// let sha512fp = key.fingerprint_with(sshkeys::FingerprintKind::Sha512);
522 /// println!("{}", sha512fp.hash);
523 /// # Ok(())
524 /// # }
525 /// ```
526 pub fn fingerprint_with(&self, kind: FingerprintKind) -> Fingerprint {
527 Fingerprint::compute(kind, &self.encode())
528 }
529
530 /// Writes the public key to a given writer.
531 ///
532 /// # Example
533 /// ```rust
534 /// # use sshkeys;
535 /// use std::fs::File;
536 /// # fn example() -> sshkeys::Result<()> {
537 /// let key = sshkeys::PublicKey::from_string("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA...")?;
538 /// let mut file = File::create("/path/to/id_ed25519.pub")?;
539 /// key.write(&mut file).unwrap();
540 /// # Ok(())
541 /// # }
542 /// ```
543 pub fn write<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
544 let encoded = self.encode();
545 let data = base64::engine::general_purpose::STANDARD.encode(&encoded);
546 match self.comment {
547 Some(ref c) => w.write_fmt(format_args!("{} {} {}\n", self.key_type.name, data, c)),
548 None => w.write_fmt(format_args!("{} {}\n", self.key_type.name, data)),
549 }
550 }
551 }
552
553 // "We have SplitWhitespace at home".
554 // https://doc.rust-lang.org/std/str/struct.SplitWhitespace.html#method.remainder
555 fn split_whitespace(s: &str) -> Option<(&str, &str)> {
556 // Find the first whitespace index.
557 let whitespace_start = s.find(char::is_whitespace)?;
558 let (left, right) = s.split_at_checked(whitespace_start)?;
559
560 // Now find the start of right, skipping over a range of whitespace.
561 let non_whitespace_start = right.find(|c: char| !c.is_whitespace())?;
562 let (_, right) = right.split_at_checked(non_whitespace_start)?;
563
564 Some((left, right))
565 }