Metadata-Version: 2.4
Name: secenvY
Version: 0.3.1
Summary: Gymnasium Environment for AI-driven Android Security Analysis, Dynamic Fuzzing, and Penetration Testing
Author: Android Security Agent Team
License: Apache-2.0
Project-URL: Homepage, https://github.com/d4em0ny/android-security-agent
Project-URL: Repository, https://github.com/d4em0ny/android-security-agent.git
Project-URL: Issues, https://github.com/d4em0ny/android-security-agent/issues
Keywords: reinforcement-learning,gymnasium,android,security,penetration-testing,fuzzing,rag,dueling-dqn
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Security
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: gymnasium>=0.29.0
Requires-Dist: numpy>=1.24.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pydantic-settings>=2.0.0
Requires-Dist: chromadb>=0.5.0
Requires-Dist: google-genai>=0.1.0
Requires-Dist: sentence-transformers>=2.2.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: rich>=13.0.0
Requires-Dist: fastapi>=0.100.0
Requires-Dist: uvicorn>=0.20.0
Requires-Dist: websockets>=11.0
Provides-Extra: agent
Requires-Dist: torch>=2.0.0; extra == "agent"
Requires-Dist: stable-baselines3>=2.0.0; extra == "agent"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Requires-Dist: torch>=2.0.0; extra == "dev"
Requires-Dist: stable-baselines3>=2.0.0; extra == "dev"

# Android Security Environment (`secenvY`)

