Skip to content

Commit

Permalink
Merge pull request #21 from XOR-op/api
Browse files Browse the repository at this point in the history
[Feat] API enhancements
  • Loading branch information
XOR-op authored Apr 4, 2023
2 parents 05c74b2 + 3a283bf commit 80f4036
Show file tree
Hide file tree
Showing 20 changed files with 379 additions and 166 deletions.
16 changes: 16 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions boltadm/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ struct CertOptions {
}

#[derive(Debug, StructOpt)]
enum MitmOptions {
enum EavesdropOptions {
/// List all captured data
List,
/// List data ranged from *start* to *end*
Expand All @@ -77,7 +77,7 @@ enum SubCommand {
/// Generate Certificates
Cert(CertOptions),
/// Captured HTTP data
Mitm(MitmOptions),
Eavesdrop(EavesdropOptions),
/// Clean unexpected shutdown
Clean,
/// Reload Configuration
Expand Down Expand Up @@ -128,10 +128,10 @@ async fn main() {
Err(e) => Err(e),
}
}
SubCommand::Mitm(opt) => match opt {
MitmOptions::List => requestor.get_mitm(None).await,
MitmOptions::Range { start, end } => requestor.get_mitm(Some((start, end))).await,
MitmOptions::Get { id } => requestor.get_mitm_payload(id).await,
SubCommand::Eavesdrop(opt) => match opt {
EavesdropOptions::List => requestor.eavesdrop(None).await,
EavesdropOptions::Range { start, end } => requestor.eavesdrop(Some((start, end))).await,
EavesdropOptions::Get { id } => requestor.get_eavesdrop_payload(id).await,
},
SubCommand::Clean => {
if !is_root() {
Expand Down
27 changes: 13 additions & 14 deletions boltadm/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub struct Requester {

impl Requester {
pub async fn get_group_list(&self) -> Result<()> {
let data = reqwest::get(self.route("/groups")).await?.text().await?;
let data = reqwest::get(self.route("/proxies")).await?.text().await?;
let result: Vec<boltapi::GetGroupRespSchema> = serde_json::from_str(data.as_str())?;
for entry in result {
println!("{}: {}", entry.name.bold().red(), entry.selected.blue());
Expand All @@ -22,12 +22,9 @@ impl Requester {
}

pub async fn set_group_proxy(&self, group: String, proxy: String) -> Result<()> {
let req = boltapi::SetGroupReqSchema {
group,
selected: proxy,
};
let req = boltapi::SetGroupReqSchema { selected: proxy };
let result = reqwest::Client::new()
.put(self.route("/groups"))
.put(self.route(format!("/proxies/{}", group).as_str()))
.json(&req)
.send()
.await?
Expand Down Expand Up @@ -122,14 +119,16 @@ impl Requester {
Ok(())
}

pub async fn get_mitm(&self, range: Option<(u32, Option<u32>)>) -> Result<()> {
pub async fn eavesdrop(&self, range: Option<(u32, Option<u32>)>) -> Result<()> {
let uri = match range {
None => self.route("/mitm/all"),
Some((s, Some(e))) => self.route(format!("/mitm/range?start={}&end={}", s, e).as_str()),
Some((s, None)) => self.route(format!("/mitm/range?start={}", s).as_str()),
None => self.route("/eavesdrop/all"),
Some((s, Some(e))) => {
self.route(format!("/eavesdrop/range?start={}&end={}", s, e).as_str())
}
Some((s, None)) => self.route(format!("/eavesdrop/range?start={}", s).as_str()),
};
let data = reqwest::get(uri).await?.text().await?;
let result: Vec<boltapi::HttpMitmSchema> = serde_json::from_str(data.as_str())?;
let result: Vec<boltapi::HttpEavesdropSchema> = serde_json::from_str(data.as_str())?;
let mut table = Table::new("{:<} {:<} {:<} {:<} {:<} {:<}");
table.add_row(
Row::new()
Expand All @@ -155,12 +154,12 @@ impl Requester {
Ok(())
}

pub async fn get_mitm_payload(&self, id: u32) -> Result<()> {
let data = reqwest::get(self.route(format!("/mitm/payload/{}", id).as_str()))
pub async fn get_eavesdrop_payload(&self, id: u32) -> Result<()> {
let data = reqwest::get(self.route(format!("/eavesdrop/payload/{}", id).as_str()))
.await?
.text()
.await?;
let result: boltapi::GetMitmDataResp = serde_json::from_str(data.as_str())?;
let result: boltapi::GetEavesdropDataResp = serde_json::from_str(data.as_str())?;
println!("================== Request ===================");
println!("Header:");
result.req_header.iter().for_each(|l| println!("{}", l));
Expand Down
26 changes: 20 additions & 6 deletions boltapi/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ pub struct SessionSchema {

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct HttpMitmSchema {
pub mitm_id: u64,
pub struct HttpEavesdropSchema {
pub eavesdrop_id: u64,
pub client: Option<String>,
pub uri: String,
pub method: String,
Expand All @@ -53,30 +53,44 @@ pub struct GetGroupRespSchema {
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct SetGroupReqSchema {
pub group: String,
pub selected: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct GetMitmRangeReq {
pub struct GetEavesdropRangeReq {
pub start: u32,
pub end: Option<u32>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct GetMitmDataReq {
pub struct GetEavesdropDataReq {
pub id: u32,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct GetMitmDataResp {
pub struct GetEavesdropDataResp {
pub req_header: Vec<String>,
#[serde(with = "base64ext")]
pub req_body: Vec<u8>,
pub resp_header: Vec<String>,
#[serde(with = "base64ext")]
pub resp_body: Vec<u8>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct TrafficResp {
pub upload: u64,
pub download: u64,
pub upload_speed: Option<u64>,
pub download_speed: Option<u64>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields)]
pub struct TunStatusSchema {
pub enabled: bool,
}
4 changes: 2 additions & 2 deletions boltconn/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ aho-corasick = "0.7.20"
anyhow = "1.0.66"
arrayref = "0.3.6"
async-trait = "0.1.58"
axum = "0.6.1"
axum = { version = "0.6.1", features = ["ws"] }
base64 = "0.21.0"
boltapi = { path = "../boltapi" }
boringtun = "0.5.2"
Expand Down Expand Up @@ -51,7 +51,7 @@ tokio = { version = "1.25.0", features = ["rt", "rt-multi-thread", "net", "sync"
tokio-rustls = { version = "0.23.4", features = ["dangerous_configuration"] }
tokio-tungstenite = "0.18.0"
tracing = "0.1.37"
tracing-subscriber = { version = "0.3.16", features = ["env-filter", "std", "fmt"] }
tracing-subscriber = { version = "0.3.16", features = ["env-filter", "std", "fmt", "json"] }
trust-dns-proto = "0.22.0"
trust-dns-resolver = { version = "0.22.0", features = ['dns-over-rustls', 'dns-over-https-rustls', 'dns-over-https', 'dns-over-tls'] }
webpki-roots = "0.22.5"
Expand Down
4 changes: 2 additions & 2 deletions boltconn/src/config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ pub struct RawRootCfg {
pub rule_local: Vec<String>,
#[serde(alias = "rule-provider", default = "default_rule_provider")]
pub rule_provider: HashMap<String, RuleProvider>,
#[serde(alias = "mitm-rule")]
pub mitm_rule: Option<Vec<String>>,
#[serde(alias = "eavesdrop-rule")]
pub eavesdrop_rule: Option<Vec<String>>,
#[serde(alias = "rewrite-rule")]
pub rewrite: Option<Vec<String>>,
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::mitm::url_rewrite::{UrlModManager, UrlModType};
use crate::mitm::{HeaderModManager, Modifier, ModifierContext};
use crate::eavesdrop::url_rewrite::{UrlModManager, UrlModType};
use crate::eavesdrop::{HeaderModManager, Modifier, ModifierContext};
use crate::platform::process::ProcessInfo;
use crate::proxy::{DumpedRequest, DumpedResponse, HttpCapturer, NetworkAddr};
use anyhow::anyhow;
Expand All @@ -11,15 +11,15 @@ use std::str::FromStr;
use std::sync::Arc;
use std::time::Instant;

pub struct MitmModifier {
pub struct EavesdropModifier {
client: Option<ProcessInfo>,
contents: Arc<HttpCapturer>,
url_rewriter: Arc<UrlModManager>,
header_rewriter: Arc<HeaderModManager>,
pending: DashMap<u64, DumpedRequest>,
}

impl MitmModifier {
impl EavesdropModifier {
pub fn new(
contents: Arc<HttpCapturer>,
url_rewriter: Arc<UrlModManager>,
Expand All @@ -37,7 +37,7 @@ impl MitmModifier {
}

#[async_trait]
impl Modifier for MitmModifier {
impl Modifier for EavesdropModifier {
async fn modify_request(
&self,
req: Request<Body>,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::mitm::Replacement;
use crate::eavesdrop::Replacement;
use http::header::HeaderName;
use http::{HeaderMap, HeaderValue};
use regex::{Regex, RegexSet};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::adapter::{Connector, TcpOutBound};
use crate::common::duplex_chan::DuplexChan;
use crate::common::id_gen::IdGenerator;
use crate::mitm::modifier::Modifier;
use crate::mitm::ModifierContext;
use crate::eavesdrop::modifier::Modifier;
use crate::eavesdrop::ModifierContext;
use crate::proxy::{ConnAbortHandle, ConnAgent};
use hyper::client::conn;
use hyper::server::conn::Http;
Expand All @@ -12,14 +12,14 @@ use std::io;
use std::sync::Arc;
use tokio::sync::RwLock;

pub struct HttpMitm {
pub struct HttpEavesdrop {
inbound: DuplexChan,
modifier: Arc<dyn Modifier>,
creator: Arc<dyn TcpOutBound>,
conn_info: Arc<RwLock<ConnAgent>>,
}

impl HttpMitm {
impl HttpEavesdrop {
pub fn new(
inbound: DuplexChan,
modifier: Arc<dyn Modifier>,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::adapter::{Connector, TcpOutBound};
use crate::common::duplex_chan::DuplexChan;
use crate::common::id_gen::IdGenerator;
use crate::mitm::modifier::Modifier;
use crate::mitm::{sign_site_cert, ModifierContext};
use crate::eavesdrop::modifier::Modifier;
use crate::eavesdrop::{sign_site_cert, ModifierContext};
use crate::proxy::{ConnAbortHandle, ConnAgent};
use hyper::client::conn;
use hyper::server::conn::Http;
Expand All @@ -18,7 +18,7 @@ use tokio_rustls::rustls::{
};
use tokio_rustls::{TlsAcceptor, TlsConnector};

pub struct HttpsMitm {
pub struct HttpsEavesdrop {
cert: Vec<Certificate>,
priv_key: PrivateKey,
server_name: String,
Expand All @@ -28,7 +28,7 @@ pub struct HttpsMitm {
conn_info: Arc<RwLock<ConnAgent>>,
}

impl HttpsMitm {
impl HttpsEavesdrop {
pub fn new(
ca_cert: &CaCertificate,
server_name: String,
Expand Down
12 changes: 6 additions & 6 deletions boltconn/src/mitm/mod.rs → boltconn/src/eavesdrop/mod.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
mod eavesdrop_modifier;
mod header_rewrite;
mod http_mitm;
mod https_mitm;
mod mitm_modifier;
mod http_eavesdrop;
mod https_eavesdrop;
mod modifier;
mod url_rewrite;

pub use eavesdrop_modifier::*;
pub use header_rewrite::*;
pub use http_mitm::HttpMitm;
pub use https_mitm::HttpsMitm;
pub use mitm_modifier::*;
pub use http_eavesdrop::HttpEavesdrop;
pub use https_eavesdrop::HttpsEavesdrop;
pub use modifier::*;
use rcgen::{
date_time_ymd, Certificate, CertificateParams, DistinguishedName, DnType, IsCa, KeyUsagePurpose,
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::mitm::ReplacedChunk;
use crate::eavesdrop::ReplacedChunk;
use regex::{Regex, RegexSet};

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
Expand Down
Loading

0 comments on commit 80f4036

Please sign in to comment.