diff --git a/Cargo.toml b/Cargo.toml index 12b867c..e346613 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,8 +11,9 @@ hyper = { version = "0.14", features = ["full"] } tokio = { version = "1", features = ["full"] } tokio-test = "0.4.2" hyper-tls = "0.5.0" -cookie = "0.15.1" serde = { version = "1", features = ["derive"] } serde_json = "1" sha1 = { version = "0.6", features = ["std"] } - +openssl = "0.10.38" +walkdir = "2.3.2" +publicsuffix = "1.3.1" diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..218864e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM rust:latest AS builder + +WORKDIR /root + +COPY . . + +RUN cargo build --release + +FROM debian:stable-slim + +RUN apt update && apt install -y ca-certificates openssl && rm -rf /var/lib/apt/lists/* + +COPY --from=builder /root/target/release/tlsa /root/tlsa + +CMD ["/root/tlsa"] diff --git a/src/main.rs b/src/main.rs index 4db09ad..e8bbd70 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,37 +1,70 @@ -use std::time::{UNIX_EPOCH, SystemTime}; use hyper_tls::HttpsConnector; -use hyper::{Client, Method}; -use serde_json::json; -use crate::utils::{body_to_str, build_request}; +use hyper::Client; +use walkdir::WalkDir; +use crate::{utils::{OVHClient, get_delta}, records::{get_all_records_from_zone, refresh_zone, get_records_from_zone, Record}}; +use publicsuffix::List; +use std::fs; mod utils; +mod records; #[tokio::main] async fn main() { let client = Client::builder().build::<_, hyper::Body>(HttpsConnector::new()); - let application_key = ""; - let application_secret = ""; - let consumer_key = ""; + let list = List::fetch().unwrap(); + let interesting_records = vec!["A", "AAAA", "MX", "CNAME"]; - let req = build_request(application_key, application_secret, consumer_key, - &Method::GET, "https://eu.api.ovh.com/1.0/auth/time", "", 0); - let res = client.request(req).await.unwrap(); - let s = res.status(); - assert!(s.is_success()); - let b = body_to_str(res.into_body()).await.parse::().unwrap(); - let delta = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64 - b; - println!("Delta is {}", delta); + let base_cert_dir = "/etc/nginx/certs/"; + let mut ovh_client = OVHClient { + app_key: "".to_string(), + app_secret: "".to_string(), + consumer_key: "".to_string(), + endpoint: "https://eu.api.ovh.com/1.0".to_string(), + delta: 0 + }; - let req = build_request(application_key, application_secret, consumer_key, - &Method::GET, "https://eu.api.ovh.com/1.0/domain/zone/{zone}/", "", delta); - let res = client.request(req).await.unwrap(); - println!("{} - {}", res.status(), body_to_str(res.into_body()).await); + ovh_client.delta = get_delta(&ovh_client, &client).await; + println!("Delta time is {}", ovh_client.delta); + println!("Sentinel started."); - - let req = build_request(application_key, application_secret, consumer_key, - &Method::POST, "https://eu.api.ovh.com/1.0/domain/zone/{zone}/record", - &json!({"fieldType" : "TXT", "subDomain": "XXXXXX", "target": "XXXXXXXXXXXXXXX"}).to_string(), delta); - let res = client.request(req).await.unwrap(); - println!("{} - {}", res.status(), body_to_str(res.into_body()).await); + for entry in WalkDir::new(base_cert_dir).into_iter().filter_map(|e| e.ok()) { + if !entry.path().ends_with("cert.pem") { continue; } + println!("Found certificate! Located at '{}'.", entry.path().display()); + let domain = entry.path().parent().unwrap() + .strip_prefix(base_cert_dir).unwrap().to_str().unwrap(); + let parsed_domain = list.parse_domain(domain).unwrap(); + let zone = parsed_domain.root().unwrap(); + let subdomain = domain.strip_suffix(zone).unwrap().strip_suffix(".").unwrap_or(""); + println!("Computing domain '{}', which has domain '{}' and subdomain '{}'.", + domain, zone, subdomain); + let records = get_all_records_from_zone(&ovh_client, &client, zone, subdomain) + .await; + if !records.iter().any(|r| interesting_records.contains(&r.field_type.as_str())) { + println!("\tDomain '{}' has no known interesting record. Skipping.", domain); + let tlsa_records_mx = get_records_from_zone(&ovh_client, &client, zone, "TLSA", format!("_587._tcp{}{}", if subdomain.is_empty() { "" } else { "." }, subdomain).as_str()).await; + let tlsa_records_site = get_records_from_zone(&ovh_client, &client, zone, "TLSA", format!("_443._tcp{}{}", if subdomain.is_empty() { "" } else { "." }, subdomain).as_str()).await; + println!("\tFound {} tlsa records associated with this domain.", tlsa_records_site.len() + tlsa_records_mx.len()); + // DELETE DANE RECORD IF FOUND ANY + println!(); + continue; + } + let certificate = fs::read_to_string(entry.path().to_str().unwrap()).expect("Something went wrong reading the file"); + let x509cert = openssl::x509::X509::from_pem(certificate.as_bytes()).unwrap(); + if records.iter().any(|r| r.field_type == "A" || r.field_type == "AAAA" || r.field_type == "CNAME") { + println!("\tDomain '{}' is associated with website.", domain); + let tlsa_records = get_records_from_zone(&ovh_client, &client, zone, "TLSA", format!("_443._tcp{}{}", if subdomain.is_empty() { "" } else { "." }, subdomain).as_str()).await; + println!("\tFound {} tlsa records associated with domain '{}'.", tlsa_records.len(), format!("_443._tcp.{}", subdomain).as_str()); + // PUT IF NOT MATCHING + // POST IF NONE + } + if records.iter().any(|r| r.field_type == "MX" && r.sub_domain == subdomain) { + println!("\tDomain '{}' is associated with mail.", domain); + let tlsa_records = get_records_from_zone(&ovh_client, &client, zone, "TLSA", format!("_587._tcp{}{}", if subdomain.is_empty() { "" } else { "." }, subdomain).as_str()).await; + println!("\tFound {} tlsa records associated with this domain.", tlsa_records.len()); + // PUT IF NOT MATCHING + // POST IF NONE + } + println!(); + } } diff --git a/src/records.rs b/src/records.rs new file mode 100644 index 0000000..d425a26 --- /dev/null +++ b/src/records.rs @@ -0,0 +1,102 @@ +use hyper::{Method, Client, client::HttpConnector}; +use hyper_tls::HttpsConnector; +use serde::{Deserialize, Serialize}; +use serde_json::{from_str, json}; +use crate::utils::{OVHClient, build_request, body_to_str}; + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct Record { + #[serde(rename = "subDomain")] + pub sub_domain: String, + pub target: String, + #[serde(rename = "fieldType")] + pub field_type: String, + pub ttl: u64, + #[serde(skip_serializing)] + pub id: u64 +} + + +pub async fn get_record_from_zone(ovh_client: &OVHClient, + client: &Client>, + zone: &str, id: u64) -> Record { + let req = build_request(ovh_client, &Method::GET, + format!("/domain/zone/{}/record/{}", + zone, id).as_str(), ""); + let res = client.request(req).await.unwrap(); + assert!(res.status().is_success()); + return from_str(body_to_str(res.into_body()).await.as_str()).unwrap(); +} + +pub async fn get_records_from_zone(ovh_client: &OVHClient, + client: &Client>, + zone: &str, field: &str, subdomain: &str) -> Vec { + let req = build_request(ovh_client, &Method::GET, + format!("/domain/zone/{}/record?fieldType={}&subDomain={}", + zone, field, subdomain).as_str(), ""); + let res = client.request(req).await.unwrap(); + assert!(res.status().is_success()); + let array: Vec = from_str(body_to_str(res.into_body()).await.as_str()).unwrap(); + let mut records = vec![]; + for i in array { + records.push(get_record_from_zone(ovh_client, client, zone, i).await); + } + return records; +} + +pub async fn get_all_records_from_zone(ovh_client: &OVHClient, + client: &Client>, + zone: &str, subdomain: &str) -> Vec { + let req = build_request(ovh_client, &Method::GET, + format!("/domain/zone/{}/record?&subDomain={}", + zone, subdomain).as_str(), ""); + let res = client.request(req).await.unwrap(); + assert!(res.status().is_success()); + let array: Vec = from_str(body_to_str(res.into_body()).await.as_str()).unwrap(); + let mut records = vec![]; + for i in array { + records.push(get_record_from_zone(ovh_client, client, zone, i).await); + } + return records; +} + +pub async fn add_record_to_zone(ovh_client: &OVHClient, + client: &Client>, + zone: &str, record: &Record) -> Record { + let req = build_request(ovh_client, &Method::POST, + format!("/domain/zone/{}/record", zone).as_str(), + serde_json::to_string(record).unwrap().as_str()); + let res = client.request(req).await.unwrap(); + assert!(res.status().is_success()); + return from_str(body_to_str(res.into_body()).await.as_str()).unwrap(); +} + +pub async fn update_record_in_zone(ovh_client: &OVHClient, + client: &Client>, + zone: &str, record: &Record) { + let req = build_request(ovh_client, &Method::PUT, + format!("/domain/zone/{}/record/{}", zone, record.id).as_str(), + json!({"subDomain": record.sub_domain, + "target": record.target, "ttl": record.ttl}).to_string().as_str()); + let res = client.request(req).await.unwrap(); + assert!(res.status().is_success()); +} + +pub async fn delete_record_from_zone(ovh_client: &OVHClient, + client: &Client>, + zone: &str, id: u64) { + let req = build_request(ovh_client, &Method::DELETE, + format!("/domain/zone/{}/record/{}", zone, id).as_str(), + ""); + let res = client.request(req).await.unwrap(); + assert!(res.status().is_success()); +} + +pub async fn refresh_zone(ovh_client: &OVHClient, client: &Client>, + zone: &str) { + let req = build_request(ovh_client, &Method::DELETE, + format!("/domain/zone/{}/refresh", zone).as_str(), + ""); + let res = client.request(req).await.unwrap(); + assert!(res.status().is_success()); +} diff --git a/src/utils.rs b/src/utils.rs index 8ab23d3..f8ae862 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,31 +1,48 @@ use std::time::{UNIX_EPOCH, SystemTime}; -use hyper::{Request, Method, Body, body}; +use hyper_tls::HttpsConnector; +use hyper::{Request, Method, Body, body, Client, client::HttpConnector}; + +pub struct OVHClient { + pub app_key: String, + pub app_secret: String, + pub consumer_key: String, + pub endpoint: String, + pub delta: i64 +} pub async fn body_to_str(res: Body) -> String { return String::from_utf8(body::to_bytes(res).await.unwrap().to_vec()).unwrap(); } -pub fn get_signature(app_secret: &str, consumer_key: &str, method: &Method, - query: &str, body: &str, delta: i64) -> String { - let stringapi = format!("{}+{}+{}+{}+{}+{}", app_secret, consumer_key, +pub fn get_signature(ovh_client: &OVHClient, method: &Method, query: &str, body: &str) -> String { + let stringapi = format!("{}+{}+{}+{}+{}+{}", ovh_client.app_secret, ovh_client.consumer_key, method.as_str(), query, body, SystemTime::now().duration_since(UNIX_EPOCH) - .unwrap().as_secs() as i64 + delta); + .unwrap().as_secs() as i64 + ovh_client.delta); return format!("$1${}", sha1::Sha1::from(stringapi).hexdigest()); } -pub fn build_request(app_key: &str, app_secret: &str, consumer_key: &str, - method: &Method, uri: &str, body: &str, delta: i64) -> Request { +pub fn build_request(ovh_client: &OVHClient, method: &Method, uri: &str, body: &str) -> Request { return Request::builder() .method(method) - .uri(uri) - .header("X-Ovh-Application", app_key) + .uri(ovh_client.endpoint.clone() + uri) + .header("X-Ovh-Application", ovh_client.app_key.clone()) .header("X-Ovh-Timestamp", SystemTime::now().duration_since(UNIX_EPOCH) - .unwrap().as_secs() as i64 + delta) - .header("X-Ovh-Consumer", consumer_key) - .header("X-Ovh-Signature", get_signature(app_secret, consumer_key, method, - uri, body, delta)) + .unwrap().as_secs() as i64 + ovh_client.delta) + .header("X-Ovh-Consumer", ovh_client.consumer_key.clone()) + .header("X-Ovh-Signature", get_signature(ovh_client, method, + format!("{}{}", + ovh_client.endpoint, uri).as_str(), body)) .header("Content-Type", "application/json;charset=utf-8") .body(Body::from(body.to_string())) - .expect("Build"); + .expect(uri); +} + +pub async fn get_delta(ovh_client: &OVHClient, client: &Client>) -> i64 { + let req = build_request(&ovh_client, &Method::GET, "/auth/time", ""); + let res = client.request(req).await.unwrap(); + let s = res.status(); + assert!(s.is_success()); + let b = body_to_str(res.into_body()).await.parse::().unwrap(); + return SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64 - b; }