Metadata-Version: 2.4
Name: secraft
Version: 0.1.2
Summary: secraft simplifies the security workflow: port scans, banners, web probing, DNS recon and credential checks as single function calls
Author: guaidao2
License-Expression: MIT
Keywords: security,pentest,recon,scanner,toolkit
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Topic :: Security
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.25
Requires-Dist: paramiko>=2.7
Requires-Dist: pymysql>=1.0
Requires-Dist: psycopg2-binary>=2.9
Requires-Dist: pymongo>=4.0
Requires-Dist: impacket>=0.11
Requires-Dist: cryptoexp>=0.2
Dynamic: license-file

# secraft

[中文文档](README.zh-CN.md) · [User guide](docs/guide.md)

**secraft simplifies the security workflow.**

Port scanning, service banners, web probing, DNS recon, credential checks — each
is one function call, and every call returns the same `Result` object with three
clear states: done, done but empty, failed. A one-off script no longer has to
juggle five libraries and five different ways of deciding whether the thing it
just did actually worked.

It is not a new language like yaklang and not a replacement for nmap, nuclei or
hydra. It is the glue layer: the common scenarios, each behind a name you can
remember.

```python
import secraft as sec

r = sec.portscan("192.168.1.1")
print(r)                    # a table you can read

if 22 in r.ports:
    sec.ssh("192.168.1.1", user="root", wordlist="pass.txt")
```

Use it only on hosts you own or are authorized to test.

## Install

```bash
pip install secraft
```

Python 3.10+. Works on Windows, Linux and macOS. There are no extras: HTTP, DNS,
port scanning, SSH checks and raw packets all ship in the one package.

## 30 seconds

```python
import secraft as sec

# 1. scan ports
r = sec.portscan("192.168.1.1", ports="1-1024")
print(r)
print(r.ports)        # [22, 80, 443]

# 2. grab banners
sec.banner("192.168.1.1", ports=r.ports)

# 3. send HTTP
r = sec.http.get("https://example.com")
print(r.status_code, r.text[:100])

# 4. collect subdomains
sec.subdomain("example.com")

# 5. write your own PoC (no YAML to learn)
r = sec.http.get("http://example.com/index.php?id=1'")
if "SQL syntax" in r.text:
    print("injection candidate")

# 6. wrap up
print(sec.log())            # what actually ran
sec.report("report.md")     # Markdown you can hand over
```

## Why the result is not a plain dict

Every call returns a `Result` with one of three states:

- **done** — finished, and there is a result.
- **done, empty** — finished, and there really is nothing (host is up, every
  port is closed).
- **failed** — the library side broke: no permission, no route, a missing
  dependency, a bad argument.

Those three lead to different next steps, so they must stay distinguishable.
`print(r)` tells you which one you are in, why, and what to try next.

```python
r.ok / r.found / r.empty / r.failed
r.data       # structured result
r.raw        # the underlying object: requests.Response / bytes / ...
r.ports      # open ports
22 in r      # port membership
```

## Modules

| Name | What it does |
| --- | --- |
| `sec.portscan` | TCP connect scan, pure Python, no nmap |
| `sec.ping` | Host discovery over TCP (open port or RST), no root, no ICMP |
| `sec.fingerprint` | Parse a banner into product, version and OS |
| `sec.synscan` | Native SYN half-open scan (Linux + root; falls back to connect elsewhere) |
| `sec.banner` | Grab the banner of open ports |
| `sec.http` | HTTP requests (a requests wrapper; `r.raw` is the `Response`) |
| `sec.web.session` | Persistent session: log in once, cookies and headers carry over |
| `sec.web.diff` | Compare two responses: status, size, body similarity, and what changed |
| `sec.Batch` | What a multi-target call returns: `items`, `open_ports[host]`, `counts`, `partial` |
| `sec.raw` | Send raw HTTP bytes, bypassing requests' normalisation |
| `sec.fuzz` | Replace one `FUZZ` marker with many payloads and compare each response against a control request |
| `sec.dns` | Hand-built DNS queries and zone-transfer (AXFR) detection |
| `sec.subdomain` | Subdomain brute force, with wildcard detection |
| `sec.ssh` / `sec.ftp` / `sec.smtp` / `sec.pop3` / `sec.imap` / `sec.telnet` / `sec.redis` / `sec.mysql` / `sec.postgres` / `sec.mongodb` / `sec.smb` / `sec.ldap` / `sec.mssql` / `sec.http_basic` / `sec.http_form` | Credential checks; can also be reached through `sec.brute.run("ssh", ...)`. Each accepts a list of hosts and returns a Batch |
| `sec.shell` | Use a credential: SSH sessions with `run`/`shell`, MySQL/PostgreSQL sessions with `query`/`shell` |
| `sec.crypto` | RSA public-key weakness audit (small modulus, Wiener, shared primes, ...), powered by cryptoexp |
| `sec.jwt` | Decode, forge `alg=none`, sign and crack HMAC secrets |
| `sec.csrf` | Turn a captured request into an auto-submitting HTML form |
| `sec.serve` | Throwaway HTTP server for callbacks and self-tests |
| `sec.tcp` / `sec.udp` | Raw socket send/recv for services without a client here |
| `sec.codec` / `sec.text` / `sec.wordlist` | Encoding, text extraction, wordlists |
| `sec.log` / `sec.report` | Call log and Markdown report |

