apex-twin 1.7.0: MySQL, PostgreSQL, MongoDB and Memcached probes
New tools_db.c module: - mysql_probe reads the initial handshake (protocol/server version, thread id, auth plugin, capability flags for TLS, secure connection and plugin auth). No credentials are sent. - postgres_probe asks with a separate SSLRequest whether SSL is offered, then sends one StartupMessage as user postgres and reports trust, cleartext, md5, SCRAM (with mechanism) or rejected (with the server message). A trust answer is audited; no password is sent. - mongo_probe sends a legacy OP_QUERY isMaster to admin.$cmd with a hand-built BSON document and parses the OP_REPLY for ok, maxWireVersion, writable primary and a version string. - memcached_probe sends one stats command and reports open access, version, connections, items, memory limit and uptime. Socket helpers apex_net_write/line/exact are exported from tools_proto.c. Tests with local fixtures: MySQL handshake with caching_sha2_password, PostgreSQL trust, md5, SCRAM and pg_hba rejection including an SSL-refused server, a MongoDB OP_REPLY, and memcached stats plus an ERROR answer. 537 checks, ASan suite green, analyze clean, release-check green including distcheck 1.7.0.
This commit is contained in:
1 parent
539b552c3d
commit
276283d535
11 files changed
+1120
-15
No files matched your search
+22
-1
@@ -8,7 +8,28 @@ fields, and state from an older version is read by a newer one.
|
||||
There are no git tags. The hash next to a version is the commit that introduced
|
||||
it; the current entry is the commit that adds this section.
|
||||
|
||||
## 1.6.0 — 2026-11-21 — this change
|
||||
## 1.7.0 — 2026-11-21 — this change
|
||||
|
||||
- **MySQL** (`mysql_probe`, new `tools_db.c`): parses the initial handshake —
|
||||
protocol version, server version, thread id, auth plugin and the capability
|
||||
flags (TLS, secure connection, plugin auth). No credentials are sent.
|
||||
- **PostgreSQL** (`postgres_probe`): a separate SSLRequest learns whether SSL
|
||||
is offered (S/N/refused), then one StartupMessage as user `postgres` reports
|
||||
trust, cleartext, md5, SCRAM (with mechanism) or rejected (with the server's
|
||||
message). A trust answer is audited; no password is sent.
|
||||
- **MongoDB** (`mongo_probe`): legacy OP_QUERY `isMaster` on `admin.$cmd` with a
|
||||
hand-built BSON document; the OP_REPLY is parsed for ok, maxWireVersion,
|
||||
writable primary and a version string.
|
||||
- **Memcached** (`memcached_probe`): one `stats` command; reports open access,
|
||||
version, current connections/items, memory limit and uptime.
|
||||
- Socket I/O helpers `apex_net_write/line/exact` exported from `tools_proto.c`
|
||||
so `tools_db.c` does not duplicate them.
|
||||
- Tests with local fixtures: a MySQL handshake, PostgreSQL servers for trust,
|
||||
md5, SCRAM and a pg_hba rejection plus SSL-refused, a MongoDB OP_REPLY and a
|
||||
memcached stats server (and one that answers ERROR). 537 checks. Coverage
|
||||
79.6%.
|
||||
|
||||
## 1.6.0 — 2026-11-21 — 539b552
|
||||
|
||||
- **TLS** (`tls_audit`): four `openssl s_client` runs (TLS 1.0, 1.1, 1.2,
|
||||
1.3) plus one `-showcerts` run. Reports which versions negotiate, the cipher
|
||||
|
||||
@@ -5,11 +5,11 @@ no Python in the serving path. It gives an agent real reconnaissance and real we
|
||||
testing behind a scope gate that refuses everything until a rules-of-engagement
|
||||
file says otherwise.
|
||||
|
||||
**73 tools · 522 end-to-end checks · 340 fuzz cases · 79.9% line coverage · ~362 KiB**
|
||||
**77 tools · 537 end-to-end checks · 340 fuzz cases · 79.6% line coverage · ~375 KiB**
|
||||
|
||||
```
|
||||
$ ./apex-twin --check
|
||||
{"version":"1.6.0","tools":73,...,"scope":{"loaded":true,...}}
|
||||
{"version":"1.7.0","tools":77,...,"scope":{"loaded":true,...}}
|
||||
```
|
||||
|
||||
APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope
|
||||
@@ -149,7 +149,7 @@ closes a request whose head or body does not arrive within
|
||||
|
||||
---
|
||||
|
||||
## Tools (73)
|
||||
## Tools (77)
|
||||
|
||||
### Scope and bookkeeping
|
||||
|
||||
@@ -261,6 +261,10 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
|
||||
| `redis_probe` | PING/INFO/DBSIZE on one connection; reports open access, version, role, clients, dbsize |
|
||||
| `snmp_probe` | Hand-built SNMPv1/v2c GET sysDescr.0 over UDP for up to four communities; raw answer as evidence |
|
||||
| `dns_zone_transfer` | `dig AXFR` against one in-scope server and zone; record counts per type, raw records, evidence |
|
||||
| `mysql_probe` | Initial handshake: server version, thread id, auth plugin, capability flags (TLS, plugin auth) |
|
||||
| `postgres_probe` | SSL offer plus one StartupMessage; reports trust/cleartext/md5/SCRAM/rejected and the server message |
|
||||
| `mongo_probe` | Hand-built OP_QUERY `isMaster` on `admin.$cmd`: ok, maxWireVersion, writable primary |
|
||||
| `memcached_probe` | One `stats`: open access, version, connections, items, memory limit, uptime |
|
||||
|
||||
### Blue team
|
||||
|
||||
@@ -463,6 +467,7 @@ The full threat model, trust boundaries and a hardening checklist are in
|
||||
| TLS audit | 4 protocol probes + 2 certificate runs per call |
|
||||
| SNMP | 4 communities, 2 attempts each, 1.8 s wait |
|
||||
| Zone transfer | one server, one in-scope zone, 30 s |
|
||||
| Database probes | one or two connections each; no password attempts |
|
||||
|
||||
---
|
||||
|
||||
@@ -473,7 +478,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
|
||||
|
||||
```sh
|
||||
make # apex-twin
|
||||
make test # version check + gate audit + 522 end-to-end checks
|
||||
make test # version check + gate audit + 537 end-to-end checks
|
||||
make version-check # the five places that carry a version must agree
|
||||
make gate-audit # static: every target-taking tool calls the gate
|
||||
make asan # apex-twin-asan with ASan + UBSan
|
||||
@@ -580,6 +585,8 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan
|
||||
src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash
|
||||
src/tools_proto.c ftp_probe, smtp_probe, ssh_audit, tls_audit,
|
||||
redis_probe, snmp_probe, dns_zone_transfer
|
||||
src/tools_db.c mysql_probe, postgres_probe, mongo_probe,
|
||||
memcached_probe
|
||||
src/sha256.c SHA-256/HMAC for integrity_baseline and jwt_audit
|
||||
src/tools_guard.c guard_check
|
||||
src/apex-twin.c MCP stdio + HTTP face, --check, --version
|
||||
@@ -609,7 +616,7 @@ examples/ scope.json
|
||||
|
||||
## Status
|
||||
|
||||
1.6.0. Built and run: 73 tools, 522 checks, 340 fuzz cases and 79.9% line
|
||||
1.7.0. Built and run: 77 tools, 537 checks, 340 fuzz cases and 79.6% line
|
||||
coverage. The loop closes: a probe captures the exchange as a pair, a finding
|
||||
points at it, `finding_update` gives it a state, an asset records the host it
|
||||
came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a
|
||||
@@ -633,8 +640,9 @@ wordlist path brute-forcing and access-log analysis; 1.3 added SSRF
|
||||
verification, detection-rule export, integrity baselines and firmware writing
|
||||
(confirm-gated); 1.4 added offline JWT/hash analysis, ATT&CK mapping and a
|
||||
/proc snapshot; 1.5 added FTP/SMTP/SSH service probes and a persistence audit;
|
||||
1.6 added TLS, Redis, SNMP and DNS zone-transfer checks, again without changing
|
||||
an existing tool or file format.
|
||||
1.6 added TLS, Redis, SNMP and DNS zone-transfer checks; 1.7 added MySQL,
|
||||
PostgreSQL, MongoDB and Memcached probes, again without changing an existing
|
||||
tool or file format.
|
||||
|
||||
Not yet wired into a fleet router, and there is no TLS interception.
|
||||
|
||||
|
||||
+6
-1
@@ -9,7 +9,7 @@ problem.
|
||||
|
||||
The supported line is the one printed by `apex-twin --version` for the tree you
|
||||
built; this document ships with that same tree. At the time of writing the line
|
||||
is **1.6.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
|
||||
is **1.7.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
|
||||
line. The 1.0 line promises that the on-disk JSON formats for findings, assets
|
||||
and traffic only gain fields, so state stays readable; older builds are still
|
||||
rebuilt rather than patched in place.
|
||||
@@ -66,6 +66,11 @@ only narrow what the proxy does (the scope gate still runs first).
|
||||
- **Firmware writing needs an explicit confirmation.** `esp_flash` refuses
|
||||
without `confirm=true`, validates an absolute image path and audits the
|
||||
attempt; it exists to provision the operator's own board.
|
||||
- **Database probes read one greeting, never a password.** `mysql_probe`
|
||||
reads the initial handshake, `postgres_probe` sends one StartupMessage with
|
||||
no password and reports the auth method, `mongo_probe` sends `isMaster` and
|
||||
`memcached_probe` sends `stats`. None of them writes, guesses or replays a
|
||||
credential; a trust/SCRAM offer is reported, not logged into.
|
||||
- **TLS, Redis, SNMP and AXFR stay read-only.** `tls_audit` performs TLS
|
||||
handshakes and reads the certificate; `redis_probe` sends PING, INFO and
|
||||
DBSIZE only; `snmp_probe` sends a GET for sysDescr.0; `dns_zone_transfer`
|
||||
|
||||
+3
-2
@@ -1,5 +1,5 @@
|
||||
.\" apex-twin.1 - manual page for APEX TWIN
|
||||
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.6.0" "User Commands"
|
||||
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.7.0" "User Commands"
|
||||
.SH NAME
|
||||
apex-twin \- scope\-gated offensive\-security MCP server
|
||||
.SH SYNOPSIS
|
||||
@@ -38,7 +38,8 @@ post\-exploitation, no C2 and no persistence. Besides reconnaissance and web
|
||||
testing it carries offensive verification (vuln_check, subdomain_enum,
|
||||
cred_test, vhost_discovery, http_brute, ssrf_probe, jwt_audit, hash_id,
|
||||
ftp_probe, smtp_probe, ssh_audit, tls_audit, redis_probe, snmp_probe,
|
||||
dns_zone_transfer), defensive audits (hardening_audit, log_audit, ioc_scan,
|
||||
dns_zone_transfer, mysql_probe, postgres_probe, mongo_probe,
|
||||
memcached_probe), defensive audits (hardening_audit, log_audit, ioc_scan,
|
||||
web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot,
|
||||
persistence_audit) and ESP32 board tools (esp_info, esp_monitor,
|
||||
esp_read_flash, esp_flash).
|
||||
|
||||
@@ -126,6 +126,8 @@ static void build_tools(void)
|
||||
g_tools[n++] = TOOLS_ESP[i];
|
||||
for (i = 0; i < TOOLS_PROTO_N && n < 96; i++)
|
||||
g_tools[n++] = TOOLS_PROTO[i];
|
||||
for (i = 0; i < TOOLS_DB_N && n < 96; i++)
|
||||
g_tools[n++] = TOOLS_DB[i];
|
||||
|
||||
g_srv.name = "apex-twin";
|
||||
g_srv.version = APEX_VERSION;
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
|
||||
#include "mcp.h"
|
||||
|
||||
#define APEX_VERSION "1.6.0"
|
||||
#define APEX_VERSION "1.7.0"
|
||||
#define APEX_MAX_OUT (1u << 20)
|
||||
#define APEX_PATH_MAX 512
|
||||
#define APEX_PATH_FULL 1024
|
||||
|
||||
@@ -36,6 +36,11 @@ int apex_serial_open(const char *path, int baud);
|
||||
/* malloc'd base64 of len bytes, NUL-terminated. */
|
||||
char *apex_base64_alloc(const char *data, size_t len);
|
||||
|
||||
/* Buffered-free socket I/O shared by the protocol and database probes. */
|
||||
int apex_net_write(int fd, const char *s);
|
||||
int apex_net_line(int fd, char *buf, size_t n);
|
||||
int apex_net_exact(int fd, unsigned char *buf, size_t n);
|
||||
|
||||
extern const mcp_tool TOOLS_RECON[];
|
||||
extern const size_t TOOLS_RECON_N;
|
||||
extern const mcp_tool TOOLS_WEB[];
|
||||
@@ -60,5 +65,7 @@ extern const mcp_tool TOOLS_ESP[];
|
||||
extern const size_t TOOLS_ESP_N;
|
||||
extern const mcp_tool TOOLS_PROTO[];
|
||||
extern const size_t TOOLS_PROTO_N;
|
||||
extern const mcp_tool TOOLS_DB[];
|
||||
extern const size_t TOOLS_DB_N;
|
||||
|
||||
#endif /* APEX_TOOLS_H */
|
||||
+862
@@ -0,0 +1,862 @@
|
||||
/*
|
||||
* tools_db.c - the database half of the reconnaissance.
|
||||
*
|
||||
* mysql_probe read the initial handshake: version, thread id, auth
|
||||
* plugin, capability flags. No credentials are sent.
|
||||
* postgres_probe learn whether SSL is offered, then send one StartupMessage
|
||||
* as user "postgres" and report the authentication method
|
||||
* (trust, cleartext, md5, SCRAM). No password is sent.
|
||||
* mongo_probe legacy OP_QUERY isMaster on admin.$cmd; BSON built by hand.
|
||||
* memcached_probe one "stats" command; reports an open instance and the
|
||||
* fields that matter (version, connections, items, memory).
|
||||
*
|
||||
* Each tool opens one or two connections to an in-scope host, reads the
|
||||
* protocol greeting and never attempts a login with a password.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <netdb.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <sys/socket.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "apex.h"
|
||||
#include "tools.h"
|
||||
|
||||
/* ---------------------------------------------------------------- utilities */
|
||||
|
||||
static uint32_t le32(const unsigned char *p)
|
||||
{
|
||||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
|
||||
static uint32_t be32(const unsigned char *p)
|
||||
{
|
||||
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) |
|
||||
((uint32_t)p[2] << 8) | (uint32_t)p[3];
|
||||
}
|
||||
|
||||
static void put_le32(unsigned char *p, uint32_t v)
|
||||
{
|
||||
p[0] = (unsigned char)v;
|
||||
p[1] = (unsigned char)(v >> 8);
|
||||
p[2] = (unsigned char)(v >> 16);
|
||||
p[3] = (unsigned char)(v >> 24);
|
||||
}
|
||||
|
||||
static void put_be32(unsigned char *p, uint32_t v)
|
||||
{
|
||||
p[0] = (unsigned char)(v >> 24);
|
||||
p[1] = (unsigned char)(v >> 16);
|
||||
p[2] = (unsigned char)(v >> 8);
|
||||
p[3] = (unsigned char)v;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- mysql_probe */
|
||||
|
||||
static void t_mysql_probe(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
int port = mcp_arg_int(args, "port", 3306);
|
||||
int fd;
|
||||
unsigned char hdr[4];
|
||||
unsigned char *payload = NULL;
|
||||
uint32_t len;
|
||||
uint32_t caps = 0;
|
||||
uint32_t thread_id = 0;
|
||||
char server_version[128];
|
||||
char plugin[64];
|
||||
char caps_text[32];
|
||||
int tls = 0;
|
||||
int secure = 0;
|
||||
int plugin_auth = 0;
|
||||
mcp_buf b;
|
||||
size_t off;
|
||||
size_t vlen;
|
||||
|
||||
(void)user;
|
||||
if (target == NULL || *target == '\0') {
|
||||
mcp_reply_error(c, "target is required");
|
||||
return;
|
||||
}
|
||||
if (port <= 0 || port > 65535) {
|
||||
mcp_reply_error(c, "port out of range");
|
||||
return;
|
||||
}
|
||||
if (!gated(c, "mysql_probe", target, port))
|
||||
return;
|
||||
fd = tcp_connect_host(target, port, 6000);
|
||||
if (fd < 0) {
|
||||
mcp_reply_error(c, "cannot connect to the MySQL service");
|
||||
return;
|
||||
}
|
||||
if (apex_net_exact(fd, hdr, 4) != 0) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "no MySQL handshake");
|
||||
return;
|
||||
}
|
||||
len = (uint32_t)hdr[0] | ((uint32_t)hdr[1] << 8) |
|
||||
((uint32_t)hdr[2] << 16);
|
||||
if (len < 5 || len > 65535) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "MySQL handshake length out of range");
|
||||
return;
|
||||
}
|
||||
payload = malloc(len);
|
||||
if (payload == NULL) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "out of memory");
|
||||
return;
|
||||
}
|
||||
if (apex_net_exact(fd, payload, len) != 0) {
|
||||
free(payload);
|
||||
close(fd);
|
||||
mcp_reply_error(c, "short MySQL handshake");
|
||||
return;
|
||||
}
|
||||
close(fd);
|
||||
if (payload[0] != 10) {
|
||||
char detail[96];
|
||||
|
||||
snprintf(detail, sizeof(detail),
|
||||
"unexpected MySQL protocol version %u", payload[0]);
|
||||
free(payload);
|
||||
mcp_reply_error(c, detail);
|
||||
return;
|
||||
}
|
||||
off = 1;
|
||||
server_version[0] = '\0';
|
||||
if (off < len) {
|
||||
vlen = strnlen((const char *)(payload + off), len - off);
|
||||
snprintf(server_version, sizeof(server_version), "%.100s",
|
||||
(const char *)(payload + off));
|
||||
off += vlen + 1;
|
||||
}
|
||||
if (off + 4 <= len) {
|
||||
thread_id = le32(payload + off);
|
||||
off += 4;
|
||||
}
|
||||
off += 8; /* auth-plugin-data-part-1 */
|
||||
if (off < len)
|
||||
off += 1; /* filler */
|
||||
if (off + 2 <= len) {
|
||||
caps = (uint32_t)payload[off] | ((uint32_t)payload[off + 1] << 8);
|
||||
off += 2;
|
||||
}
|
||||
off += 1; /* character set */
|
||||
off += 2; /* status flags */
|
||||
if (off + 2 <= len) {
|
||||
caps |= ((uint32_t)payload[off] |
|
||||
((uint32_t)payload[off + 1] << 8)) << 16;
|
||||
off += 2;
|
||||
}
|
||||
tls = (caps & 0x00000800u) != 0; /* CLIENT_SSL */
|
||||
secure = (caps & 0x00008000u) != 0; /* CLIENT_SECURE_CONNECTION */
|
||||
plugin_auth = (caps & 0x00080000u) != 0; /* CLIENT_PLUGIN_AUTH */
|
||||
/* auth-plugin-data-part-2 is max(13, auth_len - 8) bytes, then the name */
|
||||
plugin[0] = '\0';
|
||||
if (plugin_auth && off < len) {
|
||||
unsigned int alen = payload[off++];
|
||||
size_t s2;
|
||||
|
||||
off += 10; /* reserved */
|
||||
s2 = alen > 8 ? (size_t)(alen - 8) : 13;
|
||||
if (s2 < 13)
|
||||
s2 = 13;
|
||||
if (off + s2 <= len)
|
||||
off += s2;
|
||||
if (off < len) {
|
||||
size_t k = 0;
|
||||
|
||||
while (off < len && payload[off] != 0 &&
|
||||
k + 1 < sizeof(plugin))
|
||||
plugin[k++] = (char)payload[off++];
|
||||
plugin[k] = '\0';
|
||||
}
|
||||
}
|
||||
{
|
||||
int printable = plugin[0] != '\0';
|
||||
size_t k;
|
||||
|
||||
for (k = 0; plugin[k] != '\0'; k++) {
|
||||
unsigned char ch = (unsigned char)plugin[k];
|
||||
|
||||
if (!((ch >= 'a' && ch <= 'z') ||
|
||||
(ch >= 'A' && ch <= 'Z') ||
|
||||
(ch >= '0' && ch <= '9') || ch == '_' || ch == '-'))
|
||||
printable = 0;
|
||||
}
|
||||
if (!printable) {
|
||||
/* fallback: last NUL-delimited printable token in the packet */
|
||||
size_t e = len;
|
||||
size_t st;
|
||||
|
||||
while (e > 0 && payload[e - 1] == 0)
|
||||
e--;
|
||||
st = e;
|
||||
while (st > 0 && payload[st - 1] != 0)
|
||||
st--;
|
||||
if (e > st && e - st < sizeof(plugin)) {
|
||||
int ok = 1;
|
||||
|
||||
for (k = st; k < e; k++) {
|
||||
unsigned char ch = payload[k];
|
||||
|
||||
if (!((ch >= 'a' && ch <= 'z') ||
|
||||
(ch >= 'A' && ch <= 'Z') ||
|
||||
(ch >= '0' && ch <= '9') ||
|
||||
ch == '_' || ch == '-'))
|
||||
ok = 0;
|
||||
}
|
||||
if (ok)
|
||||
snprintf(plugin, sizeof(plugin), "%.*s",
|
||||
(int)(e - st), payload + st);
|
||||
}
|
||||
}
|
||||
}
|
||||
free(payload);
|
||||
snprintf(caps_text, sizeof(caps_text), "0x%08x", caps);
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"target\":");
|
||||
apex_json_str(&b, target);
|
||||
mcp_buf_printf(&b, ",\"port\":%d,\"mysql\":true,\"server_version\":", port);
|
||||
apex_json_str(&b, server_version);
|
||||
mcp_buf_printf(&b, ",\"thread_id\":%lu,\"auth_plugin\":", (unsigned long)thread_id);
|
||||
apex_json_str(&b, plugin);
|
||||
mcp_buf_printf(&b, ",\"capabilities\":\"%s\",\"tls\":%s,"
|
||||
"\"secure_connection\":%s,\"plugin_auth\":%s}",
|
||||
caps_text, tls ? "true" : "false",
|
||||
secure ? "true" : "false",
|
||||
plugin_auth ? "true" : "false");
|
||||
apex_audit("mysql_probe", target, port, 1, "handshake read",
|
||||
server_version);
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- postgres_probe */
|
||||
|
||||
static void pg_put32(unsigned char *p, uint32_t v)
|
||||
{
|
||||
put_be32(p, v);
|
||||
}
|
||||
|
||||
static int pg_ssl_supported(const char *target, int port, char *out, size_t n)
|
||||
{
|
||||
int fd = tcp_connect_host(target, port, 6000);
|
||||
unsigned char req[8];
|
||||
unsigned char reply;
|
||||
ssize_t r;
|
||||
|
||||
out[0] = '\0';
|
||||
if (fd < 0)
|
||||
return -1;
|
||||
pg_put32(req, 8);
|
||||
pg_put32(req + 4, 80877103); /* SSLRequest */
|
||||
if (write(fd, req, sizeof(req)) != (ssize_t)sizeof(req)) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
r = read(fd, &reply, 1);
|
||||
close(fd);
|
||||
if (r != 1)
|
||||
return -1;
|
||||
if (reply == 'S')
|
||||
snprintf(out, n, "supported");
|
||||
else if (reply == 'N')
|
||||
snprintf(out, n, "not-supported");
|
||||
else
|
||||
snprintf(out, n, "refused");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void pg_read_error(const unsigned char *body, size_t len, char *out,
|
||||
size_t n)
|
||||
{
|
||||
size_t off = 0;
|
||||
|
||||
out[0] = '\0';
|
||||
while (off < len && body[off] != 0) {
|
||||
unsigned char field = body[off++];
|
||||
size_t flen = strnlen((const char *)(body + off), len - off);
|
||||
|
||||
if (field == 'M')
|
||||
snprintf(out, n, "%.160s", (const char *)(body + off));
|
||||
off += flen + 1;
|
||||
}
|
||||
}
|
||||
|
||||
static void t_postgres_probe(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
const char *user_name = mcp_arg_string(args, "user");
|
||||
int port = mcp_arg_int(args, "port", 5432);
|
||||
char ssl[32];
|
||||
char auth[48];
|
||||
char detail[192];
|
||||
char mechanism[64];
|
||||
int auth_code = -1;
|
||||
int fd;
|
||||
mcp_buf b;
|
||||
|
||||
(void)user;
|
||||
if (target == NULL || *target == '\0') {
|
||||
mcp_reply_error(c, "target is required");
|
||||
return;
|
||||
}
|
||||
if (port <= 0 || port > 65535) {
|
||||
mcp_reply_error(c, "port out of range");
|
||||
return;
|
||||
}
|
||||
if (user_name == NULL || *user_name == '\0')
|
||||
user_name = "postgres";
|
||||
if (strlen(user_name) > 63) {
|
||||
mcp_reply_error(c, "user name too long");
|
||||
return;
|
||||
}
|
||||
if (!gated(c, "postgres_probe", target, port))
|
||||
return;
|
||||
snprintf(ssl, sizeof(ssl), "unknown");
|
||||
if (pg_ssl_supported(target, port, ssl, sizeof(ssl)) != 0)
|
||||
snprintf(ssl, sizeof(ssl), "unknown");
|
||||
|
||||
auth[0] = '\0';
|
||||
detail[0] = '\0';
|
||||
mechanism[0] = '\0';
|
||||
fd = tcp_connect_host(target, port, 6000);
|
||||
if (fd < 0) {
|
||||
mcp_reply_error(c, "cannot connect to the PostgreSQL service");
|
||||
return;
|
||||
}
|
||||
{
|
||||
size_t ulen = strlen(user_name);
|
||||
size_t len = 4 + 4 + 5 + ulen + 1 + 9 + ulen + 1 + 1;
|
||||
unsigned char *msg = malloc(len + 8);
|
||||
unsigned char *p;
|
||||
|
||||
if (msg == NULL) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "out of memory");
|
||||
return;
|
||||
}
|
||||
p = msg;
|
||||
put_be32(p, (uint32_t)len);
|
||||
p += 4;
|
||||
put_be32(p, 196608); /* protocol 3.0 */
|
||||
p += 4;
|
||||
memcpy(p, "user", 5);
|
||||
p += 5;
|
||||
memcpy(p, user_name, ulen);
|
||||
p += ulen;
|
||||
*p++ = '\0';
|
||||
memcpy(p, "database", 9);
|
||||
p += 9;
|
||||
memcpy(p, user_name, ulen);
|
||||
p += ulen;
|
||||
*p++ = '\0';
|
||||
*p++ = '\0';
|
||||
if (write(fd, msg, (size_t)(p - msg)) != (ssize_t)(p - msg)) {
|
||||
free(msg);
|
||||
close(fd);
|
||||
mcp_reply_error(c, "cannot send the startup message");
|
||||
return;
|
||||
}
|
||||
free(msg);
|
||||
}
|
||||
{
|
||||
int rounds;
|
||||
|
||||
for (rounds = 0; rounds < 8; rounds++) {
|
||||
unsigned char head[5];
|
||||
uint32_t mlen;
|
||||
|
||||
if (apex_net_exact(fd, head, 5) != 0)
|
||||
break;
|
||||
mlen = be32(head + 1);
|
||||
if (mlen < 4 || mlen > 65536)
|
||||
break;
|
||||
{
|
||||
unsigned char *body = malloc(mlen - 4);
|
||||
|
||||
if (body == NULL)
|
||||
break;
|
||||
if (apex_net_exact(fd, body, mlen - 4) != 0) {
|
||||
free(body);
|
||||
break;
|
||||
}
|
||||
if (head[0] == 'R' && mlen - 4 >= 4) {
|
||||
size_t off = 4;
|
||||
|
||||
auth_code = (int)be32(body);
|
||||
if (auth_code == 0)
|
||||
snprintf(auth, sizeof(auth), "trust");
|
||||
else if (auth_code == 3)
|
||||
snprintf(auth, sizeof(auth), "cleartext");
|
||||
else if (auth_code == 5)
|
||||
snprintf(auth, sizeof(auth), "md5");
|
||||
else if (auth_code == 10)
|
||||
snprintf(auth, sizeof(auth), "scram");
|
||||
else
|
||||
snprintf(auth, sizeof(auth), "other");
|
||||
if (auth_code == 10) {
|
||||
while (off < mlen - 4 && body[off] != 0) {
|
||||
size_t sl = strnlen(
|
||||
(const char *)(body + off),
|
||||
mlen - 4 - off);
|
||||
|
||||
if (mechanism[0] == '\0')
|
||||
snprintf(mechanism,
|
||||
sizeof(mechanism),
|
||||
"%.40s",
|
||||
(const char *)(body + off));
|
||||
off += sl + 1;
|
||||
}
|
||||
}
|
||||
free(body);
|
||||
break;
|
||||
}
|
||||
if (head[0] == 'E') {
|
||||
pg_read_error(body, mlen - 4, detail,
|
||||
sizeof(detail));
|
||||
snprintf(auth, sizeof(auth), "rejected");
|
||||
free(body);
|
||||
break;
|
||||
}
|
||||
free(body);
|
||||
}
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
if (auth[0] == '\0')
|
||||
snprintf(auth, sizeof(auth), "no-response");
|
||||
apex_audit("postgres_probe", target, port,
|
||||
strcmp(auth, "trust") != 0,
|
||||
strcmp(auth, "trust") == 0 ? "trust authentication accepted"
|
||||
: "password required or rejected",
|
||||
auth);
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"target\":");
|
||||
apex_json_str(&b, target);
|
||||
mcp_buf_printf(&b, ",\"port\":%d,\"postgres\":true,\"ssl\":", port);
|
||||
apex_json_str(&b, ssl);
|
||||
mcp_buf_puts(&b, ",\"auth\":");
|
||||
apex_json_str(&b, auth);
|
||||
mcp_buf_printf(&b, ",\"auth_code\":%d,\"mechanism\":", auth_code);
|
||||
apex_json_str(&b, mechanism);
|
||||
mcp_buf_puts(&b, ",\"detail\":");
|
||||
apex_json_str(&b, detail);
|
||||
mcp_buf_puts(&b, "}");
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- mongo_probe */
|
||||
|
||||
typedef struct {
|
||||
const unsigned char *val;
|
||||
size_t len;
|
||||
unsigned char type;
|
||||
} bson_value;
|
||||
|
||||
static int bson_get(const unsigned char *doc, size_t dlen, const char *key,
|
||||
bson_value *out)
|
||||
{
|
||||
size_t off = 4;
|
||||
|
||||
if (dlen < 5)
|
||||
return 0;
|
||||
while (off < dlen && doc[off] != 0) {
|
||||
unsigned char type = doc[off++];
|
||||
size_t klen;
|
||||
size_t vlen = 0;
|
||||
|
||||
klen = strnlen((const char *)(doc + off), dlen - off);
|
||||
if (off + klen + 1 > dlen)
|
||||
return 0;
|
||||
{
|
||||
const char *k = (const char *)(doc + off);
|
||||
|
||||
off += klen + 1;
|
||||
switch (type) {
|
||||
case 0x01:
|
||||
vlen = 8;
|
||||
break;
|
||||
case 0x02:
|
||||
if (off + 4 > dlen)
|
||||
return 0;
|
||||
vlen = 4 + le32(doc + off);
|
||||
break;
|
||||
case 0x03:
|
||||
case 0x04:
|
||||
if (off + 4 > dlen)
|
||||
return 0;
|
||||
vlen = le32(doc + off);
|
||||
break;
|
||||
case 0x05:
|
||||
if (off + 5 > dlen)
|
||||
return 0;
|
||||
vlen = 5 + le32(doc + off);
|
||||
break;
|
||||
case 0x07:
|
||||
vlen = 12;
|
||||
break;
|
||||
case 0x08:
|
||||
vlen = 1;
|
||||
break;
|
||||
case 0x09:
|
||||
vlen = 8;
|
||||
break;
|
||||
case 0x0a:
|
||||
vlen = 0;
|
||||
break;
|
||||
case 0x10:
|
||||
vlen = 4;
|
||||
break;
|
||||
case 0x11:
|
||||
case 0x12:
|
||||
vlen = 8;
|
||||
break;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
if (off + vlen > dlen)
|
||||
return 0;
|
||||
if (strcmp(k, key) == 0) {
|
||||
out->val = doc + off;
|
||||
out->len = vlen;
|
||||
out->type = type;
|
||||
return 1;
|
||||
}
|
||||
off += vlen;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static double bson_number(const bson_value *v, int *is_set)
|
||||
{
|
||||
*is_set = 1;
|
||||
if (v->type == 0x01) {
|
||||
double d;
|
||||
uint64_t bits = (uint64_t)le32(v->val) |
|
||||
((uint64_t)le32(v->val + 4) << 32);
|
||||
|
||||
memcpy(&d, &bits, sizeof(d));
|
||||
return d;
|
||||
}
|
||||
if (v->type == 0x10) {
|
||||
int32_t i = (int32_t)le32(v->val);
|
||||
|
||||
return (double)i;
|
||||
}
|
||||
*is_set = 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void bson_string(const bson_value *v, char *out, size_t n)
|
||||
{
|
||||
uint32_t len;
|
||||
|
||||
out[0] = '\0';
|
||||
if (v->type != 0x02 || v->len < 5)
|
||||
return;
|
||||
len = le32(v->val);
|
||||
if (len == 0 || len > v->len - 4)
|
||||
return;
|
||||
snprintf(out, n, "%.*s", (int)(len - 1), (const char *)(v->val + 4));
|
||||
}
|
||||
|
||||
static void bson_bool(const bson_value *v, int *out)
|
||||
{
|
||||
if (v->type == 0x08 && v->len >= 1)
|
||||
*out = v->val[0] != 0;
|
||||
}
|
||||
|
||||
static void t_mongo_probe(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
int port = mcp_arg_int(args, "port", 27017);
|
||||
unsigned char msg[256];
|
||||
unsigned char hdr[4];
|
||||
unsigned char *resp = NULL;
|
||||
uint32_t mlen;
|
||||
size_t ns_len;
|
||||
size_t doc_off;
|
||||
size_t doc_len;
|
||||
unsigned char ismaster_doc[32];
|
||||
size_t ismaster_len;
|
||||
mcp_buf b;
|
||||
int fd;
|
||||
int ok_set = 0;
|
||||
int bool_set = 0;
|
||||
int writable = 0;
|
||||
double ok = 0;
|
||||
long max_wire = -1;
|
||||
char version[64];
|
||||
bson_value v;
|
||||
|
||||
(void)user;
|
||||
if (target == NULL || *target == '\0') {
|
||||
mcp_reply_error(c, "target is required");
|
||||
return;
|
||||
}
|
||||
if (port <= 0 || port > 65535) {
|
||||
mcp_reply_error(c, "port out of range");
|
||||
return;
|
||||
}
|
||||
if (!gated(c, "mongo_probe", target, port))
|
||||
return;
|
||||
/* {"isMaster": 1} */
|
||||
put_le32(ismaster_doc, 19);
|
||||
ismaster_doc[4] = 0x10;
|
||||
memcpy(ismaster_doc + 5, "isMaster", 9);
|
||||
put_le32(ismaster_doc + 14, 1);
|
||||
ismaster_doc[18] = 0x00;
|
||||
ismaster_len = 19;
|
||||
ns_len = strlen("admin.$cmd") + 1;
|
||||
mlen = (uint32_t)(16 + ns_len + 4 + 4 + ismaster_len);
|
||||
put_le32(msg, mlen);
|
||||
put_le32(msg + 4, 1); /* requestID */
|
||||
put_le32(msg + 8, 0); /* responseTo */
|
||||
put_le32(msg + 12, 2004); /* OP_QUERY */
|
||||
put_le32(msg + 16, 0); /* flags */
|
||||
memcpy(msg + 20, "admin.$cmd", ns_len);
|
||||
put_le32(msg + 20 + ns_len, 0); /* numberToSkip */
|
||||
put_le32(msg + 24 + ns_len, 0xffffffffu); /* numberToReturn -1 */
|
||||
memcpy(msg + 28 + ns_len, ismaster_doc, ismaster_len);
|
||||
fd = tcp_connect_host(target, port, 6000);
|
||||
if (fd < 0) {
|
||||
mcp_reply_error(c, "cannot connect to the MongoDB service");
|
||||
return;
|
||||
}
|
||||
if (write(fd, msg, mlen) != (ssize_t)mlen) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "cannot send the OP_QUERY");
|
||||
return;
|
||||
}
|
||||
if (apex_net_exact(fd, hdr, 4) != 0) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "no MongoDB reply");
|
||||
return;
|
||||
}
|
||||
mlen = le32(hdr);
|
||||
if (mlen < 36 || mlen > (1u << 20)) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "MongoDB reply length out of range");
|
||||
return;
|
||||
}
|
||||
resp = malloc(mlen);
|
||||
if (resp == NULL) {
|
||||
close(fd);
|
||||
mcp_reply_error(c, "out of memory");
|
||||
return;
|
||||
}
|
||||
memcpy(resp, hdr, 4);
|
||||
if (apex_net_exact(fd, resp + 4, mlen - 4) != 0) {
|
||||
free(resp);
|
||||
close(fd);
|
||||
mcp_reply_error(c, "short MongoDB reply");
|
||||
return;
|
||||
}
|
||||
close(fd);
|
||||
if (le32(resp + 12) != 1) {
|
||||
free(resp);
|
||||
mcp_reply_error(c, "not an OP_REPLY");
|
||||
return;
|
||||
}
|
||||
doc_len = le32(resp + 36);
|
||||
doc_off = 36;
|
||||
if (doc_len < 5 || doc_off + doc_len > mlen) {
|
||||
free(resp);
|
||||
mcp_reply_error(c, "malformed BSON document");
|
||||
return;
|
||||
}
|
||||
version[0] = '\0';
|
||||
if (bson_get(resp + doc_off, doc_len, "ok", &v))
|
||||
ok = bson_number(&v, &ok_set);
|
||||
if (bson_get(resp + doc_off, doc_len, "maxWireVersion", &v)) {
|
||||
int set = 0;
|
||||
double d = bson_number(&v, &set);
|
||||
|
||||
if (set)
|
||||
max_wire = (long)d;
|
||||
}
|
||||
if (bson_get(resp + doc_off, doc_len, "isWritablePrimary", &v)) {
|
||||
bson_bool(&v, &writable);
|
||||
bool_set = 1;
|
||||
} else if (bson_get(resp + doc_off, doc_len, "ismaster", &v)) {
|
||||
bson_bool(&v, &writable);
|
||||
bool_set = 1;
|
||||
}
|
||||
if (bson_get(resp + doc_off, doc_len, "version", &v))
|
||||
bson_string(&v, version, sizeof(version));
|
||||
free(resp);
|
||||
apex_audit("mongo_probe", target, port, 1, "isMaster answered", "OP_QUERY");
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"target\":");
|
||||
apex_json_str(&b, target);
|
||||
mcp_buf_printf(&b, ",\"port\":%d,\"mongo\":true,\"ok\":", port);
|
||||
if (ok_set)
|
||||
mcp_buf_printf(&b, "%.3f", ok);
|
||||
else
|
||||
mcp_buf_puts(&b, "null");
|
||||
mcp_buf_printf(&b, ",\"max_wire_version\":%ld,\"writable_primary\":",
|
||||
max_wire);
|
||||
if (bool_set)
|
||||
mcp_buf_puts(&b, writable ? "true" : "false");
|
||||
else
|
||||
mcp_buf_puts(&b, "null");
|
||||
mcp_buf_puts(&b, ",\"version\":");
|
||||
apex_json_str(&b, version);
|
||||
mcp_buf_puts(&b, "}");
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ memcached_probe */
|
||||
|
||||
static void t_memcached_probe(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
int port = mcp_arg_int(args, "port", 11211);
|
||||
int fd;
|
||||
char line[1024];
|
||||
char version[64];
|
||||
char connections[64];
|
||||
char items[64];
|
||||
char maxbytes[64];
|
||||
char uptime[64];
|
||||
int stats = 0;
|
||||
int lines = 0;
|
||||
int memcached = 0;
|
||||
mcp_buf b;
|
||||
|
||||
(void)user;
|
||||
if (target == NULL || *target == '\0') {
|
||||
mcp_reply_error(c, "target is required");
|
||||
return;
|
||||
}
|
||||
if (port <= 0 || port > 65535) {
|
||||
mcp_reply_error(c, "port out of range");
|
||||
return;
|
||||
}
|
||||
if (!gated(c, "memcached_probe", target, port))
|
||||
return;
|
||||
fd = tcp_connect_host(target, port, 6000);
|
||||
if (fd < 0) {
|
||||
mcp_reply_error(c, "cannot connect to the memcached service");
|
||||
return;
|
||||
}
|
||||
version[0] = connections[0] = items[0] = maxbytes[0] = uptime[0] = '\0';
|
||||
if (apex_net_write(fd, "stats\r\n") == 0) {
|
||||
while (lines < 300 && apex_net_line(fd, line, sizeof(line)) >= 0) {
|
||||
lines++;
|
||||
if (strcmp(line, "END") == 0) {
|
||||
memcached = stats > 0;
|
||||
break;
|
||||
}
|
||||
if (strcmp(line, "ERROR") == 0)
|
||||
break;
|
||||
if (strncmp(line, "STAT ", 5) == 0) {
|
||||
char *key = line + 5;
|
||||
char *val = strchr(key, ' ');
|
||||
size_t kl;
|
||||
|
||||
if (val == NULL)
|
||||
continue;
|
||||
*val++ = '\0';
|
||||
kl = strlen(key);
|
||||
stats++;
|
||||
if (kl == 7 && strcmp(key, "version") == 0)
|
||||
snprintf(version, sizeof(version), "%.48s", val);
|
||||
else if (kl == 16 &&
|
||||
strcmp(key, "curr_connections") == 0)
|
||||
snprintf(connections, sizeof(connections),
|
||||
"%.48s", val);
|
||||
else if (kl == 10 && strcmp(key, "curr_items") == 0)
|
||||
snprintf(items, sizeof(items), "%.48s", val);
|
||||
else if (kl == 14 &&
|
||||
strcmp(key, "limit_maxbytes") == 0)
|
||||
snprintf(maxbytes, sizeof(maxbytes), "%.48s", val);
|
||||
else if (kl == 6 && strcmp(key, "uptime") == 0)
|
||||
snprintf(uptime, sizeof(uptime), "%.48s", val);
|
||||
}
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
if (memcached)
|
||||
apex_audit("memcached_probe", target, port, 0,
|
||||
"unauthenticated stats", version);
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"target\":");
|
||||
apex_json_str(&b, target);
|
||||
mcp_buf_printf(&b, ",\"port\":%d,\"memcached\":%s,\"open\":%s,"
|
||||
"\"stats_count\":%d,\"version\":", port,
|
||||
memcached ? "true" : "false",
|
||||
memcached ? "true" : "false", stats);
|
||||
apex_json_str(&b, version);
|
||||
mcp_buf_puts(&b, ",\"curr_connections\":");
|
||||
apex_json_str(&b, connections);
|
||||
mcp_buf_puts(&b, ",\"curr_items\":");
|
||||
apex_json_str(&b, items);
|
||||
mcp_buf_puts(&b, ",\"limit_maxbytes\":");
|
||||
apex_json_str(&b, maxbytes);
|
||||
mcp_buf_puts(&b, ",\"uptime\":");
|
||||
apex_json_str(&b, uptime);
|
||||
mcp_buf_puts(&b, "}");
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
const mcp_tool TOOLS_DB[] = {
|
||||
{ "mysql_probe",
|
||||
"Read the MySQL/MariaDB initial handshake: protocol version, server "
|
||||
"version, thread id, auth plugin and capability flags (TLS, secure "
|
||||
"connection, plugin auth). No credentials are sent and no login is "
|
||||
"attempted. Gate: the target must be in scope.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"target\":{\"type\":\"string\"},"
|
||||
"\"port\":{\"type\":\"integer\",\"description\":\"default 3306\"}},"
|
||||
"\"required\":[\"target\"]}",
|
||||
t_mysql_probe },
|
||||
{ "postgres_probe",
|
||||
"Ask PostgreSQL whether it offers SSL, then send one StartupMessage as "
|
||||
"user postgres and report the authentication method: trust, cleartext, "
|
||||
"md5, scram (with mechanism) or rejected (with the server message). "
|
||||
"Trust is audited as open. No password is sent. Gate: the target must "
|
||||
"be in scope.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"target\":{\"type\":\"string\"},"
|
||||
"\"port\":{\"type\":\"integer\",\"description\":\"default 5432\"},"
|
||||
"\"user\":{\"type\":\"string\",\"description\":\"default postgres\"}},"
|
||||
"\"required\":[\"target\"]}",
|
||||
t_postgres_probe },
|
||||
{ "mongo_probe",
|
||||
"Send a legacy OP_QUERY isMaster to admin.$cmd and parse the BSON reply: "
|
||||
"ok, maxWireVersion, writable primary and a version string when the "
|
||||
"server returns one. No authentication and no writes. Gate: the target "
|
||||
"must be in scope.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"target\":{\"type\":\"string\"},"
|
||||
"\"port\":{\"type\":\"integer\",\"description\":\"default 27017\"}},"
|
||||
"\"required\":[\"target\"]}",
|
||||
t_mongo_probe },
|
||||
{ "memcached_probe",
|
||||
"Send one stats command to memcached and report whether it answers "
|
||||
"without authentication, plus version, current connections, current "
|
||||
"items, memory limit and uptime. No keys are read or written. Gate: "
|
||||
"the target must be in scope.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"target\":{\"type\":\"string\"},"
|
||||
"\"port\":{\"type\":\"integer\",\"description\":\"default 11211\"}},"
|
||||
"\"required\":[\"target\"]}",
|
||||
t_memcached_probe },
|
||||
};
|
||||
|
||||
const size_t TOOLS_DB_N = sizeof(TOOLS_DB) / sizeof(TOOLS_DB[0]);
|
||||
@@ -97,6 +97,21 @@ static int read_exact(int fd, unsigned char *buf, size_t n)
|
||||
* Read a reply that may span several lines ("250-first", "250 last"). Stops at
|
||||
* the first line whose fourth byte is not '-'. Returns bytes stored or -1.
|
||||
*/
|
||||
int apex_net_write(int fd, const char *s)
|
||||
{
|
||||
return write_all(fd, s);
|
||||
}
|
||||
|
||||
int apex_net_line(int fd, char *buf, size_t n)
|
||||
{
|
||||
return read_line(fd, buf, n);
|
||||
}
|
||||
|
||||
int apex_net_exact(int fd, unsigned char *buf, size_t n)
|
||||
{
|
||||
return read_exact(fd, buf, n);
|
||||
}
|
||||
|
||||
static int read_reply(int fd, char *out, size_t n)
|
||||
{
|
||||
size_t used = 0;
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ import re
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
EXPECTED_TOOLS = 73
|
||||
EXPECTED_TOOLS = 77
|
||||
GATE = ("gated(", "gated_cmd(", "gated_run(", "apex_scope_check(")
|
||||
NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(")
|
||||
# Tools whose "target" argument filters local records; they never touch it.
|
||||
|
||||
+186
-2
@@ -134,7 +134,7 @@ res, _ = run([
|
||||
], home=empty)
|
||||
check("tools/list answers", any(r.get("id") == 1 for r in res))
|
||||
tools = [r for r in res if r.get("id") == 1][0]["result"]["tools"]
|
||||
check("73 tools registered", len(tools) == 73, len(tools))
|
||||
check("77 tools registered", len(tools) == 77, len(tools))
|
||||
names = {t["name"] for t in tools}
|
||||
for need in ("portscan", "nmap", "http_request", "marauder_scan",
|
||||
"method_playbook", "finding_add", "finding_update", "scope_check",
|
||||
@@ -1560,7 +1560,7 @@ try:
|
||||
check("http initialize", init["result"]["serverInfo"]["name"] == "apex-twin",
|
||||
init)
|
||||
listing = post({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
|
||||
check("http tools/list", len(listing["result"]["tools"]) == 73)
|
||||
check("http tools/list", len(listing["result"]["tools"]) == 77)
|
||||
shown = post(call(3, "scope_show"))
|
||||
check("http scope_show", '"loaded":true' in shown["result"]["content"][0]["text"])
|
||||
# the id must be the request's id, not one found inside the arguments
|
||||
@@ -3524,6 +3524,190 @@ shutil.rmtree(tls_dir, ignore_errors=True)
|
||||
shutil.rmtree(deep_home, ignore_errors=True)
|
||||
shutil.rmtree(proto_home, ignore_errors=True)
|
||||
|
||||
print("\n== database probes ==")
|
||||
|
||||
|
||||
def mysql_handshake():
|
||||
caps = 0x0800 | 0x8000 | 0x00080000
|
||||
payload = (bytes([10]) + b"8.0.35-test\x00" + struct.pack("<I", 42) +
|
||||
b"12345678" + b"\x00" +
|
||||
struct.pack("<H", caps & 0xffff) + bytes([33]) +
|
||||
struct.pack("<H", 2) + struct.pack("<H", caps >> 16) +
|
||||
bytes([21]) + b"\x00" * 10 + b"abcdefghijklm" +
|
||||
b"caching_sha2_password\x00")
|
||||
return struct.pack("<I", len(payload))[:3] + b"\x00" + payload
|
||||
|
||||
|
||||
def mysql_handler(conn):
|
||||
conn.sendall(mysql_handshake())
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
def pg_handler(mode, ssl=True):
|
||||
def handle(conn):
|
||||
head = conn.recv(8)
|
||||
if len(head) < 8:
|
||||
return
|
||||
length, code = struct.unpack(">II", head)
|
||||
if code == 80877103:
|
||||
conn.sendall(b"S" if ssl else b"N")
|
||||
return
|
||||
rest = b""
|
||||
while len(rest) < length - 8:
|
||||
chunk = conn.recv(length - 8 - len(rest))
|
||||
if not chunk:
|
||||
break
|
||||
rest += chunk
|
||||
if mode == "reject":
|
||||
err = (b"S" + b"FATAL\x00" + b"C" + b"28000\x00" +
|
||||
b"M" + b"no pg_hba entry\x00" + b"\x00")
|
||||
conn.sendall(b"E" + struct.pack(">I", 4 + len(err)) + err)
|
||||
return
|
||||
if mode == "trust":
|
||||
body = struct.pack(">I", 0)
|
||||
elif mode == "md5":
|
||||
body = struct.pack(">I", 5) + b"saltsalt"
|
||||
else:
|
||||
body = struct.pack(">I", 10) + b"SCRAM-SHA-256\x00\x00"
|
||||
conn.sendall(b"R" + struct.pack(">I", 4 + len(body)) + body)
|
||||
time.sleep(0.05)
|
||||
return handle
|
||||
|
||||
|
||||
def bson_element(kind, key, value):
|
||||
if kind == "double":
|
||||
return b"\x01" + key.encode() + b"\x00" + struct.pack("<d", value)
|
||||
if kind == "string":
|
||||
raw = value.encode()
|
||||
return (b"\x02" + key.encode() + b"\x00" +
|
||||
struct.pack("<I", len(raw) + 1) + raw + b"\x00")
|
||||
if kind == "int":
|
||||
return b"\x10" + key.encode() + b"\x00" + struct.pack("<i", value)
|
||||
if kind == "bool":
|
||||
return b"\x08" + key.encode() + b"\x00" + bytes([1 if value else 0])
|
||||
raise ValueError(kind)
|
||||
|
||||
|
||||
def bson_doc(body):
|
||||
return struct.pack("<i", len(body) + 5) + body + b"\x00"
|
||||
|
||||
|
||||
def mongo_handler(conn):
|
||||
head = conn.recv(4)
|
||||
if len(head) < 4:
|
||||
return
|
||||
need = struct.unpack("<i", head)[0]
|
||||
msg = head
|
||||
while len(msg) < need:
|
||||
chunk = conn.recv(need - len(msg))
|
||||
if not chunk:
|
||||
break
|
||||
msg += chunk
|
||||
reqid = struct.unpack("<i", msg[4:8])[0]
|
||||
doc = bson_doc(bson_element("double", "ok", 1.0) +
|
||||
bson_element("int", "maxWireVersion", 21) +
|
||||
bson_element("bool", "isWritablePrimary", True) +
|
||||
bson_element("string", "version", "7.0.5"))
|
||||
body = struct.pack("<iqii", 0, 0, 0, 1) + doc
|
||||
conn.sendall(struct.pack("<iiii", 16 + len(body), 1, reqid, 1) + body)
|
||||
|
||||
|
||||
def memcached_handler(conn):
|
||||
f = conn.makefile("rb")
|
||||
line = f.readline()
|
||||
if line.strip().upper() == b"STATS":
|
||||
conn.sendall(b"STAT version 1.6.21\r\n"
|
||||
b"STAT curr_connections 4\r\n"
|
||||
b"STAT curr_items 12\r\n"
|
||||
b"STAT limit_maxbytes 67108864\r\n"
|
||||
b"STAT uptime 900\r\nEND\r\n")
|
||||
|
||||
|
||||
mysql_srv, mysql_port = start_line_server(mysql_handler)
|
||||
pg_trust_srv, pg_trust_port = start_line_server(pg_handler("trust"))
|
||||
pg_md5_srv, pg_md5_port = start_line_server(pg_handler("md5"))
|
||||
pg_reject_srv, pg_reject_port = start_line_server(pg_handler("reject"))
|
||||
pg_nossl_srv, pg_nossl_port = start_line_server(pg_handler("trust", ssl=False))
|
||||
pg_scram_srv, pg_scram_port = start_line_server(pg_handler("scram"))
|
||||
mongo_srv, mongo_port = start_line_server(mongo_handler)
|
||||
memcached_srv, memcached_port = start_line_server(memcached_handler)
|
||||
memcached_bad_srv, memcached_bad_port = start_line_server(
|
||||
lambda conn: conn.sendall(b"ERROR\r\n"))
|
||||
|
||||
db_home = tempfile.mkdtemp(prefix="apex-db-")
|
||||
write_scope(db_home, {"label": "db", "expires": "2099-12-31T23:59:59Z",
|
||||
"allow_private": True, "allow_ip": ["127.0.0.1"],
|
||||
"allow_port": [str(mysql_port), str(pg_trust_port),
|
||||
str(pg_md5_port), str(pg_reject_port),
|
||||
str(pg_nossl_port), str(pg_scram_port),
|
||||
str(mongo_port), str(memcached_port),
|
||||
str(memcached_bad_port)]})
|
||||
res, _ = run([
|
||||
call(1, "mysql_probe", target="127.0.0.1", port=mysql_port),
|
||||
call(2, "postgres_probe", target="127.0.0.1", port=pg_trust_port),
|
||||
call(3, "postgres_probe", target="127.0.0.1", port=pg_md5_port),
|
||||
call(4, "postgres_probe", target="127.0.0.1", port=pg_reject_port),
|
||||
call(5, "mongo_probe", target="127.0.0.1", port=mongo_port),
|
||||
call(6, "memcached_probe", target="127.0.0.1", port=memcached_port),
|
||||
call(7, "mysql_probe", target="198.51.100.9", port=3306),
|
||||
call(8, "postgres_probe", target="127.0.0.1", port=pg_nossl_port),
|
||||
call(9, "postgres_probe", target="127.0.0.1", port=pg_scram_port),
|
||||
call(10, "memcached_probe", target="127.0.0.1", port=memcached_bad_port),
|
||||
], home=db_home)
|
||||
by_id = {r.get("id"): r for r in res}
|
||||
my = json.loads(text(by_id[1]))
|
||||
check("mysql_probe reads the handshake", my["mysql"] is True and
|
||||
my["server_version"] == "8.0.35-test" and my["thread_id"] == 42, my)
|
||||
check("mysql_probe names the auth plugin", my["auth_plugin"] ==
|
||||
"caching_sha2_password", my)
|
||||
check("mysql_probe decodes the capability flags",
|
||||
my["tls"] is True and my["secure_connection"] is True and
|
||||
my["plugin_auth"] is True, my)
|
||||
pg_trust = json.loads(text(by_id[2]))
|
||||
check("postgres_probe learns that SSL is offered",
|
||||
pg_trust["ssl"] == "supported", pg_trust)
|
||||
check("postgres_probe detects trust authentication",
|
||||
pg_trust["auth"] == "trust" and pg_trust["auth_code"] == 0, pg_trust)
|
||||
pg_md5 = json.loads(text(by_id[3]))
|
||||
check("postgres_probe detects md5 authentication",
|
||||
pg_md5["auth"] == "md5" and pg_md5["auth_code"] == 5, pg_md5)
|
||||
pg_reject = json.loads(text(by_id[4]))
|
||||
check("postgres_probe reports a rejected startup",
|
||||
pg_reject["auth"] == "rejected" and
|
||||
"no pg_hba" in pg_reject["detail"], pg_reject)
|
||||
mongo = json.loads(text(by_id[5]))
|
||||
check("mongo_probe parses the isMaster reply",
|
||||
mongo["mongo"] is True and mongo["ok"] == 1.0 and
|
||||
mongo["max_wire_version"] == 21, mongo)
|
||||
check("mongo_probe reads the writable-primary flag and version",
|
||||
mongo["writable_primary"] is True and mongo["version"] == "7.0.5", mongo)
|
||||
mc = json.loads(text(by_id[6]))
|
||||
check("memcached_probe sees an open instance",
|
||||
mc["memcached"] is True and mc["open"] is True and
|
||||
mc["stats_count"] == 5, mc)
|
||||
check("memcached_probe reads the useful counters",
|
||||
mc["version"] == "1.6.21" and mc["curr_connections"] == "4" and
|
||||
mc["curr_items"] == "12" and mc["limit_maxbytes"] == "67108864" and
|
||||
mc["uptime"] == "900", mc)
|
||||
pg_nossl = json.loads(text(by_id[8]))
|
||||
check("postgres_probe reports a server without SSL",
|
||||
pg_nossl["ssl"] == "not-supported" and pg_nossl["auth"] == "trust",
|
||||
pg_nossl)
|
||||
pg_scram = json.loads(text(by_id[9]))
|
||||
check("postgres_probe names the SCRAM mechanism",
|
||||
pg_scram["auth"] == "scram" and
|
||||
pg_scram["mechanism"] == "SCRAM-SHA-256", pg_scram)
|
||||
mc_bad = json.loads(text(by_id[10]))
|
||||
check("memcached_probe rejects a service that is not memcached",
|
||||
mc_bad["memcached"] is False and mc_bad["open"] is False, mc_bad)
|
||||
check("mysql_probe refuses an out-of-scope target", err(by_id[7]),
|
||||
text(by_id[7]))
|
||||
for srv in (mysql_srv, pg_trust_srv, pg_md5_srv, pg_reject_srv,
|
||||
pg_nossl_srv, pg_scram_srv, mongo_srv, memcached_srv,
|
||||
memcached_bad_srv):
|
||||
srv.close()
|
||||
shutil.rmtree(db_home, ignore_errors=True)
|
||||
|
||||
print("\n== esp32 tools ==")
|
||||
esp_home = tempfile.mkdtemp(prefix="apex-esp-")
|
||||
write_scope(esp_home, {"label": "esp", "expires": "2099-12-31T23:59:59Z"})
|
||||
|
||||
Reference in new issue
Block a user