From ff1902fe4156ff070951a699c1768a524eda182b Mon Sep 17 00:00:00 2001 From: Sviatoslav Boichuk Date: Tue, 24 Sep 2024 09:47:46 +0300 Subject: [PATCH] Try to decode base64 certs/keys --- src/cgw_tls.rs | 60 ++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 16 deletions(-) diff --git a/src/cgw_tls.rs b/src/cgw_tls.rs index 7e011c3..d6c1208 100644 --- a/src/cgw_tls.rs +++ b/src/cgw_tls.rs @@ -1,10 +1,12 @@ use crate::cgw_app_args::CGWWSSArgs; use crate::cgw_errors::{collect_results, Error, Result}; +use base64::prelude::BASE64_STANDARD; +use base64::Engine; use eui48::MacAddress; use rustls_pki_types::{CertificateDer, PrivateKeyDer}; use std::fs; -use std::io::BufRead; +use std::io::{BufRead, Read}; use std::path::Path; use std::{fs::File, io::BufReader, str::FromStr, sync::Arc}; use tokio::net::TcpStream; @@ -20,34 +22,60 @@ use x509_parser::parse_x509_certificate; const CGW_TLS_CERTIFICATES_PATH: &str = "/etc/cgw/certs"; const CGW_TLS_NB_INFRA_CERTS_PATH: &str = "/etc/cgw/nb_infra/certs"; -pub async fn cgw_tls_read_certs(cert_file: &str) -> Result>> { - let file = match File::open(cert_file) { +async fn cgw_tls_read_file(file_path: &str) -> Result> { + let mut file = match File::open(file_path) { Ok(f) => f, Err(e) => { return Err(Error::Tls(format!( - "Failed to open TLS certificate file: {}. Error: {}", - cert_file, e + "Failed to open file: {}. Error: {}", + file_path, e ))); } }; - let mut reader = BufReader::new(file); - - collect_results(rustls_pemfile::certs(&mut reader)) -} - -pub async fn cgw_tls_read_private_key(private_key_file: &str) -> Result> { - let file = match File::open(private_key_file) { - Ok(f) => f, + let metadata = match fs::metadata(file_path) { + Ok(meta) => meta, Err(e) => { return Err(Error::Tls(format!( - "Failed to open TLS private key file: {}. Error: {}", - private_key_file, e + "Failed to read {} metadata. Error: {}", + file_path, e ))); } }; - let mut reader = BufReader::new(file); + let mut buffer = vec![0; metadata.len() as usize]; + if let Err(e) = file.read_exact(&mut buffer) { + return Err(Error::Tls(format!( + "Failed to read {} file. Error: {}", + file_path, e + ))); + } + + let decoded_buffer = { + if let Ok(d) = BASE64_STANDARD.decode(buffer.clone()) { + info!( + "Cert file {} is base64 encoded, trying to use decoded.", + file_path + ); + d + } else { + buffer + } + }; + + Ok(decoded_buffer) +} + +pub async fn cgw_tls_read_certs(cert_file: &str) -> Result>> { + let buffer = cgw_tls_read_file(cert_file).await?; + let mut reader = BufReader::new(buffer.as_slice()); + + collect_results(rustls_pemfile::certs(&mut reader)) +} + +pub async fn cgw_tls_read_private_key(private_key_file: &str) -> Result> { + let buffer = cgw_tls_read_file(private_key_file).await?; + let mut reader = BufReader::new(buffer.as_slice()); match rustls_pemfile::private_key(&mut reader) { Ok(ret_pk) => match ret_pk {