## Sessions, comparison, and many targets

```python
with sec.web.session("http://192.168.1.10") as s:
    s.post("/login", data={"user": "admin", "pass": "admin"})
    base = s.get("/item?id=1")
    test = s.get("/item?id=1'")
    print(sec.web.diff(base, test).data)   # status, length, similarity, why

b = sec.portscan(["192.168.1.1", "192.168.1.2"])
print(b.open_ports)        # {'192.168.1.1': [22, 80]}
print(b.partial, b.counts) # True {'ok': 1, 'empty': 1, 'error': 0}
```

One target returns a `Result`; many targets return a `Batch`. Batch does not
pretend to be a Result: `b.open_ports[host]` answers "which ports on which
host", and `"10.0.0.1" in b` asks whether that *target* is in the batch.

## A script is also a command

```python
# tool.py
import secraft as sec

@sec.cli.command
def scan(target, ports: str = "", timeout: float = 1.0):
    """Scan a host for open ports."""
    return sec.portscan(target, ports=ports or None, timeout=timeout)

if __name__ == "__main__":
    raise SystemExit(sec.cli.run())
```

`python tool.py scan 10.0.0.5 --ports 1-1024` now works, `--help` comes from
the signature, `--json` prints the whole Result for `jq`, and the exit code
follows the three states (0 found, 1 empty, 2 failed). No plugin system, no
config file: three pieces, the decorator, `run()`, and the output.

## Credential checks: one skeleton, fifteen protocols

```python
sec.brute.supported()
# ['ftp', 'http-basic', 'http-form', 'imap', 'ldap', 'mariadb', 'mongo',
#  'mongodb', 'mssql', 'mysql', 'pop3', 'postgres', 'postgresql', 'redis',
#  'smb', 'smtp', 'ssh', 'telnet']

sec.ssh("10.0.0.5", user="root", wordlist="pass.txt")
sec.redis("10.0.0.5", wordlist="pass.txt")          # also spots "no password set"
sec.mysql("10.0.0.5", user="root", wordlist="pass.txt")
sec.brute.run("postgres", "10.0.0.5", user="postgres", passwords=["123456"])
```

The three states are the same everywhere: credentials found is done; tried
everything and found nothing is done-but-empty; no authentication ever happened
(protocol mismatch, cannot connect) is failed. A Redis with no password is
reported as unauthenticated access, never as "no password found".

Protocols: ssh, ftp, smtp (including 465/587), pop3, imap, telnet, redis,
http-basic, http-form, mysql, postgres, mongodb, smb, ldap, mssql.

Web, database and SMB checks go through established drivers (requests /
pymysql / psycopg2 / pymongo / impacket) instead of hand-written wire formats: a
protocol detail done wrong produces false negatives, and a feature that quietly
lies is worse than a missing feature.

### Concurrency

Attempts run in a thread pool. `workers` defaults to 16, the same order of
magnitude as hydra's `-t`, and every protocol accepts it:

```python
sec.ssh("10.0.0.5", user="root", wordlist="pass.txt", workers=32)
sec.ftp("10.0.0.5", user="admin", wordlist="pass.txt", workers=1)  # one at a time
```

`workers=1` is strictly sequential. Higher values are faster but can trip
account lockout policies or IDS: that trade-off is yours to make, so it is a
parameter rather than a hidden decision. `delay` (minimum seconds between
attempt starts, applied globally) and
`max_tries` (stop after N pairs) are the other two knobs.

VNC (needs the DES challenge) and RDP (NLA) are not implemented.

## PoC without YAML

nuclei's template syntax exists to serve its command line. Inside a script,
deciding whether a bug is there is normally three lines:

