Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2g downgrade update #91

Merged
merged 8 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions bin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ clap = { version = "4.5.2", features = ["derive"] }
serde_json = "1.0.114"
image = "0.25.1"
tempfile = "3.10.1"
simple_logger = "5.0.0"
54 changes: 42 additions & 12 deletions bin/src/check.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{collections::HashMap, future, path::PathBuf, pin::pin};
use rayhunter::{analysis::analyzer::Harness, diag::DataType, gsmtap_parser, pcap::GsmtapPcapWriter, qmdl::QmdlReader};
use log::{info, warn};
use rayhunter::{analysis::analyzer::{EventType, Harness}, diag::DataType, gsmtap_parser, pcap::GsmtapPcapWriter, qmdl::QmdlReader};
use tokio::fs::{metadata, read_dir, File};
use clap::Parser;
use futures::TryStreamExt;
Expand All @@ -9,7 +10,7 @@ mod dummy_analyzer;
#[derive(Parser, Debug)]
#[command(version, about)]
struct Args {
#[arg(short, long)]
wgreenberg marked this conversation as resolved.
Show resolved Hide resolved
#[arg(short = 'p', long)]
qmdl_path: PathBuf,

#[arg(short, long)]
Expand All @@ -20,6 +21,9 @@ struct Args {

#[arg(long)]
enable_dummy_analyzer: bool,

#[arg(short, long)]
quiet: bool,
}

async fn analyze_file(harness: &mut Harness, qmdl_path: &str, show_skipped: bool) {
Expand All @@ -41,20 +45,37 @@ async fn analyze_file(harness: &mut Harness, qmdl_path: &str, show_skipped: bool
}
for analysis in row.analysis {
for maybe_event in analysis.events {
if let Some(event) = maybe_event {
warnings += 1;
println!("{}: {:?}", analysis.timestamp, event);
let Some(event) = maybe_event else { continue };
match event.event_type {
EventType::Informational => {
info!(
"{}: INFO - {} {}",
qmdl_path,
analysis.timestamp,
event.message,
);
}
EventType::QualitativeWarning { severity } => {
warn!(
"{}: WARNING (Severity: {:?}) - {} {}",
qmdl_path,
severity,
analysis.timestamp,
event.message,
);
warnings += 1;
}
}
}
}
}
if show_skipped && skipped > 0 {
println!("{}: messages skipped:", qmdl_path);
info!("{}: messages skipped:", qmdl_path);
for (reason, count) in skipped_reasons.iter() {
println!(" - {}: \"{}\"", count, reason);
info!(" - {}: \"{}\"", count, reason);
}
}
println!("{}: {} messages analyzed, {} warnings, {} messages skipped", qmdl_path, total_messages, warnings, skipped);
info!("{}: {} messages analyzed, {} warnings, {} messages skipped", qmdl_path, total_messages, warnings, skipped);
}

async fn pcapify(qmdl_path: &PathBuf) {
Expand All @@ -75,21 +96,30 @@ async fn pcapify(qmdl_path: &PathBuf) {
}
}
}
println!("wrote pcap to {:?}", &pcap_path);
info!("wrote pcap to {:?}", &pcap_path);
}