[![PyPI Version](https://img.shields.io/pypi/v/secenvY.svg?color=blue)](https://pypi.org/project/secenvY/)
[![Python Versions](https://img.shields.io/pypi/pyversions/secenvY.svg)](https://pypi.org/project/secenvY/)
[![Gymnasium](https://img.shields.io/badge/Gymnasium-v0.29.1%2B-green.svg)](https://gymnasium.farama.org/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

**`secenvY`** (`AndroidSecurityEnv-v0`) is a gold-standard Gymnasium benchmark environment and decision-making engine for automated Android mobile application security analysis, dynamic fuzzing, and penetration testing.

Adhering strictly to **Farama Foundation Gymnasium standards**, `secenvY` exposes standard NumPy observation tensors and discrete action spaces, enabling seamless plug-and-play integration with popular reinforcement learning frameworks including **Stable-Baselines3**, **CleanRL**, **RLlib**, and custom PyTorch agents.

---

## 🚀 5-Line Quickstart

```python
import gymnasium as gym
import secenvY

env = gym.make("AndroidSecurityEnv-v0")
obs, info = env.reset(seed=42, options={"pkg": "com.vulnerable.bank"})

for _ in range(50):
    action = env.action_space.sample(mask=info.get("action_mask"))
    obs, reward, terminated, truncated, info = env.step(action)
    if terminated or truncated:
        break
env.close()
```

---

## 📦 Installation

### Pure Environment (Lightweight Benchmark)
Installs only the environment, state pipeline, gateway, and RAG reasoner without heavy ML dependencies:
```bash
pip install secenvY
```

### With RL Training Baselines (`[agent]` Extra)
Installs PyTorch and Stable-Baselines3 to run the reference training algorithms in `examples/`:
```bash
pip install "secenvY[agent]"
```

### Development & Testing
```bash
git clone https://github.com/d4em0ny/android-security-agent.git
cd android-security-agent
pip install -e ".[dev]"
```

---

## 📊 Environment Specification

| Property | Value | Notes |
| :--- | :--- | :--- |
| **Environment ID** | `AndroidSecurityEnv-v0` | Registered via standard `gym.register` |
| **Observation Space** | `Box(0.0, 1.0, (117,), float32)` | Continuous, bounded, normalized across 17 domain groups |
| **Action Space** | `Discrete(8)` | 4 UI exploration actions + 3 security fuzzing actions + 1 finish action |
| **Default Horizon** | `100` steps | Configurable via `max_steps` |
| **Dual-Dispatch** | Yes | Numerical RL stream + Semantic RAG Reasoner |

---

## 🧭 Action Space Specification (`Discrete(8)`)

The action space consists of **8 discrete meta-actions** categorized into UI exploration, security fuzzing, and episode lifecycle:

| Action ID | Meta-Action | Category | Description | Dynamic Masking Preconditions |
| :---: | :--- | :--- | :--- | :--- |
| `0` | `TAP` | `UI_EXPLORATION` | Tap clickable widget or primary interactable component | Masked if `interactable_count == 0` |
| `1` | `TYPE_TEXT` | `UI_EXPLORATION` | Type fuzz inputs or credentials into input fields | Masked if `input_fields_count == 0` |
| `2` | `SCROLL` | `UI_EXPLORATION` | Scroll screen vertically to reveal off-screen views | Masked if `scroll_position >= 0.9` |
| `3` | `BACK` | `UI_EXPLORATION` | Press Android system back button to ascend UI hierarchy | Masked if `depth == 0` (at Root Screen) |
| `4` | `INJECT_SQL_PAYLOAD` | `SECURITY_TESTING` | Inject SQL injection payloads into active input fields | Masked if `input_fields_count == 0` |
| `5` | `START_ACTIVITY` | `SECURITY_TESTING` | Launch target exported Activity directly via `am start` | Masked if `exported_activities == 0` |
| `6` | `QUERY_PROVIDER` | `SECURITY_TESTING` | Query target Content Provider URI via `content query` | Masked if `exported_providers == 0` |
| `7` | `FINISH` | `LIFECYCLE` | Conclude audit session cleanly and collect audit rewards | Always valid (1) |

Dynamic action masks are returned on every `reset()` and `step()` inside `info["action_mask"]` (length 8 boolean array).

---

## 🔍 Observation Space Specification (117-D Tensor)

Every observation is a 1-D vector of **117 continuous values bounded in `[0.0, 1.0]`** (`dtype=np.float32`), structured across 17 domain groups:

| Group | Dimension Range | Group Name | Features Encoded |
| :---: | :---: | :--- | :--- |
| **1** | `0 - 2` | **Meta & Step Metrics** | Step progress `(step / max_steps)`, Remaining step budget, Last action ID one-hot normalized. |
| **2** | `3 - 8` | **App Metadata** | `debuggable`, `allow_backup`, `uses_cleartext_traffic`, Target SDK normalized `(sdk / 35)`, Min SDK normalized `(sdk / 35)`, `has_custom_permissions`. |
| **3** | `9 - 28` | **Permissions (Multi-Hot)** | Multi-hot encoding for 20 critical permissions (INTERNET, READ_STORAGE, WRITE_STORAGE, LOCATION, SMS, CAMERA, CONTACTS, MICROPHONE, PHONE_STATE, BIOMETRICS, etc.). |
| **4** | `29 - 36` | **Static Attack Surface** | Total activities, Exported activities, Total services, Exported services, Total receivers, Exported receivers, Total providers, Exported providers (all normalized by 50). |
| **5** | `37 - 42` | **Static Storage Analysis** | Manifest allowBackup, DB count, Prefs file count, World-readable files, Hardcoded API keys found, Insecure backup paths. |
| **6** | `43 - 48` | **Static Crypto Analysis** | Multi-hot for 6 insecure crypto patterns (ECB mode, Static IV, Weak DES/MD5/SHA1, Hardcoded AES keys, Insecure PRNG, Custom TrustManager). |
| **7** | `49 - 53` | **Static WebView Analysis** | JavaScript enabled, DOM storage enabled, Universal access from file URLs, Cleartext content over HTTPS, Exposed JS interfaces count. |
| **8** | `54 - 58` | **Static Call Graph Metrics** | Insecure sink count, Native JNI calls count, Reflection usage count, Dynamic code loading (DexClassLoader), IPC broadcast intents count. |
| **9** | `59 - 66` | **Dynamic UI State** | UI depth level (norm / 10), Interactable widgets count (norm / 50), Input fields count (norm / 10), Has active WebView flag, Scroll position `[0.0, 1.0]`, Screen hash scalar, Is logged in flag, Current activity ID (norm / 100). |
| **10** | `67 - 74` | **Dynamic Storage Runtime** | SharedPrefs hook hits, SQLite hook hits, Internal file I/O hits, External storage hits, SharedPreferences secrets leaked count, SQLite database secrets leaked count, World-readable files accessed, Storage vulnerabilities confirmed. |
| **11** | `75 - 80` | **Dynamic Crypto Runtime** | Crypto hook hits, Insecure runtime cipher detected, Static encryption key intercepted, Weak hash function detected, Intercepted raw keys count, Crypto runtime exceptions triggered. |
| **12** | `81 - 86` | **Dynamic WebView Runtime** | WebView hook hits, Enumerated JS bridge objects, JS interface method invocations, Untrusted remote URL loaded, Malicious JS payload executed flag, Insecure local file access bypassed. |
| **13** | `87 - 92` | **Dynamic Network Telemetry** | Network hook hits, Intercepted remote host count, Cleartext HTTP requests count, SSL pinning bypassed flag, Untrusted certs accepted flag, Sensitive authentication headers leaked count. |
| **14** | `93 - 98` | **Dynamic Exported IPC** | Exported activities tested count, Exported activities exploited count, Exported services tested count, Exported services hijacked count, Exported content providers queried count, SQL injection leaks via provider count. |
| **15** | `99 - 104` | **Dynamic Logging & Telemetry** | Total logcat lines parsed (norm / 1000), Insecure PII/token logcat leaks count, System/App fatal crash count, ANR error count, StrictMode violations count, Unhandled runtime exceptions count. |
| **16** | `105 - 114` | **Vulnerability Flags (10-bit)** | Active confirmation flags for: Hardcoded Secrets, Insecure Storage, Insecure Crypto, Exported Component Exposure, Unhandled Crash / DoS, SQL Injection, Cross-Site Scripting (XSS), Path Traversal, World-Readable Files, SSL Bypass. |
| **17** | `115 - 116` | **Exploration & Coverage** | Unique screens visited coverage `[0.0, 1.0]`, Cumulative vulnerability discovery score `[0.0, 1.0]`. |

---

## 🧠 Dual-Dispatch Architecture

```
                                      ┌──────────────────────────────────────┐
                                      │        RL Agent / Benchmark          │
                                      │  (Stable-Baselines3, Custom DQN)     │
                                      └──────────────────┬───────────────────┘
                                                         │ env.step(action)
                                                         ▼
                                      ┌──────────────────────────────────────┐
                                      │     SecurityEnv (AndroidSecurityEnv) │
                                      └──────────────────┬───────────────────┘
                                                         │
                                        ┌────────────────┴────────────────┐
                                        ▼                                 ▼
                         Path 1: Numerical RL Stream       Path 2: Semantic RAG Reasoner
                         ┌───────────────────────────┐     ┌───────────────────────────┐
                         │  • StateValidator         │     │  • Fast-Path Delta Check  │
                         │  • StateBuilder           │     │  • Domain Knowledge RAG   │
                         │  • StateEncoder (117-D)   │     │  • Gemini LLM Reasoner    │
                         └─────────────┬─────────────┘     └─────────────┬─────────────┘
                                       │                                 │
                                       └────────────────┬────────────────┘
                                                        ▼
                                       ┌─────────────────────────────────┐
                                       │ RewardCalculator & Policy Engine│
                                       │ (Vulnerability Bonuses + Cost)  │
                                       └────────────────┬────────────────┘
                                                        │ (obs, reward, done, info)
                                                        ▼
```

---

## 🌐 Embedded In-Memory Host Architecture & WebSocket Connectivity

`secenvY` natively embeds the WebSocket gateway server directly inside the Gymnasium environment in a background daemon thread, eliminating the need for standalone server processes and achieving **zero loopback network latency** in Python memory:

### 1. Host Mode (Default)
When initializing `SecurityEnv()`, the environment automatically hosts the WebSocket server on `ws://localhost:8000/ws/session` (or configured host/port):

```python
from secenvY import SecurityEnv

# Natively hosts the embedded gateway in memory
env = SecurityEnv()

# Prints connection banner with exact URL (e.g. ws://localhost:8000/ws/session?session_id=secenv-8f2a)
# Pauses and completes handshake when Local State Manager connects
obs, info = env.reset()
```

### 2. Mock Mode (Fast Offline Simulation)
For sub-0.5ms offline reinforcement learning benchmarks without physical devices:

```python
from secenvY import SecurityEnv, MockSystemGateway

env = SecurityEnv(gateway=MockSystemGateway())
obs, info = env.reset(seed=42)
```

---

## 🧪 Training & Reference Examples

The repository includes ready-to-run reference implementations under [`examples/`](file:///home/berserker/Documents/Android%20/SecEnv/examples):

- **Stable-Baselines3 Benchmark**:
  ```bash
  python examples/train_stable_baselines.py
  ```
- **Custom Dueling Double DQN with Prioritized Experience Replay**:
  ```bash
  python examples/train_custom_agent.py
  ```
- **Standalone Tensor Conversion Utility**:
  ```python
  from examples.tensor_converter import TensorConverter
  converter = TensorConverter()
  state_tensor = converter.to_tensor(obs, device="cuda") # [1, 117]
  ```

---

## 🧪 Verification & Automated Testing

Run the full validation suite:

```bash
# Run all unit, compliance, and integration tests
pytest tests/ -v

# Run performance and SLA benchmark tests (< 5ms SLA)
pytest tests/test_pipeline_performance.py -v -s
```

---

## 📄 License

Apache-2.0 License. See [LICENSE](LICENSE) for details.
