Security Go — Attack Detection Library

Security Go — Attack Detection Library

English

An attack detection package written in Go, covering 32 detectors, 5 major attack categories, and 3 pluggable storage backends. Unified interface + registry pattern, a pure detection library that fits any Go HTTP framework.

Design

Core Principles

  • Zero-dependency detection — every detector uses only Go’s standard-library regexp, no external dependencies
  • Unified interface — each detector implements the Detector interface (Name() + Detect()), managed centrally through the Engine registry
  • Precompiled regexes — all patterns are compiled at var initialization, so runtime overhead is zero
  • Configure on demand — injection/protocol/data/file detectors work out of the box; the HTTP validators need app-specific configuration

    Design Architecture

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
                      ┌───────────────────────────────┐
│ security.Engine │
│ ┌─────────────────────────┐ │
│ │ Detector Registry │ │
│ │ map[string]Detector │ │
│ └─────────────────────────┘ │
│ │
│ Detect(name, input) │
│ DetectAll(input) │
│ DetectRequest(*http.Request) │
└──────────────┬────────────────┘

┌─────────────────┬───────────┴───────────┬─────────────────┐
│ │ │ │
┌──────▼──────┐ ┌──────▼──────┐ ┌────────────▼────────┐ ┌───▼───────────┐
│ injection │ │ protocol │ │ data │ │ file │
│ (10) │ │ (9) │ │ (5) │ │ (3) │
│ │ │ │ │ │ │ │
│ xss, sql, │ │ ssrf, xxe, │ │ deser, csv, │ │ traversal, │
│ command, │ │ header, │ │ mail, jwt, │ │ upload, │
│ nosql, │ │ host, │ │ proto_poll │ │ data_leak │
│ ldap, │ │ smuggling, │ │ │ │ │
│ xpath, │ │ redirect, │ │ │ │ │
│ jndi, ssi, │ │ cors, ws, │ │ │ │ │
│ graphql, │ │ dns_rebind │ │ │ │ │
│ ssti │ │ │ │ │ │ │
└─────────────┘ └─────────────┘ └─────────────────────┘ └───────────────┘

┌───────────────────────────────────────────────────────────────┤
│ │
┌──────▼──────────┐ ┌──────────▼──────────┐
│ httpval │ │ storage │
│ (5) │ │ ┌──────────────┐ │
│ │ │ │ Backend │ │
│ method, size, │ │ │ interface │ │
│ type, csrf, │ │ └──┬───┬───┬───┘ │
│ ip_blacklist │◄───── uses storage.Backend ───────────►│ Memory File Redis │
│ (needs config) │ │ │
└─────────────────┘ └────────────────────┘

Data Flow

1
2
3
4
5
6
7
8
9
HTTP Request


┌──────────────┐ ┌─────────────────┐ ┌──────────────┐
│ collectInputs│────▶│ DetectAll() │────▶│ []*Result │
│ URL, Query, │ │ per-detector call │ │ aggregated │
│ Headers, │ │ Detect(input) │ │ │
│ Cookies │ └─────────────────┘ └──────────────┘
└──────────────┘

Severity Levels

Level Description Typical Scenario
SeverityLow Low risk Invalid HTTP method, Content-Type mismatch
SeverityMedium Medium risk CORS misconfiguration, open redirect, GraphQL introspection
SeverityHigh High risk XSS, SQL injection, SSRF, path traversal
SeverityCritical Critical Command injection, JNDI, SSTI, XXE, data leakage

What It Detects

Injection Attacks (10)

Detector Detection Patterns
XSS <script>, on[a-z]+= event handlers, javascript: pseudo-protocol, SVG/CSS injection, eval(), document.cookie
SQL Injection UNION SELECT (including /**/ bypasses), sleep/benchmark/pg_sleep, boolean blind injection, information_schema enumeration, xp_cmdshell
Command Injection Backticks, $(), pipe characters, /dev/tcp, PHP system/exec/shell_exec, chained execution && ; `\ \ `
NoSQL Injection MongoDB $ne $gt $regex $where operators, $func, JSON key injection
LDAP Injection Filter operators `(\ (&(!,objectClass=*`, URL-encoding bypasses
XPATH Injection Boolean bypass ' or '1'='1, string-length(), count()
JNDI/Log4Shell ${jndi:ldap://, ${lower:j} obfuscation, ${env:} environment variables, ldap/rmi/dns protocols
SSI Injection <!--#exec cmd=, <!--#include file=, <!--#echo var=
GraphQL Injection __schema/__type introspection, deeply nested DoS (5+ levels), mutation detection
SSTI Jinja2 {{}}, FreeMarker ${}, ERB <% %>, Python MRO traversal, config/self access

Protocol and Request Attacks (9)

Detector Detection Patterns
SSRF Internal IPs (127/10/172.16/192.168), 169.254.169.254, IPv6 loopback, gopher/dict/file/ftp protocols
XXE <!ENTITY SYSTEM/PUBLIC, parameter entities %entity;, DOCTYPE declarations
HTTP Header Injection CRLF %0d%0a / \r\n, Set-Cookie/Location/Content-Length injection
Host Header Attack CRLF Host injection, X-Forwarded-Host, X-Original-URL poisoning
Request Smuggling Transfer-Encoding/Content-Length mismatch, double TE headers, \x0b folded-header obfuscation
Open Redirect //evil.com protocol-relative URLs, javascript:/data: pseudo-protocols
CORS Bypass Origin: null, Access-Control-Allow-* header injection
WebSocket Hijacking Upgrade header injection, null Origin bypass, ws:// URLs
DNS Rebinding Internal IPs in the Host header, localhost, short hostnames with no TLD

HTTP Protocol Validation (5)

Detector Description
HTTP Method Only GET/POST/PUT/DELETE/HEAD/OPTIONS/PATCH are allowed; anything else raises an alert
Request Body Size Exceeding the limit (10MB by default) raises an alert
Content-Type Only the configured MIME type allowlist is accepted
CSRF Origin Checks whether the Origin of a cross-origin request matches the Host, with support for an extra allowlist
IP Blacklist Auto-bans after N attacks within a time window (default 5 per 60s → 15-minute ban), with File/Redis/Memory storage

Data and Deserialization Attacks (5)

Detector Detection Patterns
PHP Deserialization O:digits: / C:digits: serialized objects, unserialize(), magic methods (__wakeup/__destruct)
CSV Injection `=cmd\ ,@SUM(,+/-formula prefixes,HYPERLINK/DDE`
Email Header Injection Bcc/Cc/From/To injection, MIME multipart, boundary parameters
JWT Attacks alg: none bypass, kid path traversal, empty-signature detection (structural decoding analysis)
Prototype Pollution __proto__/constructor keys, __defineGetter__/__defineSetter__

Files and Sensitive Data (3)

Detector Detection Patterns
Path Traversal ../, ..\\, php://filter/php://input, null bytes, URL-encoding bypasses, /etc/passwd
Malicious Upload Extension allowlist (15 types) + content scan for PHP tags <?php/<?=
Data Leakage Credit card numbers, AWS Access Keys, private keys -----BEGIN, database connection strings, API tokens, JWT secrets, GitHub PATs

Storage Backends (3)

Backend Description
Memory sync.Mutex + map, expired entries swept every 30s
File JSON file persistence, flushed on Close
Redis Separate submodule, Pipeline Incr + TTL, requires go-redis/v9

Usage

Installation

1
go get github.com/erikwang2013/security-go

Quick Start

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"fmt"
"github.com/erikwang2013/security-go"
"github.com/erikwang2013/security-go/all"
)

func main() {
e := security.NewEngine()
all.RegisterAll(e) // register all 27 zero-config detectors in one call

// single detection
r := e.Detect("xss", "<script>alert(1)</script>")
fmt.Printf("Detected: %v, Severity: %d\n", r.Detected, r.Severity)

// full scan
for _, r := range e.DetectAll("' OR '1'='1") {
fmt.Printf("[%s] %s\n", r.Name, r.Message)
}
}

HTTP Request Detection

1
2
3
4
5
6
7
8
9
10
func handler(w http.ResponseWriter, r *http.Request) {
e := security.NewEngine()
all.RegisterAll(e)

for _, result := range e.DetectRequest(r) {
if result.Detected {
log.Printf("Attack detected: [%s] %s", result.Name, result.Message)
}
}
}

HTTP Validator Configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// method validation
e.Register(&httpval.Method{})

// request body size limit
e.Register(httpval.NewBodySize(5 * 1024 * 1024)) // 5MB

// Content-Type allowlist
e.Register(httpval.NewContentType([]string{
"application/json", "application/x-www-form-urlencoded",
}))

// CSRF Origin check
e.Register(&httpval.CSRFOrigin{
Host: "example.com", AllowList: []string{"api.example.com"},
})

// IP blacklist (auto-ban: 5 per 60s → 15-minute ban)
mem := storage.NewMemory()
defer mem.Close()
bl := httpval.NewIPBlacklist(mem)
e.Register(bl)

// record when an attack happens
blocked, _ := bl.RecordAttack(clientIP)

Custom Detectors

1
2
3
4
5
6
7
8
9
10
11
12
type MyDetector struct{}

func (d *MyDetector) Name() string { return "my_detector" }

func (d *MyDetector) Detect(input string) *security.Result {
return &security.Result{
Name: "my_detector", Detected: strings.Contains(input, "evil"),
Severity: security.SeverityHigh, Message: "malicious content detected",
}
}

e.Register(&MyDetector{})


Copyright (c) 2026 erik erik@erik.xyzhttps://erik.xyz