```python
def thinkphp_rce(url):
    # Raw string on purpose: in a normal string, \t becomes a tab character
    payload = (
        r"/index.php?s=/Index/\think\app/invokefunction"
        "&function=call_user_func_array&vars[0]=phpinfo&vars[1][]=1"
    )
    r = sec.http.get(url.rstrip("/") + payload)
    return r.ok and "PHP Version" in r.text

if thinkphp_rce("http://example.com"):
    print("it fired")
```

For malformed packets and raw messages, use `sec.raw`:

```python
def redis_unauth(host, port=6379):
    r = sec.raw.send(host, port, b"PING\r\n")
    return r.ok and "+PONG" in r.text
```

That is freer than YAML and easier to debug: a mistake is a Python traceback
with a line number. More examples in [examples/poc.py](examples/poc.py).

## Dependencies and licence

Seven dependencies, all installable on Windows (pure Python or with wheels):

| Package | Used for | Licence |
| --- | --- | --- |
| requests | HTTP | Apache-2.0 |
| paramiko | SSH | LGPL-2.1 |
| pymysql | MySQL / MariaDB | MIT |
| psycopg2-binary | PostgreSQL | LGPL (with exception) |
| pymongo | MongoDB | Apache-2.0 |
| impacket | SMB / LDAP / MSSQL | Apache 1.1 derivative |
| cryptoexp | public-key weakness audit | MIT |

- No scapy, no nmap, no pyyaml, no GPL code. The SYN scan builds IP/TCP
  itself; PoCs are Python, not YAML.
- The protocol modules import their drivers lazily, so `import secraft` does not
  pay for all of them.
- A SYN scan needs raw sockets, so it only runs on Linux as root; everywhere
  else it falls back to a connect scan and says so in the result.
- secraft itself is MIT.

## Known limitations

- **SYN scan is Linux + root only.** Raw sockets are not available to plain
  Python on Windows or macOS. On any other platform, or without root, the call
  falls back to a connect scan and `r.engine` reads `connect(fallback)`; with
  `fallback=False` you get a failure naming the reason instead.
- **One CIDR call covers at most 256 addresses.** Larger ranges are refused
  rather than half-scanned.
- **Banners are a heuristic.** Services that greet on connect are read
  passively; a silent port is then probed as HTTP, or as TLS on TLS ports. A
  service that waits for a protocol-specific request looks silent, and a banner
  is self-reported — it can be wrong or deliberately fake.
- **`http_form` judges by response differences.** Status code, body length
  (over 50 bytes) and final URL are compared against one deliberately wrong
  login, plus a list of failure phrases. A site that renders success and
  failure identically will fool it in either direction; confirm hits by hand.
- **`fuzz` reports differences, not findings.** It sends a few control requests
  (the marker set to a harmless value) to learn what "normal" looks like, then
  flags payloads whose status, size or body falls outside that envelope, and
  says which in `row["why"]`. If the controls disagree with each other (a noisy
  page, a rate limit), body comparison is switched off and `r.reason` says so.
  It does not classify a vulnerability; a real finding that changes nothing in
  status, size or body similarity is missed.
- **`http_basic` treats any 2xx without credentials as unauthenticated
  access.** That is a probe result, not a proof of what the endpoint does.
- **The DNS resolver is hand-written.** It covers A, AAAA, NS, CNAME, MX, TXT,
  SOA, SRV and PTR, plus AXFR over TCP. No DNSSEC validation, no DoH/DoT.
- **`subdomain` is a DNS wordlist run.** Wildcard filtering compares one random
  probe, so a wildcard that rotates addresses still produces noise. CNAME-only
  names and names missing from the wordlist are not found.
- **Some protocol-specific gaps:** Redis AUTH uses the password only (a Redis 6
  ACL user needs `AUTH user pass`); MySQL 8 `caching_sha2_password` is reported
  as a failure, not a wrong password; the LDAP check is port 389 only; SMB,
  MSSQL and LDAP checks do not do Kerberos or integrated authentication.
- **There is no pivoting.** No SOCKS proxy, no tunnelling, no lateral movement,
  no session handling. One call is one target.
- **The log is in memory and keeps the last 2000 calls.** `sec.report()` covers
  this process only; calls your own code makes with requests or socket are not
  in it.
- **It is not a substitute for nmap, nuclei or hydra.** Service/version
  detection, CVE templates, very large wordlists and protocol breadth are their
  job, not this library's.

## Roadmap

- VNC (DES challenge) and RDP (NLA) credential checks — the two protocols left
  out so far.
- Structured export beyond Markdown: `Result.to_dict()` exists, a JSON report
  writer does not.
- DNSSEC awareness and more record types in `sec.dns`.
- Pivoting and tunnelling are out of scope for a glue layer; they need a
  different design, not another function.

## Status

v0.1.0.

## Licence

MIT © guaidao2