#[tokio::main]
async fn main() {
env_logger::init();
let args = Args::parse();
let level = if args.quiet {
log::LevelFilter::Warn
} else {
log::LevelFilter::Trace
};
simple_logger::SimpleLogger::new()
.with_colors(true)
.without_timestamps()
.with_level(level)
.init().unwrap();

let mut harness = Harness::new_with_all_analyzers();
if args.enable_dummy_analyzer {
harness.add_analyzer(Box::new(dummy_analyzer::TestAnalyzer { count: 0 }));
}
println!("Analyzers:");
info!("Analyzers:");
for analyzer in harness.get_metadata().analyzers {
println!(" - {}: {}", analyzer.name, analyzer.description);
info!(" - {}: {}", analyzer.name, analyzer.description);
}

let metadata = metadata(&args.qmdl_path).await.expect("failed to get metadata");
Expand Down
6 changes: 4 additions & 2 deletions lib/src/analysis/analyzer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use crate::{diag::MessagesContainer, gsmtap_parser};
use super::{
imsi_requested::ImsiRequestedAnalyzer,
information_element::InformationElement,
lte_downgrade::LteSib6And7DowngradeAnalyzer,
connection_redirect_downgrade::ConnectionRedirect2GDowngradeAnalyzer,
priority_2g_downgrade::LteSib6And7DowngradeAnalyzer,
null_cipher::NullCipherAnalyzer,
};

Expand Down Expand Up @@ -117,8 +118,9 @@ impl Harness {

pub fn new_with_all_analyzers() -> Self {
let mut harness = Harness::new();
harness.add_analyzer(Box::new(LteSib6And7DowngradeAnalyzer{}));
harness.add_analyzer(Box::new(ImsiRequestedAnalyzer::new()));
harness.add_analyzer(Box::new(ConnectionRedirect2GDowngradeAnalyzer{}));
harness.add_analyzer(Box::new(LteSib6And7DowngradeAnalyzer{}));
harness.add_analyzer(Box::new(NullCipherAnalyzer{}));

harness
Expand Down
42 changes: 42 additions & 0 deletions lib/src/analysis/connection_redirect_downgrade.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use std::borrow::Cow;

use super::analyzer::{Analyzer, Event, EventType, Severity};
use super::information_element::{InformationElement, LteInformationElement};
use telcom_parser::lte_rrc::{DL_DCCH_Message, DL_DCCH_MessageType, DL_DCCH_MessageType_c1, RRCConnectionReleaseCriticalExtensions, RRCConnectionReleaseCriticalExtensions_c1, RedirectedCarrierInfo};
use super::util::unpack;

// Based on HITBSecConf presentation "Forcing a targeted LTE cellphone into an
// eavesdropping network" by Lin Huang
pub struct ConnectionRedirect2GDowngradeAnalyzer {
}

// TODO: keep track of SIB state to compare LTE reselection blocks w/ 2g/3g ones
impl Analyzer for ConnectionRedirect2GDowngradeAnalyzer {
fn get_name(&self) -> Cow<str> {
Cow::from("Connection Release/Redirected Carrier 2G Downgrade")
}

fn get_description(&self) -> Cow<str> {
Cow::from("Tests if a cell releases our connection and redirects us to a 2G cell.")
}

fn analyze_information_element(&mut self, ie: &InformationElement) -> Option<Event> {
unpack!(InformationElement::LTE(lte_ie) = ie);
unpack!(LteInformationElement::DlDcch(DL_DCCH_Message { message }) = lte_ie);
unpack!(DL_DCCH_MessageType::C1(c1) = message);
unpack!(DL_DCCH_MessageType_c1::RrcConnectionRelease(release) = c1);
unpack!(RRCConnectionReleaseCriticalExtensions::C1(c1) = &release.critical_extensions);
unpack!(RRCConnectionReleaseCriticalExtensions_c1::RrcConnectionRelease_r8(r8_ies) = c1);
unpack!(Some(carrier_info) = &r8_ies.redirected_carrier_info);
match carrier_info {
RedirectedCarrierInfo::Geran(_carrier_freqs_geran) => Some(Event {
event_type: EventType::QualitativeWarning { severity: Severity::High },
message: format!("Detected 2G downgrade"),
}),
_ => Some(Event {
event_type: EventType::Informational,
message: format!("RRCConnectionRelease CarrierInfo: {:?}", carrier_info),
}),
}
}
}
6 changes: 3 additions & 3 deletions lib/src/analysis/imsi_requested.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ impl Analyzer for ImsiRequestedAnalyzer {
return None;
};

// NAS identity request
// NAS identity request, ID type IMSI
if payload == &[0x07, 0x55, 0x01] {
if self.packet_num < PACKET_THRESHHOLD {
return Some(Event {
event_type: EventType::QualitativeWarning {
severity: Severity::Medium
},
message: format!(
"NAS IMSI request detected, however it was within \
"NAS IMSI identity request detected, however it was within \
the first {} packets of this analysis. If you just \
turned your device on, this is likely a \
false-positive.",
Expand All @@ -50,7 +50,7 @@ impl Analyzer for ImsiRequestedAnalyzer {
event_type: EventType::QualitativeWarning {
severity: Severity::High
},
message: format!("NAS IMSI request detected"),
message: format!("NAS IMSI identity request detected"),
})
}
}
Expand Down
4 changes: 3 additions & 1 deletion lib/src/analysis/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
pub mod analyzer;
pub mod information_element;
pub mod lte_downgrade;
pub mod priority_2g_downgrade;
pub mod connection_redirect_downgrade;
pub mod imsi_provided;
pub mod imsi_requested;
pub mod null_cipher;
pub mod util;
32 changes: 32 additions & 0 deletions lib/src/analysis/util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

// Unpacks a pattern, or returns None.
//
// # Examples
// You can use `unpack!` to unroll highly nested enums like this:
// ```
// enum Foo {
// A(Bar),
// B,
// }
//
// enum Bar {
// C(Baz)
// }
//
// struct Baz;
//
// fn get_bang(foo: Foo) -> Option<Baz> {
// unpack!(Foo::A(bar) = foo);
// unpack!(Bar::C(baz) = bar);
// baz
// }
// ```
//
macro_rules! unpack {
($pat:pat = $val:expr) => {
let $pat = $val else { return None; };
};
}

// this is apparently how you make a macro publicly usable from this module
pub(crate) use unpack;
wgreenberg marked this conversation as resolved.
Show resolved Hide resolved