Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 31 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,52 +2,67 @@

Shared Go engine for the CatNet scanning ecosystem.

## Documentation & Contracts

Before adopting `catnet-core`, please review our [API Stability Policy](docs/contracts/api-stability.md).

## Packages

| Package | Funções e Tipos Públicos | Descrição |
| Package | Public Types & Functions | Description |
|---|---|---|
| `pkg/scanner` | `DeviceInfo`, `ScanConfig`, `DefaultConfig`, `StartScan`, `StopScan`, `Ping`, `ReverseDNS`, `GetMAC`, `ScanPorts`, `ParseRange` | Lógica central de varredura e primitivas de rede. |
| `pkg/exporter` | `ExportJSON`, `ExportXML`, `ExportCSV` | Funções para exportação segura de resultados (prevenção contra CSV injection). |
| `pkg/engine` | `ScanConfig`, `DefaultConfig`, `StartScan` | Main scan orchestrator using `context.Context`. |
| `pkg/results` | `DeviceInfo` | Core models used across the ecosystem. |
| `pkg/targets` | `ParseRange` | Target parsing and CIDR utilities. |
| `pkg/discovery` | `Ping`, `ReverseDNS`, `GetMAC` | Host liveness and resolution primitives. |
| `pkg/ports` | `ScanPorts` | Port scanning utilities. |
| `pkg/exporter` | `ExportJSON`, `ExportXML`, `ExportCSV` | Safe result export functions (with CSV injection prevention). |
| `pkg/scanner` | *Deprecated* | Temporary compatibility wrapper. Do not use for new code. |

## Quickstart

```go
package main

import (
"context"
"fmt"
"github.com/mendsec/catnet-core/pkg/scanner"

"github.com/mendsec/catnet-core/pkg/engine"
"github.com/mendsec/catnet-core/pkg/results"
)

func main() {
ips := []string{"192.168.1.1"}
cfg := scanner.DefaultConfig()
cfg := engine.DefaultConfig()
cfg.Sanitize()

err := scanner.StartScan(ips, cfg, func(d scanner.DeviceInfo) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

err := engine.StartScan(ctx, ips, cfg, func(d results.DeviceInfo) {
if d.IsAlive {
fmt.Printf("Encontrado: %s (%s)\n", d.IP, d.MAC)
fmt.Printf("Found: %s (%s)\n", d.IP, d.MAC)
}
}, func(progress float64) {
fmt.Printf("Progresso: %.2f%%\n", progress*100)
fmt.Printf("Progress: %.2f%%\n", progress*100)
})

if err != nil {
panic(err)
fmt.Printf("Scan failed: %v\n", err)
}
}
```

## Ecosystem

| Repositório | Papel |
| Repository | Role |
|---|---|
| [`catnet-core`](https://github.com/mendsec/catnet-core) | Engine Go compartilhada — sem GUI |
| [`catnet-scanner`](https://github.com/mendsec/catnet-scanner) | Frontend desktop Go + Wails + React |
| [`catnet`](https://github.com/mendsec/catnet) | CLI Go scriptável |
| [`catnet-tui`](https://github.com/mendsec/catnet-tui) | TUI interativa Go + Bubble Tea |
| [`catnet-core`](https://github.com/mendsec/catnet-core) | Shared Go engine — no GUI |
| [`catnet-scanner`](https://github.com/mendsec/catnet-scanner) | Desktop frontend (Go + Wails + React) |
| [`catnet`](https://github.com/mendsec/catnet) | Scriptable Go CLI |
| [`catnet-tui`](https://github.com/mendsec/catnet-tui) | Interactive TUI (Go + Bubble Tea) |

## Status

Versão atual: v0.1.0
Veja o [CHANGELOG.md](CHANGELOG.md) para detalhes.
Current version: v0.1.0
See [CHANGELOG.md](CHANGELOG.md) for details.
48 changes: 48 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Arquitetura: catnet-core

O `catnet-core` é o motor compartilhado de varredura e descoberta de rede para o ecossistema CatNet. Ele foi projetado para ser leve, não possuir dependências externas de terceiros (apenas a biblioteca padrão do Go) e funcionar tanto no Windows quanto em sistemas POSIX.

A ausência de abstrações de interface desnecessárias e dependências garante que ele sirva como um núcleo de alta performance para os componentes upstream (`catnet-scanner`, `catnet-tui`, `catnet-cli`).

## Estrutura de Pacotes

A base do código é dividida em dois pacotes principais:

### 1. `pkg/scanner`
Este pacote gerencia toda a lógica de varredura, orquestração concorrente e chamadas de rede baixo-nível.
- **Orquestração Concorrente (`scan.go`)**: Implementa a função `StartScan`, utilizando um pool de goroutines parametrizado pelo `ScanConfig`. O controle de fluxo é garantido por `context.Context`, `sync.Mutex` e `atomic.Bool` para evitar scans paralelos conflitantes.
- **Primitivas de Rede (`net.go`)**: Funções unificadas e públicas para varredura (como `Ping`, `ScanPorts`, `GetMAC` e `ReverseDNS`).
- **Resolução Específica de Sistema Operacional (`os_windows.go` e `os_posix.go`)**:
- *Windows*: Utiliza `syscall` para acessar a API do Windows (`iphlpapi.dll` via `SendARP`) evitando o spawn de subprocessos lentos sempre que possível.
- *POSIX*: Faz fallback para comandos do sistema operacional (`ping` e `arp` via `os/exec`) assegurando compatibilidade geral.
- **Tratamento de Ranges (`utils.go`)**: Lógica de parsing de IPs capaz de entender e traduzir sub-redes CIDR (`/24`), intervalos com hífen (`192.168.1.10-20`) e IPs unitários em blocos compatíveis para varredura.

### 2. `pkg/exporter`
Separa estritamente a varredura da serialização. Recebe as structs completas (`scanner.DeviceInfo`) e as formata em padrões de mercado, garantindo a integridade dos dados gerados.
- Formatos suportados: `JSON`, `XML` e `CSV`.
- Segurança: A função de exportação para CSV traz sanitização embutida para mitigar vulnerabilidades de Injeção de CSV (CSV Injection), filtrando prefixos de execução maliciosa originados nas resoluções de Hostname e vendor.

## Diagrama de Execução

```mermaid
flowchart TD
App[Frontend / CLI / TUI] -->|1. Passa Lista de IPs e ScanConfig| ScannerCore(pkg/scanner)

subgraph ScannerCore
StartScan --> |Goroutine Pool| Workers
Workers --> net.Ping
Workers --> net.ScanPorts
Workers --> net.GetMAC
Workers --> net.ReverseDNS
end

ScannerCore -->|2. Emite onResult e onProgress callbacks| App

App -->|3. Passa []DeviceInfo para exportação| ExporterCore(pkg/exporter)

subgraph ExporterCore
ExportJSON
ExportXML
ExportCSV --> |Sanitização contra CSV Injection| CSV
end
```
54 changes: 54 additions & 0 deletions docs/architecture/changes-milestone-1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Milestone 1: Core Architecture Hardening

## Overview

As part of Milestone 1, `catnet-core` underwent significant architectural hardening. The goal was to remove the monolithic `pkg/scanner` and split responsibilities into focused domain packages, establish a context-aware execution model, and set strict API stability guidelines for downstream consumers.

## Package Boundaries

### Before
All scanning, parsing, network, and execution logic was housed inside a single package: `pkg/scanner`.
The entry point `StartScan` relied on global variables (`sync.Mutex`, `atomic.Bool`) preventing multiple concurrent scan jobs from running in the same process.

### After
The responsibilities were divided into the following domain packages:
- **`pkg/engine`**: Contains `ScanConfig`, `DefaultConfig`, and the context-aware `StartScan` orchestrator.
- **`pkg/results`**: Defines `DeviceInfo` as the standard ecosystem result schema.
- **`pkg/targets`**: Contains `ParseRange` and internal CIDR/dash range parsing tools.
- **`pkg/discovery`**: Contains `Ping` and OS-specific liveness logic, `ReverseDNS`, and `GetMAC`.
- **`pkg/ports`**: Contains `ScanPorts` logic.

### Deprecation Shim
A new temporary file `pkg/scanner/shim.go` was introduced. `pkg/scanner` is now officially **deprecated**. The shim aliases the structs, functions, and variables to their new respective packages, maintaining backward compatibility while consumers like `catnet-scanner` and `catnet-tui` migrate.

## API Changes

### Context-Aware Execution
- `engine.StartScan` now accepts a `context.Context` as its first parameter instead of relying on a global package lock.
- `scanner.StopScan` is deprecated. While the shim maintains it using a hidden package-level context, all new integrations should manage cancellation directly through the passed context.

### Global State Removal
- Global variables `isScanning`, `scanMu`, and `cancelScan` were completely removed from `pkg/engine`.

## File Operations

- **Created Directories**: `pkg/engine`, `pkg/results`, `pkg/targets`, `pkg/discovery`, `pkg/ports`, `docs/contracts`, `docs/architecture`.
- **Moved/Renamed**:
- `pkg/scanner/scan.go` -> `pkg/engine/scan.go`
- `pkg/scanner/scan_test.go` -> `pkg/engine/scan_test.go`
- `pkg/scanner/config.go` -> `pkg/engine/config.go`
- `pkg/scanner/device.go` -> `pkg/results/device.go`
- `pkg/scanner/utils.go` -> `pkg/targets/parse.go`
- `pkg/scanner/utils_test.go` -> `pkg/targets/parse_test.go`
- `pkg/scanner/os_windows.go` -> `pkg/discovery/os_windows.go`
- `pkg/scanner/os_posix.go` -> `pkg/discovery/os_posix.go`
- `pkg/scanner/net.go` -> `pkg/discovery/net.go`
- `pkg/scanner/net_test.go` -> `pkg/discovery/net_test.go`
- **Created**:
- `pkg/ports/scanner.go` (Extracted `ScanPorts`)
- `pkg/scanner/shim.go` (Deprecation wrapper)
- `docs/contracts/api-stability.md`
- `docs/architecture/changes-milestone-1.md`

## Test Enhancements
All tests were adjusted to target the new domain boundaries. Removed unused imports and verified that `go test ./...` and `go build ./...` succeed seamlessly on both Windows and POSIX environments.
Binary file removed docs/archives/phase2_refactor_and_cli.md
Binary file not shown.
26 changes: 0 additions & 26 deletions docs/archives/phase3_react_refactor_plan.md

This file was deleted.

29 changes: 0 additions & 29 deletions docs/archives/phase3_walkthrough.md

This file was deleted.

40 changes: 0 additions & 40 deletions docs/archives/phase4_tui_plan.md

This file was deleted.

50 changes: 0 additions & 50 deletions docs/archives/phase4_tui_walkthrough.md

This file was deleted.

Loading
Loading