Skip to content

Feat : Implementation of Network Analyzer VPN ModuleπŸ‘πŸ½Β #49

@muhammad7865

Description

@muhammad7865

🌐 Network Analyzer β€” Implementation Plan

CyberShield Β· Network Analyzer Feature
Approach: Backend-first Β· One service per commit Β· No broken dependencies mid-way

The Network Analyzer captures all device traffic through a local VPN tunnel, scores each packet using a layered threat engine, and alerts the user in real-time. All processing is on-device β€” no data leaves the phone.


πŸ“‘ Table of Contents

  1. Build Order β€” Backend First
  2. Commit-by-Commit Plan
  3. Database Design
  4. Whitelist & Blacklist Strategy
  5. ThreatAnalyzer β€” Scoring Pipeline
  6. Seed Data β€” First Launch
  7. Verification Plan

πŸ—οΈ Build Order β€” Backend First

Why backend-first?

  • Each upper layer depends on the one below it (UI β†’ ViewModel β†’ Repository β†’ DAOs)
  • Every commit compiles and is independently testable
  • No broken stubs or placeholder dependencies
DB Entities & DAOs           ← Commit 1  (foundation β€” everything sits on this)
   └─► Seed Worker           ← Commit 2  (data to query against)
         └─► PacketParser    ← Commit 3  (decode raw VPN bytes)
               └─► ThreatAnalyzer       ← Commit 4  (score decoded packets)
                     └─► VpnMonitorService          ← Commit 5  (capture + wire together)
                           └─► Domain Models + Repo  ← Commits 6–7
                                 └─► ViewModel        ← Commit 8
                                       └─► Full UI    ← Commit 9
                                             └─► Hilt ← Commit 10

πŸ“¦ Commit-by-Commit Plan

# Commit Message Files
1 feat: add Room DB entities and DAOs for network analyzer 4 entities, 4 DAOs, register in CyberShieldDatabase
2 feat: add threat_domains seed asset and first-launch worker assets/threat_domains.json, SeedThreatDbWorker.kt
3 feat: implement PacketParser for raw IP packet decoding core/network/PacketParser.kt
4 feat: implement ThreatAnalyzer with weighted scoring engine core/network/ThreatAnalyzer.kt
5 feat: implement VpnMonitorService with packet capture loop core/service/VpnMonitorService.kt, AndroidManifest.xml
6 feat: add domain models and NetworkAnalyzerRepository interface domain/model/, domain/repository/
7 feat: implement NetworkAnalyzerRepositoryImpl data/repository/NetworkAnalyzerRepositoryImpl.kt
8 feat: add NetworkViewModel with UiState and VPN lifecycle presentation/network/NetworkViewModel.kt
9 feat: replace NetworkView placeholder with full monitoring UI presentation/network/NetworkView.kt
10 feat: wire all network analyzer components via Hilt di/AppModule.kt

πŸ—„οΈ Database Design β€” 4 Room Tables

-- 1. network_traffic  (Traffic Logs β€” 7-day rolling retention)
id               INTEGER  PRIMARY KEY AUTOINCREMENT
timestamp        INTEGER
source_ip        TEXT
destination_ip   TEXT
destination_domain TEXT
destination_port INTEGER
protocol         TEXT     -- TCP | UDP | ICMP
bytes_sent       INTEGER
threat_level     TEXT     -- SAFE | SUSPICIOUS | MALICIOUS
threat_score     REAL     -- 0.0–1.0
blocked          INTEGER  -- 0 | 1

-- 2. threat_domains  (Threat Intelligence β€” seeded from bundled JSON)
domain           TEXT  PRIMARY KEY
threat_type      TEXT  -- MALWARE | PHISHING | C2 | TRACKING | ADS
severity         REAL  -- 0.0–1.0
category         TEXT
source           TEXT  -- 'builtin' | 'user_reported' | 'cloud'
last_updated     INTEGER

-- 3. network_whitelist
domain           TEXT  PRIMARY KEY
added_at         INTEGER
added_by         TEXT  -- 'system' | 'user'
notes            TEXT

-- 4. network_blacklist
domain           TEXT  PRIMARY KEY
added_at         INTEGER
added_by         TEXT
reason           TEXT
block_permanently INTEGER  -- 0 = expires after 30d, 1 = permanent

DB Retention / Cleanup (daily WorkManager job)

Table Retention Rule
network_traffic 7 days Delete rows where timestamp < now - 7d
network_blacklist (block_permanently=0) 30 days Delete expired rows
threat_domains Indefinite Replaced on app update / cloud sync
network_whitelist Indefinite User removes manually

πŸ”’ Whitelist & Blacklist Strategy

VPN starts
  └─► Load whitelist + blacklist from Room β†’ in-memory HashSet<String>

