Commit ·
73c5503
0
Parent(s):
Projeto
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- .gitignore +13 -0
- README.md +205 -0
- app.py +153 -0
- data/data.yaml +16 -0
- data_real_aws/data_real_aws.yaml +16 -0
- data_real_aws/images/train/index100_png.rf.0b3b0491fae93b76f5f10f0b6b88048e.jpg +0 -0
- data_real_aws/images/train/index101_jpg.rf.711b15e7878901c8966ad59f1770b609.jpg +0 -0
- data_real_aws/images/train/index104_png.rf.1aef9726ad25339de7b5c8a62e8fc520.jpg +0 -0
- data_real_aws/images/train/index106_png.rf.889771ba6c48c78058bb4d912306757a.jpg +0 -0
- data_real_aws/images/train/index107_png.rf.ac4fc53867993651cbc76c51814308d8.jpg +0 -0
- data_real_aws/images/train/index108_png.rf.9ea7a8d275ad35b11924853cb2f493ad.jpg +0 -0
- data_real_aws/images/train/index109_png.rf.ab4a4481e90632ff37f2f9063fd5ab08.jpg +0 -0
- data_real_aws/images/train/index10_png.rf.c8ef7566cdfd99d61bafd978a43762f8.jpg +0 -0
- data_real_aws/images/train/index111_png.rf.4d4e35c5da185bce7a5bafe734fa4f88.jpg +0 -0
- data_real_aws/images/train/index112_png.rf.62ddc5abd872d6b6b2bdbc11c0d29b5a.jpg +0 -0
- data_real_aws/images/train/index114_png.rf.580b4abf793ee82906723818ef5fda9c.jpg +0 -0
- data_real_aws/images/train/index118_jpg.rf.5243c4bfab4979b13b738eb204a8a86e.jpg +0 -0
- data_real_aws/images/train/index119_png.rf.0a4cacb6190388ff2c7e4aa6b67e16c0.jpg +0 -0
- data_real_aws/images/train/index11_png.rf.86d38aa4ec5b3362aaaed5128419131b.jpg +0 -0
- data_real_aws/images/train/index120_png.rf.ee774811f7030b17f2f7c7feae253be4.jpg +0 -0
- data_real_aws/images/train/index121_png.rf.2d87cddb6a871b06eef74ed0925b8b05.jpg +0 -0
- data_real_aws/images/train/index123_png.rf.07e80b32fb6ad207559c5ab24aef2b73.jpg +0 -0
- data_real_aws/images/train/index124_png.rf.c9f98b7bf3d9a6de06897f38ba6fee99.jpg +0 -0
- data_real_aws/images/train/index125_png.rf.fac2e10a2feed221e4ea3693c2f9da31.jpg +0 -0
- data_real_aws/images/train/index126_png.rf.8f65b36bb6fbc27e21165199da906762.jpg +0 -0
- data_real_aws/images/train/index128_png.rf.854083f70d61fce164ca4df7c540b5c5.jpg +0 -0
- data_real_aws/images/train/index12_png.rf.96f336e89e4682118bc7aa83be91d807.jpg +0 -0
- data_real_aws/images/train/index130_png.rf.a6351d5860d4eca3687c402dfb66544e.jpg +0 -0
- data_real_aws/images/train/index131_png.rf.7d2f7a4c97a2dcb3d235645bac98636d.jpg +0 -0
- data_real_aws/images/train/index134_png.rf.54acae9bec3d0218066bc11334fc4b5e.jpg +0 -0
- data_real_aws/images/train/index135_png.rf.c51ffcadeaeae4b91c6cee576150b26b.jpg +0 -0
- data_real_aws/images/train/index136_png.rf.c80b0050b0ed6462ba6a33a1052cdeda.jpg +0 -0
- data_real_aws/images/train/index137_jpg.rf.6bf3aaa3747b666ca037bbba23f2132f.jpg +0 -0
- data_real_aws/images/train/index139_png.rf.4c4a782d8607d54ff4bcc0684ab3b0c2.jpg +0 -0
- data_real_aws/images/train/index142_png.rf.77a0df2423eb3f79e7851d522bc9a8ba.jpg +0 -0
- data_real_aws/images/train/index143_png.rf.06c94a1ab4446796aae4fbd3fd3067c8.jpg +0 -0
- data_real_aws/images/train/index144_png.rf.fd9fc39fc83e316b556c221c514461e5.jpg +0 -0
- data_real_aws/images/train/index145_png.rf.7b41dbffb5c902f0550c1e75ab76d789.jpg +0 -0
- data_real_aws/images/train/index147_jpeg.rf.5b56e4a6ab9e4fd0168ac38f446fdefe.jpg +0 -0
- data_real_aws/images/train/index14_png.rf.642e6c420937aa2c4a242ec8e911416a.jpg +0 -0
- data_real_aws/images/train/index150_png.rf.edc93334ea5c63b012b9fbfd6e52e383.jpg +0 -0
- data_real_aws/images/train/index151_jpg.rf.dcf6a136899b9a7fc7a4046d2aea487c.jpg +0 -0
- data_real_aws/images/train/index154_jpg.rf.914756a32eee1df9ddf1a6a87b684b4c.jpg +0 -0
- data_real_aws/images/train/index156_png.rf.cc357c27cef1ce9949d9983e2a750c26.jpg +0 -0
- data_real_aws/images/train/index157_jpeg.rf.ac986728e72db9a96b3f34e115ad6a22.jpg +0 -0
- data_real_aws/images/train/index158_png.rf.13fd5641f279dfd0892d857c982bcdef.jpg +0 -0
- data_real_aws/images/train/index159_png.rf.b354f7eb271dd5f68503996980ea6407.jpg +0 -0
- data_real_aws/images/train/index15_jpg.rf.704ea6cf8bc277289bb837e8b4b40e30.jpg +0 -0
- data_real_aws/images/train/index160_png.rf.fb157896a0ea484f69c39db7ab58478b.jpg +0 -0
.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.venv/
|
| 4 |
+
venv/
|
| 5 |
+
runs_threat_modeling/
|
| 6 |
+
data/images/
|
| 7 |
+
data/labels/
|
| 8 |
+
yolov8n.pt
|
| 9 |
+
.DS_Store
|
| 10 |
+
.env
|
| 11 |
+
# Observação: models/best.pt (modelo treinado final) É versionado propositalmente
|
| 12 |
+
# via Git LFS para que o Hugging Face Space suba com o modelo pronto.
|
| 13 |
+
|
README.md
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Modelagem de Ameaças (STRIDE)
|
| 3 |
+
emoji: 🛡️
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: "5.27.0"
|
| 8 |
+
python_version: "3.11"
|
| 9 |
+
app_file: app.py
|
| 10 |
+
pinned: false
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# 🛡️ Modelagem de Ameaças — STRIDE
|
| 14 |
+
|
| 15 |
+
MVP desenvolvido para o Hackathon (Pós-Tech FIAP) da **FIAP Software Security**.
|
| 16 |
+
O sistema interpreta automaticamente um diagrama de arquitetura de software
|
| 17 |
+
(imagem), identifica os componentes presentes (usuário, servidor, API Gateway,
|
| 18 |
+
banco de dados etc.) usando um modelo de visão computacional treinado de forma
|
| 19 |
+
supervisionada, e gera um **Relatório de Modelagem de Ameaças** baseado na
|
| 20 |
+
metodologia **STRIDE**, com contramedidas recomendadas por componente.
|
| 21 |
+
|
| 22 |
+
Aplicação em produção: `https://huggingface.co/spaces/<seu-usuario>/<seu-space>`
|
| 23 |
+
|
| 24 |
+
Documentação completa do fluxo de desenvolvimento: [`docs/fluxo_solucao.md`](docs/fluxo_solucao.md).
|
| 25 |
+
|
| 26 |
+
---
|
| 27 |
+
|
| 28 |
+
## 1. Objetivos atendidos
|
| 29 |
+
|
| 30 |
+
- [x] Sistema que interpreta um diagrama de arquitetura e identifica componentes.
|
| 31 |
+
- [x] Geração automática de Relatório de Modelagem de Ameaças (STRIDE).
|
| 32 |
+
- [x] Construção de um dataset de imagens de arquitetura de software
|
| 33 |
+
(sintético — ver seção 6, Limitações).
|
| 34 |
+
- [x] Anotação do dataset em formato YOLO (bounding box por componente).
|
| 35 |
+
- [x] Treinamento de um modelo supervisionado (YOLOv8 via Ultralytics).
|
| 36 |
+
- [x] Sistema que busca vulnerabilidades (ameaças STRIDE) e contramedidas
|
| 37 |
+
por componente, via base de conhecimento (`src/threat_kb.py`).
|
| 38 |
+
|
| 39 |
+
## 2. Arquitetura da solução
|
| 40 |
+
|
| 41 |
+
```
|
| 42 |
+
Usuário → app.py (Gradio) → ComponentDetector → threat_kb.py → report_generator.py → Relatório (Markdown + PDF)
|
| 43 |
+
↑
|
| 44 |
+
models/best.pt (YOLOv8 treinado)
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
Estrutura de pastas:
|
| 48 |
+
|
| 49 |
+
```
|
| 50 |
+
.
|
| 51 |
+
├── app.py # Interface Gradio (entry point do Hugging Face Space)
|
| 52 |
+
├── requirements.txt
|
| 53 |
+
├── .env.example # Template de variáveis de ambiente (copie para .env)
|
| 54 |
+
├── src/
|
| 55 |
+
│ ├── dataset_generator.py # Gera dataset sintético anotado (formato YOLO)
|
| 56 |
+
│ ├── train.py # Treina o modelo YOLOv8 sobre o dataset
|
| 57 |
+
│ ├── finetune.py # Continua o treino com dados reais anotados
|
| 58 |
+
│ ├── detector.py # Detector supervisionado (com inferência por tiles)
|
| 59 |
+
│ ├── llm_detector.py # Detector alternativo via integração externa (opcional)
|
| 60 |
+
│ ├── threat_kb.py # Base de conhecimento STRIDE (ameaças + contramedidas)
|
| 61 |
+
│ └── report_generator.py # Gera o relatório final (Markdown + PDF)
|
| 62 |
+
├── scripts/
|
| 63 |
+
│ └── convert_roboflow_aws.py # Converte datasets Roboflow (ícones AWS) para as 12 classes do projeto
|
| 64 |
+
├── data/ # Dataset sintético gerado (images/ + labels/ + data.yaml)
|
| 65 |
+
├── data_real_aws/ # Dataset real (210 imagens, ícones AWS) já convertido, pronto para finetune.py
|
| 66 |
+
├── models/ # models/best.pt — modelo treinado (versionado via Git LFS)
|
| 67 |
+
├── examples/ # Imagens de exemplo usadas na interface
|
| 68 |
+
└── docs/
|
| 69 |
+
└── fluxo_solucao.md # Documentação do fluxo de desenvolvimento
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
## 3. Como executar localmente
|
| 73 |
+
|
| 74 |
+
```bash
|
| 75 |
+
git clone <url-do-repositorio>
|
| 76 |
+
cd <nome-do-repositorio>
|
| 77 |
+
|
| 78 |
+
python -m venv venv
|
| 79 |
+
source venv/bin/activate # Linux/Mac
|
| 80 |
+
# venv\Scripts\activate # Windows (cmd/PowerShell)
|
| 81 |
+
# source venv/Scripts/activate # Windows (Git Bash)
|
| 82 |
+
|
| 83 |
+
pip install -r requirements.txt
|
| 84 |
+
|
| 85 |
+
# 1) Gerar o dataset sintético anotado
|
| 86 |
+
python src/dataset_generator.py
|
| 87 |
+
|
| 88 |
+
# 2) Treinar o modelo supervisionado (requer internet na 1ª execução,
|
| 89 |
+
# para baixar o checkpoint base yolov8n.pt)
|
| 90 |
+
python src/train.py --data data/data.yaml --epochs 100
|
| 91 |
+
|
| 92 |
+
# 3) Rodar a aplicação
|
| 93 |
+
python app.py
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
A aplicação abre em `http://127.0.0.1:7860`.
|
| 97 |
+
|
| 98 |
+
Se `models/best.pt` ainda não existir, a aplicação roda em **modo
|
| 99 |
+
demonstração** (heurística de segmentação por cor), garantindo que o fluxo
|
| 100 |
+
completo (upload → detecção → relatório) seja demonstrável mesmo antes do
|
| 101 |
+
treino.
|
| 102 |
+
|
| 103 |
+
## 4. Como publicar no Hugging Face Spaces
|
| 104 |
+
|
| 105 |
+
1. Crie um Space em https://huggingface.co/new-space com **SDK: Gradio**.
|
| 106 |
+
2. Clone o repositório do Space e copie todos os arquivos deste projeto para
|
| 107 |
+
dentro dele (o `README.md` já contém o front-matter YAML exigido pelo
|
| 108 |
+
Spaces).
|
| 109 |
+
3. Versione `models/best.pt` com **Git LFS** (arquivo binário grande):
|
| 110 |
+
```bash
|
| 111 |
+
git lfs install
|
| 112 |
+
git lfs track "*.pt"
|
| 113 |
+
git add .gitattributes models/best.pt
|
| 114 |
+
git commit -m "Adiciona modelo treinado"
|
| 115 |
+
```
|
| 116 |
+
4. Envie tudo (`git push`) — o Space instala `requirements.txt` e executa
|
| 117 |
+
`app.py` automaticamente.
|
| 118 |
+
|
| 119 |
+
Sem `models/best.pt`, o Space sobe igualmente em modo demonstração.
|
| 120 |
+
|
| 121 |
+
## 5. Detector alternativo (opcional, complementar)
|
| 122 |
+
|
| 123 |
+
Além do detector supervisionado (requisito do hackathon), o projeto inclui
|
| 124 |
+
um detector alternativo baseado em integração externa (`src/llm_detector.py`),
|
| 125 |
+
útil para diagramas reais onde o detector supervisionado ainda tem
|
| 126 |
+
classificação limitada (ver seção 7).
|
| 127 |
+
|
| 128 |
+
Para habilitar:
|
| 129 |
+
|
| 130 |
+
```bash
|
| 131 |
+
cp .env.example .env
|
| 132 |
+
# edite .env e preencha ANTHROPIC_API_KEY=sua-chave-aqui
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
Com a chave configurada, a interface passa a exibir um seletor de motor de
|
| 136 |
+
detecção ("Supervisionado" ou "Alternativo"). Sem a chave, apenas o detector
|
| 137 |
+
supervisionado fica disponível — a aplicação funciona normalmente em
|
| 138 |
+
qualquer um dos dois casos.
|
| 139 |
+
|
| 140 |
+
**Este recurso é complementar, não substitui o pipeline supervisionado**,
|
| 141 |
+
que continua sendo a implementação central do projeto e atende ao
|
| 142 |
+
requisito de detecção supervisionada do desafio.
|
| 143 |
+
|
| 144 |
+
## 6. Metodologia STRIDE aplicada
|
| 145 |
+
|
| 146 |
+
Para cada componente identificado, o sistema consulta `src/threat_kb.py`,
|
| 147 |
+
que mapeia o tipo de componente para as categorias STRIDE relevantes:
|
| 148 |
+
|
| 149 |
+
| Letra | Categoria | Pergunta-guia |
|
| 150 |
+
|---|---|---|
|
| 151 |
+
| S | Spoofing (Falsificação de identidade) | O agente é quem afirma ser? |
|
| 152 |
+
| T | Tampering (Violação de integridade) | Os dados/código podem ser alterados indevidamente? |
|
| 153 |
+
| R | Repudiation (Repúdio) | É possível provar quem fez a ação? |
|
| 154 |
+
| I | Information Disclosure (Exposição de informação) | Dados sensíveis podem ser vistos por quem não deveria? |
|
| 155 |
+
| D | Denial of Service (Negação de serviço) | O serviço pode ficar indisponível? |
|
| 156 |
+
| E | Elevation of Privilege (Elevação de privilégio) | Um ator pode obter mais permissões do que deveria? |
|
| 157 |
+
|
| 158 |
+
Cada ameaça retornada inclui descrição contextualizada, severidade
|
| 159 |
+
(Baixa/Média/Alta/Crítica) e contramedida recomendada.
|
| 160 |
+
|
| 161 |
+
## 7. Limitações conhecidas e trabalhos futuros
|
| 162 |
+
|
| 163 |
+
- **Dataset sintético como base do treino inicial**: não existe dataset
|
| 164 |
+
público anotado de diagramas de arquitetura de software; `dataset_generator.py`
|
| 165 |
+
cria diagramas artificiais para viabilizar o treino supervisionado desde o
|
| 166 |
+
início do projeto. Isso garante boa **localização** de componentes mesmo em
|
| 167 |
+
diagramas reais, mas a **classificação** é limitada nesses casos, já que o
|
| 168 |
+
modelo não vê o estilo visual real de ícones oficiais (AWS/Azure/GCP)
|
| 169 |
+
apenas com dados sintéticos.
|
| 170 |
+
- **Dataset real integrado**: o projeto já inclui `data_real_aws/`, um
|
| 171 |
+
dataset real de 210 imagens com ícones oficiais da AWS (derivado do
|
| 172 |
+
dataset público "AWS Icon Detector" do Roboflow, convertido de 182
|
| 173 |
+
classes específicas para as 12 classes deste projeto via
|
| 174 |
+
`scripts/convert_roboflow_aws.py`). Use-o com `src/finetune.py` para
|
| 175 |
+
melhorar a classificação em diagramas reais:
|
| 176 |
+
```bash
|
| 177 |
+
python src/finetune.py --data data_real_aws/data_real_aws.yaml --epochs 30
|
| 178 |
+
```
|
| 179 |
+
- **Inferência por tiles**: `detector.py` recorta imagens grandes em janelas
|
| 180 |
+
sobrepostas antes de rodar o modelo, para não perder ícones pequenos em
|
| 181 |
+
diagramas densos.
|
| 182 |
+
- **Detector alternativo**: `llm_detector.py` oferece uma alternativa baseada em
|
| 183 |
+
integração externa, que não depende de treino específico e tende a
|
| 184 |
+
generalizar melhor para diagramas reais — ver seção 5.
|
| 185 |
+
- **Base de conhecimento estática**: `threat_kb.py` é baseada em regras
|
| 186 |
+
fixas; pode ser estendida com busca em bases externas (CWE, OWASP, MITRE
|
| 187 |
+
ATT&CK) via RAG.
|
| 188 |
+
|
| 189 |
+
## 8. Créditos e licenças de dados de terceiros
|
| 190 |
+
|
| 191 |
+
O dataset `data_real_aws/` é derivado do dataset público **"AWS Icon
|
| 192 |
+
Detector"** (Roboflow, licença CC BY 4.0):
|
| 193 |
+
https://universe.roboflow.com/aws-icons/aws-icon-detector
|
| 194 |
+
|
| 195 |
+
As imagens originais foram mantidas; as anotações foram remapeadas das 182
|
| 196 |
+
classes originais para as 12 classes deste projeto via
|
| 197 |
+
`scripts/convert_roboflow_aws.py`. Crédito ao autor original do dataset no
|
| 198 |
+
Roboflow Universe.
|
| 199 |
+
|
| 200 |
+
## 9. Entregáveis do hackathon
|
| 201 |
+
|
| 202 |
+
- [x] Documentação do fluxo de desenvolvimento: `docs/fluxo_solucao.md`
|
| 203 |
+
- [x] Código-fonte completo e comentado neste repositório
|
| 204 |
+
- [ ] Vídeo de até 15 minutos explicando a solução
|
| 205 |
+
- [ ] Link do GitHub do projeto
|
app.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
app.py
|
| 4 |
+
|
| 5 |
+
Interface Gradio do sistema de Modelagem de Ameaças (STRIDE).
|
| 6 |
+
|
| 7 |
+
Fluxo:
|
| 8 |
+
1. Upload de um diagrama de arquitetura de software.
|
| 9 |
+
2. ComponentDetector identifica os componentes presentes na imagem.
|
| 10 |
+
3. A imagem é anotada com as detecções (bounding boxes).
|
| 11 |
+
4. report_generator cruza os componentes com a base de conhecimento
|
| 12 |
+
STRIDE e monta o relatório de ameaças.
|
| 13 |
+
5. O relatório é exibido em Markdown e disponibilizado em PDF.
|
| 14 |
+
|
| 15 |
+
Ponto de entrada padrão para Hugging Face Spaces (sdk: gradio, app_file: app.py).
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import tempfile
|
| 21 |
+
|
| 22 |
+
import gradio as gr
|
| 23 |
+
from PIL import ImageDraw, ImageFont
|
| 24 |
+
|
| 25 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 26 |
+
|
| 27 |
+
from detector import ComponentDetector
|
| 28 |
+
from report_generator import build_markdown_report, save_pdf_report
|
| 29 |
+
import llm_detector
|
| 30 |
+
|
| 31 |
+
MODEL_PATH = os.path.join(os.path.dirname(__file__), "models", "best.pt")
|
| 32 |
+
detector = ComponentDetector(model_path=MODEL_PATH, conf_threshold=0.35)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _draw_detections(image, detections):
|
| 36 |
+
annotated = image.convert("RGB").copy()
|
| 37 |
+
draw = ImageDraw.Draw(annotated)
|
| 38 |
+
try:
|
| 39 |
+
font = ImageFont.truetype("DejaVuSans-Bold.ttf", 14)
|
| 40 |
+
except Exception:
|
| 41 |
+
font = ImageFont.load_default()
|
| 42 |
+
|
| 43 |
+
for det in detections:
|
| 44 |
+
x0, y0, x1, y1 = det.box
|
| 45 |
+
draw.rectangle([x0, y0, x1, y1], outline=(220, 30, 30), width=3)
|
| 46 |
+
label = f"{det.label.replace('_', ' ')} ({det.confidence:.0%})"
|
| 47 |
+
draw.rectangle([x0, max(0, y0 - 16), x0 + 8 * len(label), y0], fill=(220, 30, 30))
|
| 48 |
+
draw.text((x0 + 2, max(0, y0 - 16)), label, fill=(255, 255, 255), font=font)
|
| 49 |
+
return annotated
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def analisar_diagrama(imagem, nome_sistema, motor_deteccao):
|
| 53 |
+
if imagem is None:
|
| 54 |
+
return None, "Envie uma imagem de diagrama de arquitetura para começar.", None
|
| 55 |
+
|
| 56 |
+
usar_llm = motor_deteccao == "Alternativo — melhor para diagramas reais"
|
| 57 |
+
|
| 58 |
+
if usar_llm and llm_detector.is_available():
|
| 59 |
+
detections = llm_detector.predict(imagem)
|
| 60 |
+
demo_mode = False
|
| 61 |
+
elif usar_llm:
|
| 62 |
+
detections = []
|
| 63 |
+
aviso = ("Detector alternativo selecionado, mas ANTHROPIC_API_KEY não está configurada. "
|
| 64 |
+
"Configure-a no arquivo .env (veja .env.example) ou volte para o "
|
| 65 |
+
"detector supervisionado.")
|
| 66 |
+
return imagem, aviso, None
|
| 67 |
+
else:
|
| 68 |
+
detections = detector.predict(imagem)
|
| 69 |
+
demo_mode = detector.demo_mode
|
| 70 |
+
|
| 71 |
+
imagem_anotada = _draw_detections(imagem, detections)
|
| 72 |
+
|
| 73 |
+
nome = nome_sistema.strip() if nome_sistema and nome_sistema.strip() else "Sistema Analisado"
|
| 74 |
+
relatorio_md = build_markdown_report(detections, demo_mode=demo_mode, sistema_nome=nome)
|
| 75 |
+
|
| 76 |
+
tmp_dir = tempfile.mkdtemp()
|
| 77 |
+
pdf_path = os.path.join(tmp_dir, "relatorio_stride.pdf")
|
| 78 |
+
save_pdf_report(relatorio_md, pdf_path)
|
| 79 |
+
|
| 80 |
+
return imagem_anotada, relatorio_md, pdf_path
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
EXAMPLES_DIR = os.path.join(os.path.dirname(__file__), "examples")
|
| 84 |
+
examples = []
|
| 85 |
+
if os.path.isdir(EXAMPLES_DIR):
|
| 86 |
+
for filename in sorted(os.listdir(EXAMPLES_DIR)):
|
| 87 |
+
if filename.lower().endswith((".png", ".jpg", ".jpeg")):
|
| 88 |
+
examples.append([os.path.join(EXAMPLES_DIR, filename), "Arquitetura de Exemplo"])
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
with gr.Blocks(title="Modelagem de Ameaças — STRIDE") as demo:
|
| 92 |
+
gr.Markdown(
|
| 93 |
+
"""
|
| 94 |
+
# 🛡️ Modelagem de Ameaças (STRIDE)
|
| 95 |
+
**FIAP Software Security — MVP de detecção supervisionada de ameaças**
|
| 96 |
+
|
| 97 |
+
Envie um diagrama de arquitetura de software. O sistema identifica os
|
| 98 |
+
componentes presentes (usuários, servidores, APIs, bancos de dados etc.)
|
| 99 |
+
e gera automaticamente um Relatório de Modelagem de Ameaças baseado na
|
| 100 |
+
metodologia **STRIDE**, com contramedidas recomendadas.
|
| 101 |
+
"""
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
with gr.Row():
|
| 105 |
+
with gr.Column(scale=1):
|
| 106 |
+
entrada_imagem = gr.Image(type="pil", label="Diagrama de Arquitetura")
|
| 107 |
+
nome_sistema = gr.Textbox(
|
| 108 |
+
label="Nome do sistema (opcional)",
|
| 109 |
+
placeholder="Ex.: Sistema SEI - Plataforma de Atendimento",
|
| 110 |
+
)
|
| 111 |
+
opcoes_motor = ["Supervisionado (YOLOv8 treinado)"]
|
| 112 |
+
if llm_detector.is_available():
|
| 113 |
+
opcoes_motor.append("Alternativo — melhor para diagramas reais")
|
| 114 |
+
motor_deteccao = gr.Radio(
|
| 115 |
+
choices=opcoes_motor,
|
| 116 |
+
value=opcoes_motor[0],
|
| 117 |
+
label="Motor de detecção",
|
| 118 |
+
)
|
| 119 |
+
botao = gr.Button("🔍 Analisar Diagrama", variant="primary")
|
| 120 |
+
if examples:
|
| 121 |
+
gr.Examples(examples=examples, inputs=[entrada_imagem, nome_sistema])
|
| 122 |
+
|
| 123 |
+
with gr.Column(scale=1):
|
| 124 |
+
saida_imagem = gr.Image(type="pil", label="Componentes Identificados")
|
| 125 |
+
|
| 126 |
+
saida_relatorio = gr.Markdown(label="Relatório de Modelagem de Ameaças")
|
| 127 |
+
saida_pdf = gr.File(label="Baixar relatório em PDF")
|
| 128 |
+
|
| 129 |
+
botao.click(
|
| 130 |
+
fn=analisar_diagrama,
|
| 131 |
+
inputs=[entrada_imagem, nome_sistema, motor_deteccao],
|
| 132 |
+
outputs=[saida_imagem, saida_relatorio, saida_pdf],
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
gr.Markdown(
|
| 136 |
+
"""
|
| 137 |
+
---
|
| 138 |
+
**Supervisionado**: modelo YOLOv8 treinado sobre dataset próprio (requisito
|
| 139 |
+
do projeto). Boa localização de componentes; classificação mais confiável em
|
| 140 |
+
diagramas sintéticos, ainda limitada em ícones reais de nuvem (AWS/Azure/GCP).
|
| 141 |
+
|
| 142 |
+
**Alternativo**: usa uma integração externa via API para interpretar o diagrama
|
| 143 |
+
diretamente, sem necessidade de treino específico — tende a generalizar melhor
|
| 144 |
+
para diagramas reais. Requer `ANTHROPIC_API_KEY` configurada (veja `.env.example`).
|
| 145 |
+
|
| 146 |
+
Se nenhum modelo treinado (`models/best.pt`) estiver presente, o motor
|
| 147 |
+
Supervisionado roda em modo demonstração (heurística de cor).
|
| 148 |
+
"""
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
if __name__ == "__main__":
|
| 153 |
+
demo.launch()
|
data/data.yaml
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
path: /home/claude/threat-modeling-ai/data
|
| 2 |
+
train: images/train
|
| 3 |
+
val: images/val
|
| 4 |
+
names:
|
| 5 |
+
0: usuario
|
| 6 |
+
1: servidor_aplicacao
|
| 7 |
+
2: banco_de_dados
|
| 8 |
+
3: api_gateway
|
| 9 |
+
4: load_balancer
|
| 10 |
+
5: firewall_waf
|
| 11 |
+
6: fila_mensagens
|
| 12 |
+
7: cache
|
| 13 |
+
8: servico_externo
|
| 14 |
+
9: identity_provider
|
| 15 |
+
10: storage
|
| 16 |
+
11: cdn
|
data_real_aws/data_real_aws.yaml
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
path: /home/claude/threat-modeling-ai/data_real_aws
|
| 2 |
+
train: images/train
|
| 3 |
+
val: images/val
|
| 4 |
+
names:
|
| 5 |
+
0: usuario
|
| 6 |
+
1: servidor_aplicacao
|
| 7 |
+
2: banco_de_dados
|
| 8 |
+
3: api_gateway
|
| 9 |
+
4: load_balancer
|
| 10 |
+
5: firewall_waf
|
| 11 |
+
6: fila_mensagens
|
| 12 |
+
7: cache
|
| 13 |
+
8: servico_externo
|
| 14 |
+
9: identity_provider
|
| 15 |
+
10: storage
|
| 16 |
+
11: cdn
|
data_real_aws/images/train/index100_png.rf.0b3b0491fae93b76f5f10f0b6b88048e.jpg
ADDED
|
data_real_aws/images/train/index101_jpg.rf.711b15e7878901c8966ad59f1770b609.jpg
ADDED
|
data_real_aws/images/train/index104_png.rf.1aef9726ad25339de7b5c8a62e8fc520.jpg
ADDED
|
data_real_aws/images/train/index106_png.rf.889771ba6c48c78058bb4d912306757a.jpg
ADDED
|
data_real_aws/images/train/index107_png.rf.ac4fc53867993651cbc76c51814308d8.jpg
ADDED
|
data_real_aws/images/train/index108_png.rf.9ea7a8d275ad35b11924853cb2f493ad.jpg
ADDED
|
data_real_aws/images/train/index109_png.rf.ab4a4481e90632ff37f2f9063fd5ab08.jpg
ADDED
|
data_real_aws/images/train/index10_png.rf.c8ef7566cdfd99d61bafd978a43762f8.jpg
ADDED
|
data_real_aws/images/train/index111_png.rf.4d4e35c5da185bce7a5bafe734fa4f88.jpg
ADDED
|
data_real_aws/images/train/index112_png.rf.62ddc5abd872d6b6b2bdbc11c0d29b5a.jpg
ADDED
|
data_real_aws/images/train/index114_png.rf.580b4abf793ee82906723818ef5fda9c.jpg
ADDED
|
data_real_aws/images/train/index118_jpg.rf.5243c4bfab4979b13b738eb204a8a86e.jpg
ADDED
|
data_real_aws/images/train/index119_png.rf.0a4cacb6190388ff2c7e4aa6b67e16c0.jpg
ADDED
|
data_real_aws/images/train/index11_png.rf.86d38aa4ec5b3362aaaed5128419131b.jpg
ADDED
|
data_real_aws/images/train/index120_png.rf.ee774811f7030b17f2f7c7feae253be4.jpg
ADDED
|
data_real_aws/images/train/index121_png.rf.2d87cddb6a871b06eef74ed0925b8b05.jpg
ADDED
|
data_real_aws/images/train/index123_png.rf.07e80b32fb6ad207559c5ab24aef2b73.jpg
ADDED
|
data_real_aws/images/train/index124_png.rf.c9f98b7bf3d9a6de06897f38ba6fee99.jpg
ADDED
|
data_real_aws/images/train/index125_png.rf.fac2e10a2feed221e4ea3693c2f9da31.jpg
ADDED
|
data_real_aws/images/train/index126_png.rf.8f65b36bb6fbc27e21165199da906762.jpg
ADDED
|
data_real_aws/images/train/index128_png.rf.854083f70d61fce164ca4df7c540b5c5.jpg
ADDED
|
data_real_aws/images/train/index12_png.rf.96f336e89e4682118bc7aa83be91d807.jpg
ADDED
|
data_real_aws/images/train/index130_png.rf.a6351d5860d4eca3687c402dfb66544e.jpg
ADDED
|
data_real_aws/images/train/index131_png.rf.7d2f7a4c97a2dcb3d235645bac98636d.jpg
ADDED
|
data_real_aws/images/train/index134_png.rf.54acae9bec3d0218066bc11334fc4b5e.jpg
ADDED
|
data_real_aws/images/train/index135_png.rf.c51ffcadeaeae4b91c6cee576150b26b.jpg
ADDED
|
data_real_aws/images/train/index136_png.rf.c80b0050b0ed6462ba6a33a1052cdeda.jpg
ADDED
|
data_real_aws/images/train/index137_jpg.rf.6bf3aaa3747b666ca037bbba23f2132f.jpg
ADDED
|
data_real_aws/images/train/index139_png.rf.4c4a782d8607d54ff4bcc0684ab3b0c2.jpg
ADDED
|
data_real_aws/images/train/index142_png.rf.77a0df2423eb3f79e7851d522bc9a8ba.jpg
ADDED
|
data_real_aws/images/train/index143_png.rf.06c94a1ab4446796aae4fbd3fd3067c8.jpg
ADDED
|
data_real_aws/images/train/index144_png.rf.fd9fc39fc83e316b556c221c514461e5.jpg
ADDED
|
data_real_aws/images/train/index145_png.rf.7b41dbffb5c902f0550c1e75ab76d789.jpg
ADDED
|
data_real_aws/images/train/index147_jpeg.rf.5b56e4a6ab9e4fd0168ac38f446fdefe.jpg
ADDED
|
data_real_aws/images/train/index14_png.rf.642e6c420937aa2c4a242ec8e911416a.jpg
ADDED
|
data_real_aws/images/train/index150_png.rf.edc93334ea5c63b012b9fbfd6e52e383.jpg
ADDED
|
data_real_aws/images/train/index151_jpg.rf.dcf6a136899b9a7fc7a4046d2aea487c.jpg
ADDED
|
data_real_aws/images/train/index154_jpg.rf.914756a32eee1df9ddf1a6a87b684b4c.jpg
ADDED
|
data_real_aws/images/train/index156_png.rf.cc357c27cef1ce9949d9983e2a750c26.jpg
ADDED
|
data_real_aws/images/train/index157_jpeg.rf.ac986728e72db9a96b3f34e115ad6a22.jpg
ADDED
|
data_real_aws/images/train/index158_png.rf.13fd5641f279dfd0892d857c982bcdef.jpg
ADDED
|
data_real_aws/images/train/index159_png.rf.b354f7eb271dd5f68503996980ea6407.jpg
ADDED
|
data_real_aws/images/train/index15_jpg.rf.704ea6cf8bc277289bb837e8b4b40e30.jpg
ADDED
|
data_real_aws/images/train/index160_png.rf.fb157896a0ea484f69c39db7ab58478b.jpg
ADDED
|