From 6d65c5ffc3dbd7ac80c1ada64c47f370b05d846c Mon Sep 17 00:00:00 2001 From: Delta1925 Date: Sat, 15 Apr 2023 18:58:46 +0200 Subject: [PATCH] Improve getting user email from cert --- .gitignore | 1 + src/errors.rs | 2 ++ src/utils.rs | 24 +++++++++++++++++------- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 5649d47..cb3e22b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /target /data +/logs /config.toml \ No newline at end of file diff --git a/src/errors.rs b/src/errors.rs index b5eac2e..e1f54b0 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -3,6 +3,8 @@ use thiserror::Error; #[derive(Error, Debug, Clone, Copy)] pub enum Error { + #[error("EC1: Cert is invalid")] + InvalidCert, #[error("EP1: Error while parsing cert")] ParseCert, #[error("EP2: Error while parsing an E-Mail address")] diff --git a/src/utils.rs b/src/utils.rs index 7525989..6001073 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -4,7 +4,7 @@ use crate::settings::SETTINGS; use flexi_logger::{style, DeferredNow, FileSpec, FlexiLoggerError, Logger, LoggerHandle, Record}; use rand::{distributions::Alphanumeric, thread_rng, Rng}; use sequoia_net::wkd::Url; -use sequoia_openpgp::{parse::Parse, Cert}; +use sequoia_openpgp::{parse::Parse, Cert, policy::NullPolicy}; use std::path::{Path, PathBuf}; #[macro_export] @@ -15,10 +15,15 @@ macro_rules! pending_path { } pub fn parse_pem(pemfile: &str) -> Result { - match sequoia_openpgp::Cert::from_bytes(pemfile.as_bytes()) { - Ok(cert) => Ok(cert), - Err(_) => Err(Error::ParseCert), + let cert = match sequoia_openpgp::Cert::from_bytes(pemfile.as_bytes()) { + Ok(cert) => cert, + Err(_) => return Err(Error::ParseCert), + }; + let policy = NullPolicy::new(); + if cert.with_policy(&policy, None).is_err() { + return Err(Error::InvalidCert) } + Ok(cert) } pub fn gen_random_token() -> String { @@ -27,9 +32,14 @@ pub fn gen_random_token() -> String { } pub fn get_email_from_cert(cert: &Cert) -> Result { - let userid_opt = match cert.userids().next() { - Some(userid_opt) => userid_opt, - None => return Err(Error::ParseCert), + let policy = NullPolicy::new(); + let validcert = match cert.with_policy(&policy, None) { + Ok(validcert) => validcert, + Err(_) => return Err(Error::InvalidCert) + }; + let userid_opt = match validcert.primary_userid() { + Ok(userid_opt) => userid_opt, + Err(_) => return Err(Error::ParseCert), }; let email_opt = match userid_opt.email() { Ok(email_opt) => email_opt,