Each packet arrives
  └─► Check in-memory HashSet  (~0ms, O(1))
       Found in whitelist? β†’ βœ… SAFE.  Exit. No analysis.
       Found in blacklist? β†’ 🚨 MALICIOUS. Drop packet. Exit.
       Not found?          β†’ Pass to ThreatAnalyzer pipeline.

How entries get added

Source Whitelist Blacklist
Bundled at install Top-50 trusted domains ~50 k known C2/malware/phishing domains
User taps 'Always Allow' βœ… β€”
User taps 'Block Forever' β€” βœ…
Auto-promote β€” Domain hits MALICIOUS 3Γ— in 24 hrs
Phase 2 cloud Safe-list delta sync Daily diff from abuse.ch / URLhaus

πŸ’‘ Memory sync rule: User adds/removes an entry β†’ write to Room AND update live HashSet immediately. No VPN restart needed.


🧠 ThreatAnalyzer β€” Scoring Pipeline

Signal A β€” Domain Reputation   (weight: 50%)
  Query threat_domains Room DB for the destination domain
  Found? Use its severity score (0.0–1.0)
  Not found? Score = 0.0

Signal B β€” Port Risk            (weight: 30%)
  Port 4444 / 1337 / 6667  β†’ 1.0  (known C2/hacking ports)
  Port 21 / 23 / 25        β†’ 0.5  (unencrypted/legacy)
  Port 80 / 443 / 53       β†’ 0.0  (normal traffic)
  Any other port            β†’ 0.2  (unknown)

Signal C β€” Pattern Heuristics  (weight: 20%)
  Payload > 10 KB to unknown port β†’ +0.3
  Destination is private IP       β†’ +0.2
  Port 80/443 but non-HTTP data   β†’ +0.2

Final Score = (A Γ— 0.5) + (B Γ— 0.3) + (C Γ— 0.2)

< 0.3    β†’ βœ… SAFE       β€” forward silently
0.3–0.7  β†’ ⚠️ SUSPICIOUS  β€” forward + in-app alert
> 0.7    β†’ 🚨 MALICIOUS   β€” drop packet + push notification

Real Example

Packet β†’ malware-c2.ru : port 4444 : 15KB payload

  Signal A β†’ severity 0.95 (C2 in threat DB)  Γ— 0.5 = 0.475
  Signal B β†’ port 4444 = 1.0                  Γ— 0.3 = 0.300
  Signal C β†’ payload > 10KB                   Γ— 0.2 = 0.060
                                        TOTAL       = 0.835

  0.835 > 0.7  β†’  🚨 MALICIOUS  β†’  Packet DROPPED

🌱 Seed Data β€” First Launch

The threat_domains.json is bundled inside the APK β€” NOT downloaded. Works offline from day one.

Public sources used

Feed Type
URLhaus (abuse.ch) Malware distribution URLs
Feodo Tracker (abuse.ch) Botnet C2 servers
PhishTank Verified phishing pages
EasyPrivacy Ad / tracking domains

First-launch seeding flow

App launches for the very first time
  └─► DataStore flag: "seeded?" β†’ NO
  └─► Schedule SeedThreatDbWorker  (WorkManager, one-time, background)
        └─► Open assets/threat_domains.json
        └─► Batch-insert all entries into Room  (~2–3 sec)
        └─► Set DataStore flag: "seeded = true"

Every subsequent launch:
  └─► DataStore flag: "seeded?" β†’ YES  β†’  skip, nothing happens

What happens on an app update?

Scenario How handled
New APK installed New threat_domains.json ships with it. Version check triggers a re-seed.
Between updates (Phase 2) Optional daily delta download β€” only new/changed entries, not the full 50k.
Completely offline phone Works fine β€” uses bundled snapshot from install day.

βœ… Verification Plan

Unit Tests (JVM β€” no device needed)

What Test
PacketParser Feed known TCP/UDP byte arrays β†’ assert correct IP, port, protocol extracted
ThreatAnalyzer β€” whitelist Whitelisted domain β†’ assert SAFE, score = 0.0
ThreatAnalyzer β€” blacklist Blacklisted domain β†’ assert MALICIOUS, shouldBlock = true
ThreatAnalyzer β€” port risk Port 4444 + unknown domain β†’ assert score > 0.7
ThreatAnalyzer β€” formula C2 domain (severity 0.95) + port 4444 β†’ assert score β‰ˆ 0.835
./gradlew test

On-Device Manual Checks

  1. Install app β†’ DB Inspector β†’ confirm threat_domains table has entries
  2. Start VPN β†’ navigate to known malicious domain from seed data β†’ confirm notification fires
  3. Tap Always Allow β†’ verify domain in network_whitelist, next request silent
  4. Tap Block Forever β†’ verify domain in network_blacklist, packet dropped
  5. Stop VPN β†’ foreground notification dismissed cleanly

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions