[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-111234":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":8,"htmlUrl":8,"language":9,"languages":8,"totalLinesOfCode":8,"stars":10,"forks":11,"watchers":12,"openIssues":13,"contributorsCount":13,"subscribersCount":13,"size":13,"stars1d":13,"stars7d":11,"stars30d":14,"stars90d":13,"forks30d":13,"starsTrendScore":13,"compositeScore":15,"rankGlobal":8,"rankLanguage":8,"license":16,"archived":17,"fork":17,"defaultBranch":18,"hasWiki":19,"hasPages":17,"topics":20,"createdAt":8,"pushedAt":21,"updatedAt":22,"readmeContent":23,"aiSummary":24,"trendingCount":13,"starSnapshotCount":13,"syncStatus":25,"lastSyncTime":26,"discoverSource":27},111234,"frp-ban","799953468\u002Ffrp-ban","799953468",null,"C#",173,1,137,0,36,42,"MIT License",false,"master",true,[],"2026-11-14 04:57:41","2026-11-18 23:05:45","# frp-ban\n\nHigh-performance security plugin for [frps](https:\u002F\u002Fgithub.com\u002Ffatedier\u002Ffrp) that blocks banned IP addresses using a TLS-encrypted custom TCP protocol for distributed IP ban management.\n\n## Features\n\n- ✅ **Frp Plugin Integration** — Intercepts banned IPs at frps Login\u002FNewUserConn stage\n- ✅ **TLS Encrypted Communication** — Binary protocol + TLS 1.2\u002F1.3 between server and clients\n- ✅ **Rule Engine** — Client monitors log files and triggers bans automatically based on regex patterns\n- ✅ **High Performance** — ConcurrentDictionary lookup, pooled bounded frames, cached regexes, event-driven log tailing\n- ✅ **Production Hardened** — Bounded connections and queues, per-IP connection\u002Fmessage limits, handshake deadlines\n\n---\n\n## Architecture\n\n```\n CLIENT MACHINE (FrpBan.Client)          FRP SERVER\n ┌──────────────────────────────┐       ┌──────────────────────────────────┐\n │ frpc                          │       │ frps (:7000)                     │\n │   │                           │       │   │ plugin callbacks              │\n │   ▼ frp tunnel                │◄─────►│   ▼                               │\n │ services (SSH, web, ...)      │       │ FrpBan (:9000 HTTP, :9443 TLS)  │\n │                               │       │   POST \u002Fhandler  (Login\u002FNewUser)  │\n │ FrpBan.Client                 │       │                                   │\n │  ├─ Log monitors (rules.d\u002F)   │       │ BanService (ConcurrentDict)      │\n │  │   FileSystemWatcher        │       │   ├─ IsBanned() O(1) lookup      │\n │  │   rule matching engine     │       │   └─ Auto-expire expired bans    │\n │  ▼                            │       │                                   │\n │  TLS client ──────────────────┼──────►│ TCP server (:9443)               │\n │    auto-reconnect             │       │   ├─ TLS 1.2\u002F1.3 only            │\n │    health check (ping\u002Fpong)   │       │   ├─ Connection + message limits  │\n │    exponential backoff        │       │   └─ Connection pool (max 100)   │\n └──────────────────────────────┘       └──────────────────────────────────┘\n```\n\n**Workflow:**\n1. frps calls FrpBan's `POST \u002Fhandler` before each `Login` and `NewUserConn` operation\n2. FrpBan checks in-memory ban list, rejects banned IPs from establishing tunnels\n3. Client FrpBan.Client monitors log files, sends ban requests via TLS connection when attack patterns match\n4. Server receives ban requests, updates memory and persistent storage, blocks that IP from subsequent connections\n\n---\n\n## Project Structure\n\n```\nsrc\u002F\n├── FrpBan.Protocol\u002F          # Shared binary protocol library\n│   ├── Message.cs            # Bounded message framing (max 64 KiB body)\n│   ├── Messages\u002F             # Individual wire message types\n│   ├── Transport\u002F            # Exact asynchronous frame reads\n│   ├── Security\u002F             # Shared TLS trust validation\n│   └── MessageType.cs        # Protocol message types\n├── FrpBan\u002F                   # Server application\n│   ├── Services\u002F\n│   │   ├── BanService.cs     # ConcurrentDictionary-based ban storage\n│   │   └── TcpServerService.cs  # TLS server + rate limiting\n│   ├── Endpoints\u002F            # HTTP mapping and pre-body authorization\n│   ├── Security\u002F             # Cached callback networks and bounded rate limits\n│   ├── Handlers\u002F\n│   │   └── PluginRequestHandler.cs  # frps plugin handler\n│   └── Configuration\u002F\n│       └── PluginSettings.cs\n└── FrpBan.Client\u002F            # Client application\n    ├── Services\u002F\n    │   ├── ClientConnectionService.cs  # Auto-reconnect TLS client\n    │   ├── BanDeliveryService.cs # Bounded retry queue for disconnected clients\n    │   ├── FileLogMonitor.cs  # Serialized, bounded UTF-8 log tailing\n    │   ├── RuleMatchEngine.cs # Regex pattern matching engine\n    │   └── RulesLoader.cs     # YAML rule configuration loader\n    └── rules.d\u002F               # Ban rule definitions (YAML)\n\ntests\u002FFrpBan.Tests\u002F            # Unit, security and loopback integration tests\nDirectory.Build.props         # Shared build properties\nDirectory.Packages.props      # Central NuGet package versions\n```\n\n---\n\n## Security Features\n\n### ✅ Implemented Protections\n\n- **TLS rate limiting**: 10 new connections and 120 protocol messages\u002Fminute per IP (configurable)\n- **Connection pooling**: Max 100 concurrent TLS connections (configurable)\n- **Bounded input**: 64 KiB protocol\u002FHTTP body limit, 64 Ki-character log-line limit\n- **TLS 1.2\u002F1.3 only**: Disabled outdated protocols\n- **CIDR validation**: Validated prefix lengths (0-32 for IPv4, 0-128 for IPv6)\n- **Production TLS enforcement**: Cannot disable certificate validation in production\n- **Atomic persistence**: One coalescing writer and same-directory atomic file replacement\n\n---\n\n## Configuration\n\n### Server (`src\u002FFrpBan\u002Fappsettings.json`)\n\n```json\n{\n  \"PluginSettings\": {\n    \"Token\": \"CHANGE_ME_TO_A_LONG_RANDOM_SECRET\",\n    \"BanFilePath\": \"\u002Fvar\u002Flib\u002Ffrp-ban\u002Fbans.json\",\n    \"AppLogPath\": \"\u002Fvar\u002Flog\u002Ffrp-ban\u002Ffrp-ban-.log\",\n    \"AllowedPluginAddresses\": [\"127.0.0.1\", \"::1\", \"192.168.1.0\u002F24\"],\n    \"DefaultBanDurationSeconds\": 3600,\n    \"Tls\": {\n      \"Enabled\": true,\n      \"TcpListenerEnabled\": true,\n      \"Port\": 9443,\n      \"CertificatePath\": \"\u002Fetc\u002Ffrp-ban\u002Fcerts\u002Fserver.pfx\",\n      \"CertificatePassword\": \"your-cert-password\",\n      \"RequireClientCertificate\": false\n    }\n  },\n  \"Logging\": {\n    \"LogLevel\": {\n      \"Default\": \"Information\",\n      \"Microsoft.AspNetCore\": \"Warning\"\n    }\n  },\n  \"urls\": \"http:\u002F\u002F127.0.0.1:9000\"\n}\n```\n\n| Key | Description |\n|-----|-------------|\n| `Token` | TLS client authentication token (use env var `PluginSettings__Token` in production) |\n| `BanFilePath` | JSON file path for persistent ban storage |\n| `AppLogPath` | Serilog log file path (auto-rotated) |\n| `AllowedPluginAddresses` | IPs\u002FCIDR allowed to call `\u002Fhandler` (frps localhost), empty = allow all |\n| `DefaultBanDurationSeconds` | Default ban duration (seconds), `0` = permanent |\n| `Tls.Enabled` | Enable TLS TCP listener |\n| `Tls.Port` | TLS listener port (default: 9443) |\n| `Logging.LogLevel.Default` | Minimum log level: Debug, Information, Warning, Error |\n\n**Production configuration:**\n```bash\n# Use environment variables for secrets\nexport PluginSettings__Token=\"$(openssl rand -base64 32)\"\nexport PluginSettings__Tls__CertificatePassword=\"$(cat \u002Fetc\u002Ffrp-ban\u002Fcerts\u002Fpassword.txt)\"\n```\n\nStartup rejects placeholder tokens and secrets shorter than 32 characters. HTTP\ncallbacks bind to loopback by default; configure the listener and trusted callback\naddresses explicitly if frps runs on another host. Ban durations use `null` for\nthe configured default and `0` for a permanent ban.\n\nTLS deadlines and limits are configured under `PluginSettings.Tls`:\n`MaxConcurrentConnections` (100), `MaxConnectionsPerMinute` (10),\n`MaxMessagesPerMinute` (120), `HandshakeTimeoutSeconds` (10),\n`IdleTimeoutSeconds` (90), and `WriteTimeoutSeconds` (10).\n\n### Client (`src\u002FFrpBan.Client\u002Fappsettings.json`)\n\n```json\n{\n  \"ClientSettings\": {\n    \"ServerAddress\": \"frps.example.com\",\n    \"ServerPort\": 9443,\n    \"Token\": \"CHANGE_ME_TO_A_LONG_RANDOM_SECRET\",\n    \"RulesPath\": \".\u002Frules.d\",\n    \"Tls\": {\n      \"ValidateServerCertificate\": true,\n      \"AllowSelfSignedCertificates\": false,\n      \"ClientCertificatePath\": null,\n      \"ClientCertificatePassword\": null,\n      \"CaCertificatePath\": null\n    },\n    \"Reconnection\": {\n      \"InitialDelayMs\": 5000,\n      \"MaxDelayMs\": 300000,\n      \"BackoffMultiplier\": 2.0,\n      \"MaxRetries\": -1,\n      \"HealthCheckIntervalMs\": 30000\n    }\n  }\n}\n```\n\nClient certificates are optional unless the server requires mTLS. Configure\n`CaCertificatePath` for a private CA; otherwise system trust is used.\n`ConnectionTimeoutSeconds` defaults to 15, `RequestTimeoutSeconds` to 10, and\n`MaxPendingBans` to 1024. Queued bans retry after reconnection and remain in memory\nonly; normal process shutdown drains tasks but does not persist this client queue.\n\n### Ban Rules (`src\u002FFrpBan.Client\u002Frules.d\u002F*.yaml`)\n\nExample: `01-ssh-bruteforce.yaml`\n```yaml\nrules:\n  - name: ssh-bruteforce\n    enabled: true\n    logSource:\n      type: file\n      path: \u002Fvar\u002Flog\u002Fauth.log\n    matching:\n      - type: regex\n        pattern: 'Failed password.*from (?\u003Cip>\\d+\\.\\d+\\.\\d+\\.\\d+)'\n    action:\n      type: threshold\n      maxMatches: 5\n      windowSeconds: 300\n      banDurationSeconds: 3600\n      reason: SSH brute force attempt\n    maxTrackedIps: 10000\n```\n\n**Rule options:**\n- `type: file` — Monitor file with FileSystemWatcher (efficient, no polling)\n- `type: journal` — Not implemented; rejected during rule loading\n- `action.type: threshold` — Trigger after `maxMatches` in `windowSeconds`\n- `banDurationSeconds: 0` — Permanent ban\n\n---\n\n## Build & Run\n\n### Release packages\n\nTagged releases provide Windows `.zip`, macOS `.tar.gz`, and Linux\n`.deb`, `.rpm`, Arch `.pkg.tar.zst`, Alpine `.apk` and portable `.tar.gz` builds for\nx64 and ARM64. Server (`frp-ban-…`) and client (`frp-ban-client-…`) are packaged\nseparately, each with its .NET runtime. Client packages also include YAML rules.\nSee [Release packaging and installation](docs\u002FRELEASING.md) for the full matrix,\nconfiguration steps and GitHub\u002FGitLab CI runner requirements.\n\n### Build\n\n```bash\n# Build all projects\ndotnet build FrpBan.slnx\n\n# Publish server (self-contained)\ndotnet publish src\u002FFrpBan -c Release -r linux-x64 --self-contained -o .\u002Fpublish\u002Fserver\n\n# Publish client\ndotnet publish src\u002FFrpBan.Client -c Release -r linux-x64 --self-contained -o .\u002Fpublish\u002Fclient\n```\n\n### Development\n\n```bash\n# Run server\ncd src\u002FFrpBan\ndotnet run\n\n# Run client\ncd src\u002FFrpBan.Client\ndotnet run\n```\n\n### Generate TLS Certificates\n\n```bash\n# Self-signed certificate for development\nopenssl req -x509 -newkey rsa:4096 -keyout server-key.pem -out server-cert.pem -days 365 -nodes \\\n  -subj \"\u002FCN=localhost\" -addext \"subjectAltName=DNS:localhost,IP:127.0.0.1\"\nopenssl pkcs12 -export -out server.pfx -inkey server-key.pem -in server-cert.pem\n\n# Set ClientSettings.Tls.CaCertificatePath to server-cert.pem for this local certificate.\n# For production, use Let's Encrypt or your organization's CA\n```\n\n---\n\n## Deployment\n\n### Server (systemd)\n\nInstall the appropriate native package using the steps in\n[Release packaging and installation](docs\u002FRELEASING.md). Packages install the\nservice, runtime and configuration directories; configure the token and TLS\ncertificate before starting the service.\n\n```bash\nsudo nano \u002Fetc\u002Ffrp-ban\u002Fappsettings.json\n# Configure Token and Tls.CertificatePath, or set secrets in \u002Fetc\u002Ffrp-ban\u002Fenv.\nsudo systemctl enable --now frp-ban\nsudo systemctl status frp-ban\njournalctl -u frp-ban -f\n```\n\n### Client (systemd)\n\nInstall the client native package using the steps in\n[Release packaging and installation](docs\u002FRELEASING.md). Configure the server\naddress, token and TLS trust, edit the bundled rules, and grant the\n`frp-ban-client` account read access to monitored logs before starting the service.\n\n```bash\n# Arch Linux example (use linux-arm64 on Arch Linux ARM)\nsudo pacman -U .\u002Ffrp-ban-client-1.2.3-linux-x64.pkg.tar.zst\nsudo nano \u002Fetc\u002Ffrp-ban-client\u002Fappsettings.json\nsudo nano \u002Fetc\u002Ffrp-ban-client\u002Frules.d\u002F01-ssh-bruteforce.yaml\n# If monitored logs are owned by adm, grant access before starting:\n# sudo usermod -aG adm frp-ban-client\nsudo systemctl enable --now frp-ban-client\nsudo systemctl status frp-ban-client\njournalctl -u frp-ban-client -f\n```\n\n---\n\n## frps Configuration\n\nAdd to `frps.toml`:\n\n```toml\n[[httpPlugins]]\nname = \"frp-ban\"\naddr = \"127.0.0.1:9000\"\npath = \"\u002Fhandler\"\nops  = [\"Login\", \"NewUserConn\"]\n```\n\n---\n\n## Logging\n\n### Application Logs\n\n- **Path**: `PluginSettings.AppLogPath` (default: `\u002Fvar\u002Flog\u002Ffrp-ban\u002Ffrp-ban-.log`)\n- **Rotation**: Daily + 100MB file size limit\n- **Retention**: 30 days\n- **Format**: `YYYY-MM-DD HH:mm:ss.fff [LEVEL] Message`\n\n```bash\n# Real-time (systemd)\nsudo journalctl -u frp-ban -f\n\n# Real-time (log file)\nsudo tail -f \u002Fvar\u002Flog\u002Ffrp-ban\u002Ffrp-ban-$(date +%Y%m%d).log\n\n# Search errors\nsudo grep -i error \u002Fvar\u002Flog\u002Ffrp-ban\u002Ffrp-ban-*.log\n```\n\n---\n\n## Performance Characteristics\n\n| Metric | Value |\n|--------|-------|\n| Ban lookup (IsBanned) | ConcurrentDictionary lookup with canonical IP keys |\n| Max concurrent TLS connections | 100 (configurable) |\n| TLS connection rate | 10 new connections\u002Fminute per IP (configurable) |\n| Protocol message rate | 120 messages\u002Fminute per IP (configurable) |\n| Max protocol\u002FHTTP body | 64 KiB |\n| Frame buffers | Pooled on demand; no fixed 1 MiB receive buffer |\n| File monitoring | Event-driven, serialized reads with bounded partial-line state |\n| Regex matching | Cached per expression, 100 ms timeout |\n| Persistence | One writer, approximately 100 ms burst coalescing, atomic replace |\n\nThese describe implementation limits, not benchmark results. Production latency,\nthroughput, and memory usage depend on workload and require measurement.\n\n---\n\n## Troubleshooting\n\n### Client cannot connect\n\n1. Check TLS certificate:\n   ```bash\n   openssl s_client -connect frps.example.com:9443 -showcerts\n   ```\n\n2. Check token hash:\n   ```bash\n   echo -n \"your-token\" | sha256sum\n   ```\n\n3. View server logs:\n   ```bash\n   journalctl -u frp-ban -n 50\n   ```\n\n### High memory usage\n\n- Check ban count: inspect `\u002Fvar\u002Flib\u002Ffrp-ban\u002Fbans.json`\n- Review ban expiration settings\n- Monitor for ban list pollution\n\n### TLS connection failures\n\n- Ensure `ValidateServerCertificate` matches environment (disable only in development)\n- Check certificate expiration: `openssl x509 -in server-cert.pem -noout -dates`\n- Configure CA certificate path for self-signed certificates\n\n---\n\n## Protocol Specification\n\n### Binary Message Format\n\n```\n[Type: 1 byte][Length: 4 bytes big-endian][Body: variable]\n```\n\n**Message Types:**\n- `0x01` HELLO — Handshake (includes token hash)\n- `0x02` BAN_REQUEST — Ban request\n- `0x03` BAN_RESPONSE — Ban response\n- `0x04` PING — Health check\n- `0x05` PONG — Health check response\n- `0x06` ERROR — Error message\n\n**Body Format**: JSON (UTF-8)\n\n---\n\n## License\n\nMIT License\n\n---\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature\u002Famazing-feature`)\n3. Commit your changes (`git commit -m 'Add amazing feature'`)\n4. Push to the branch (`git push origin feature\u002Famazing-feature`)\n5. Open a Pull Request\n\n**Security vulnerabilities**: Please report privately to the maintainer.\n\n---\n\n## Roadmap\n\n- [ ] Systemd journal monitoring support (`type: journal`)\n- [ ] IP whitelist\u002Fexemption list\n- [ ] Prometheus metrics endpoint\n- [ ] Web UI for ban management\n- [ ] Docker\u002FPodman images\n- [ ] Kubernetes Helm chart\n- [ ] Full IPv6 testing\n- [ ] gRPC protocol option (alternative to binary TCP)\n\n---\n\nSee [CHANGELOG.md](CHANGELOG.md) for version history.\n","这是一个为 frp（Fast Reverse Proxy）服务端（frps）设计的高性能安全插件，用于实时拦截和阻止恶意 IP 地址建立隧道连接。它通过 TLS 加密的自定义 TCP 协议实现分布式 IP 封禁管理，支持基于日志正则匹配的自动封禁、内存级 O(1) 查询、连接与消息限流、自动过期等生产级特性。核心采用 C# 实现，集成于 frps 的 Login 和 NewUserConn 阶段，适用于需防范暴力登录、扫描攻击或滥用隧道的中小型内网穿透部署场景。",2,"2026-11-24 04:40:32","CREATED_QUERY"]