major refacto
docker / build (push) Failing after 1s

This commit is contained in:
tchivert committed 2026-07-17 22:01:07 +02:00
1 parent 0f666c102f
commit 8deeb69504
11 files changed
+551 -239

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
.git/
.gitignore
.gitattributes
*.md
LICENSE
docker-compose*.yml
Dockerfile
.gitea/
logs.db
data/
ssh-tarpit
rollout.sh
+26 -25
View File
@@ -2,39 +2,40 @@ name: build
on:
push:
branches:
- "main"
tags:
- '*'
jobs:
build:
runs-on: ubuntu-latest
container:
image: catthehacker/ubuntu:act-latest
steps:
- name: Setup go
uses: actions/setup-go@v4
with:
go-version: '>=1.20'
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0 # all history for all branches and tags
fetch-depth: 0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Linux build amd64
run: CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o bin/ssh-tarpit-linux-amd64
- name: Login to registry
uses: docker/login-action@v2
- name: Linux build arm64
run: CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o bin/ssh-tarpit-linux-arm64
- name: Darwin build amd64
run: CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o bin/ssh-tarpit-darwin-amd64
- name: Darwin build arm64
run: CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o bin/ssh-tarpit-darwin-arm64
- name: Upload binaries to release
uses: https://gitea.com/actions/release-action@main
with:
registry: git.rznet.fr
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push
uses: docker/build-push-action@v4
env:
ACTIONS_RUNTIME_TOKEN: '' # See https://gitea.com/gitea/act_runner/issues/119
with:
context: .
file: ./Dockerfile
platforms: |
linux/amd64
linux/arm64
push: true
tags: git.rznet.fr/${{ github.repository }}:latest
draft: false
prerelease: false
files: |-
bin/**
api_key: "${{ secrets.RELEASE_TOKEN }}"
+40
View File
@@ -0,0 +1,40 @@
name: docker
on:
push:
branches:
- "main"
jobs:
build:
runs-on: ubuntu-latest
container:
image: catthehacker/ubuntu:act-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0 # all history for all branches and tags
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to registry
uses: docker/login-action@v2
with:
registry: git.rznet.fr
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push
uses: docker/build-push-action@v4
env:
ACTIONS_RUNTIME_TOKEN: '' # See https://gitea.com/gitea/act_runner/issues/119
with:
context: .
file: ./Dockerfile
platforms: |
linux/amd64
linux/arm64
push: true
tags: git.rznet.fr/${{ github.repository }}:latest
-1
View File
@@ -1,4 +1,3 @@
data/
ssh-tarpit
logs.db
rollout.sh
+9 -13
View File
@@ -1,20 +1,16 @@
FROM golang AS build
FROM golang:alpine AS build
RUN apk add --no-cache gcc musl-dev
WORKDIR /app
COPY go.mod ./
COPY go.sum ./
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=1 GOOS=linux go build -ldflags='-extldflags=-static' -o ssh-tarpit .
COPY *.go ./
RUN CGO_ENABLED=1 GOOS=linux go build -o ssh-tarpit .
FROM debian:stable-slim
FROM alpine
RUN apk add --no-cache netcat-openbsd
RUN adduser -D -H -s /sbin/nologin tarpit
WORKDIR /app
COPY --from=build /app/ssh-tarpit ./
EXPOSE 2222
USER tarpit
ENTRYPOINT ["/app/ssh-tarpit"]
+53 -34
View File
@@ -1,56 +1,75 @@
# SSH-Tarpit
SSH honeypot capable of reading GeoIP databases and to output the informations in a SQLite or MySQL database. It can also be used as a [tarpit](https://nullprogram.com/blog/2019/03/22/) to block hackers for some time.
SSH honeypot capable of reading GeoIP databases and logging connection information to a SQLite or MySQL database. It can also be used as a [tarpit](https://nullprogram.com/blog/2019/03/22/) to hold hackers' connections open indefinitely.
## Configuration
All configuration is done via environment variables:
| Variable | Default | Description |
|---|---|---|
| `SSH_TARPIT_PORT` | `2222` | Port to listen on |
| `SSH_TARPIT_TARPIT` | `false` | Enable tarpit mode (`true`, `1`, `yes`, `on`) |
| `SSH_TARPIT_TARPIT_DELAY` | `1s` | Delay between tarpit bytes |
| `SSH_TARPIT_TARPIT_MAX_DURATION` | `0s` | Max tarpit duration (0 = unlimited) |
| `SSH_TARPIT_DB_PATH` | `./logs.db` | Path to SQLite database |
| `SSH_TARPIT_GEOIP_PATH` | | Path to GeoIP databases (GeoIP disabled if empty) |
| `SSH_TARPIT_MYSQL_USER` | | MySQL username (enables MySQL when set) |
| `SSH_TARPIT_MYSQL_PASS` | | MySQL password |
| `SSH_TARPIT_MYSQL_HOST` | `localhost` | MySQL host |
| `SSH_TARPIT_MYSQL_PORT` | `3306` | MySQL port |
| `SSH_TARPIT_MYSQL_DB` | `sshtarpit` | MySQL database name |
| `SSH_TARPIT_BANNER` | `SSH-2.0-OpenSSH_9.1p1 Debian-1` | Fake SSH banner |
| `SSH_TARPIT_MAX_CONNS` | `100` | Maximum concurrent connections |
| `SSH_TARPIT_SHUTDOWN_TIMEOUT` | `30s` | Max time to wait for active connections on shutdown |
## Deployment
### SQLite
Change user/pass and port if needed in the docker-compose.yml, create the database file, and then start the container:
Create the database file, then start the container:
```bash
git clone https://git.rznet.fr/razian/ssh-tarpit.git
cd ssh-tarpit
vim docker-compose.yml
touch logs.db
docker-compose up -d
git clone https://git.rznet.fr/razian/ssh-tarpit.git
cd ssh-tarpit
touch logs.db
docker compose up -d
```
### MySQL
Same as SQLite, but using the docker-compose-mysql.yml file:
Create a `.env` file with the required passwords:
```bash
git clone https://git.rznet.fr/razian/ssh-tarpit.git
cd ssh-tarpit
vim docker-compose-mysql.yml
docker-compose -f docker-compose-mysql.yml up -d
cat > .env <<EOF
MYSQL_ROOT_PASSWORD=your_db_root_password
MYSQL_PASS=your_db_root_password
EOF
```
Then start with the MySQL compose file:
```bash
git clone https://git.rznet.fr/razian/ssh-tarpit.git
cd ssh-tarpit
vim .env # set passwords
docker compose -f docker-compose-mysql.yml up -d
```
### GeoIP
I use [geoipupdate](https://github.com/maxmind/geoipupdate)
Use [geoipupdate](https://github.com/maxmind/geoipupdate) to download the GeoLite2 databases, then mount them and set `SSH_TARPIT_GEOIP_PATH`.
## Usage
## Database Schema
```sql
CREATE TABLE connections (
ip TEXT,
country TEXT,
city TEXT,
latitude REAL,
longitude REAL,
isp TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
Usage of ssh-tarpit:
--db string
Path to SQLite database (default "./logs.db")
--geoip string
Path to GeoIP databases
--mysql_db string
MySQL database (default "sshtarpit")
--mysql_host string
MySQL host (default "localhost")
--mysql_pass string
MySQL password
--mysql_port string
MySQL port (default "3306")
--mysql_user string
MySQL username
--port string
Port to listen on (default "2222")
--tarpit
Tarpit connections (default "false")
```
+26
View File
@@ -0,0 +1,26 @@
services:
ssh-tarpit:
image: git.rznet.fr/razian/ssh-tarpit
container_name: ssh-tarpit
ports:
- '2222:2222'
restart: always
volumes:
- ./logs.db:/app/logs.db
- ./data/geoip:/app/GeoIP
environment:
- SSH_TARPIT_PORT=2222
- SSH_TARPIT_TARPIT=false
- SSH_TARPIT_GEOIP_PATH=/app/GeoIP
geoipupdate:
image: ghcr.io/maxmind/geoipupdate
container_name: ssh-tarpit-geoipupdate
restart: unless-stopped
volumes:
- ./data/geoip:/usr/share/GeoIP
environment:
GEOIPUPDATE_ACCOUNT_ID: ""
GEOIPUPDATE_LICENSE_KEY: ""
GEOIPUPDATE_EDITION_IDS: "GeoLite2-City GeoLite2-ASN"
GEOIPUPDATE_FREQUENCY: "12"
+12 -13
View File
@@ -1,4 +1,3 @@
version: '3.3'
services:
ssh-tarpit:
image: git.rznet.fr/razian/ssh-tarpit
@@ -8,21 +7,21 @@ services:
restart: always
# volumes:
# - /var/lib/GeoIP:/app/GeoIP
command:
- --port=2222
- --tarpit=false
- --mysql_user=root
- --mysql_pass=<CHANGETHIS>
- --mysql_host=db
- --mysql_port=3306
- --mysql_db=sshtarpit
# - --geoip=/app/GeoIP
environment:
- SSH_TARPIT_PORT=2222
- SSH_TARPIT_TARPIT=false
- SSH_TARPIT_MYSQL_USER=${MYSQL_USER:-root}
- SSH_TARPIT_MYSQL_PASS=${MYSQL_PASS}
- SSH_TARPIT_MYSQL_HOST=db
- SSH_TARPIT_MYSQL_PORT=3306
- SSH_TARPIT_MYSQL_DB=sshtarpit
# - SSH_TARPIT_GEOIP_PATH=/app/GeoIP
db:
image: mariadb
image: mariadb:11
restart: always
environment:
MARIADB_ROOT_PASSWORD: <CHANGETHIS>
MARIADB_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MARIADB_DATABASE: sshtarpit
volumes:
- ./data:/var/lib/mysql
- ./data/mysql:/var/lib/mysql
+4 -5
View File
@@ -1,4 +1,3 @@
version: '3.3'
services:
ssh-tarpit:
image: git.rznet.fr/razian/ssh-tarpit
@@ -9,7 +8,7 @@ services:
volumes:
- ./logs.db:/app/logs.db
# - /var/lib/GeoIP:/app/GeoIP
command:
- --port=2222
- --tarpit=false
# - --geoip=/app/GeoIP
environment:
- SSH_TARPIT_PORT=2222
- SSH_TARPIT_TARPIT=false
# - SSH_TARPIT_GEOIP_PATH=/app/GeoIP
+1 -1
View File
@@ -1,6 +1,6 @@
module ssh-tarpit
go 1.19
go 1.26
require (
github.com/go-sql-driver/mysql v1.7.0
+368 -147
View File
@@ -1,182 +1,403 @@
package main
import (
"context"
"crypto/rand"
"database/sql"
"flag"
"fmt"
"log"
"net"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
// MySQL driver registration
_ "github.com/go-sql-driver/mysql"
// SQLite3 driver registration (requires CGO)
_ "github.com/mattn/go-sqlite3"
"github.com/oschwald/geoip2-golang"
)
var (
tarpit = flag.Bool("tarpit", false, "Tarpit connections")
db = flag.String("db", "./logs.db", "Path to SQLite database")
geoip = flag.String("geoip", "", "Path to GeoIP databases")
port = flag.String("port", "2222", "Port to listen on")
mysql_user = flag.String("mysql_user", "", "MySQL username")
mysql_pass = flag.String("mysql_pass", "", "MySQL password")
mysql_host = flag.String("mysql_host", "localhost", "MySQL host")
mysql_port = flag.String("mysql_port", "3306", "MySQL port")
mysql_db = flag.String("mysql_db", "sshtarpit", "MySQL database")
)
// Config holds all configuration sourced from environment variables.
type Config struct {
Port int
Tarpit bool
TarpitDelay time.Duration
TarpitMaxDur time.Duration // 0 = unlimited
DBPath string
GeoIPPath string
MySQLUser string
MySQLPass string
MySQLHost string
MySQLPort string
MySQLDB string
Banner string
MaxConns int
ShutdownTimeout time.Duration
}
const (
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
delay = 1
)
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func main() {
flag.Parse()
fmt.Println("Listening on port", *port)
ln, err := net.Listen("tcp", ":"+*port)
if err != nil {
fmt.Println(err)
os.Exit(1)
func loadConfig() Config {
return Config{
Port: getEnvInt("SSH_TARPIT_PORT", 2222),
Tarpit: getEnvBool("SSH_TARPIT_TARPIT", false),
TarpitDelay: getEnvDuration("SSH_TARPIT_TARPIT_DELAY", 1*time.Second),
TarpitMaxDur: getEnvDuration("SSH_TARPIT_TARPIT_MAX_DURATION", 0),
DBPath: getEnv("SSH_TARPIT_DB_PATH", "./logs.db"),
GeoIPPath: getEnv("SSH_TARPIT_GEOIP_PATH", ""),
MySQLUser: getEnv("SSH_TARPIT_MYSQL_USER", ""),
MySQLPass: getEnv("SSH_TARPIT_MYSQL_PASS", ""),
MySQLHost: getEnv("SSH_TARPIT_MYSQL_HOST", "localhost"),
MySQLPort: getEnv("SSH_TARPIT_MYSQL_PORT", "3306"),
MySQLDB: getEnv("SSH_TARPIT_MYSQL_DB", "sshtarpit"),
Banner: getEnv("SSH_TARPIT_BANNER", "SSH-2.0-OpenSSH_9.1p1 Debian-1"),
MaxConns: getEnvInt("SSH_TARPIT_MAX_CONNS", 100),
ShutdownTimeout: getEnvDuration("SSH_TARPIT_SHUTDOWN_TIMEOUT", 30*time.Second),
}
}
// Env helpers
func getEnv(key, defaultVal string) string {
if v := os.Getenv(key); v != "" {
return v
}
return defaultVal
}
func getEnvBool(key string, defaultVal bool) bool {
v := os.Getenv(key)
if v == "" {
return defaultVal
}
switch strings.ToLower(v) {
case "true", "1", "yes", "on":
return true
default:
return false
}
}
func getEnvInt(key string, defaultVal int) int {
v := os.Getenv(key)
if v == "" {
return defaultVal
}
i, err := strconv.Atoi(v)
if err != nil {
log.Printf("Invalid value for %s=%q, using default %d: %v", key, v, defaultVal, err)
return defaultVal
}
return i
}
func getEnvDuration(key string, defaultVal time.Duration) time.Duration {
v := os.Getenv(key)
if v == "" {
return defaultVal
}
d, err := time.ParseDuration(v)
if err != nil {
log.Printf("Invalid duration for %s=%q, using default %s: %v", key, v, defaultVal, err)
return defaultVal
}
return d
}
// ConnectionLogger persists connection records.
type ConnectionLogger interface {
LogConnection(ip, country, city string, latitude, longitude float64, isp string) error
Close() error
}
// dbLogger implements ConnectionLogger with a *sql.DB connection pool.
type dbLogger struct {
db *sql.DB
}
func (l *dbLogger) LogConnection(ip, country, city string, latitude, longitude float64, isp string) error {
_, err := l.db.Exec(
"INSERT INTO connections (ip, country, city, latitude, longitude, isp) VALUES (?, ?, ?, ?, ?, ?)",
ip, country, city, latitude, longitude, isp,
)
return err
}
func (l *dbLogger) Close() error {
return l.db.Close()
}
func newLogger(cfg Config) (ConnectionLogger, error) {
var driverName, dsn string
if cfg.MySQLUser != "" {
driverName = "mysql"
dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true",
cfg.MySQLUser, cfg.MySQLPass, cfg.MySQLHost, cfg.MySQLPort, cfg.MySQLDB)
} else {
driverName = "sqlite3"
dsn = cfg.DBPath
}
db, err := sql.Open(driverName, dsn)
if err != nil {
return nil, fmt.Errorf("sql.Open: %w", err)
}
// Connection pool tuning
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)
// SQLite-specific pragmas for better concurrent write performance
if driverName == "sqlite3" {
if _, err := db.Exec("PRAGMA journal_mode=WAL"); err != nil {
log.Printf("Warning: could not set WAL mode: %v", err)
}
if _, err := db.Exec("PRAGMA busy_timeout=5000"); err != nil {
log.Printf("Warning: could not set busy_timeout: %v", err)
}
}
// Create table once at startup
createSQL := `CREATE TABLE IF NOT EXISTS connections (
ip TEXT,
country TEXT,
city TEXT,
latitude REAL,
longitude REAL,
isp TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`
if _, err := db.Exec(createSQL); err != nil {
db.Close()
return nil, fmt.Errorf("create table: %w", err)
}
log.Printf("Database ready (driver=%s)", driverName)
return &dbLogger{db: db}, nil
}
// GeoIP helpers
type geoipReaders struct {
city *geoip2.Reader
asn *geoip2.Reader
}
func newGeoIPReaders(geoipPath string) (*geoipReaders, error) {
city, err := geoip2.Open(geoipPath + "/GeoLite2-City.mmdb")
if err != nil {
return nil, fmt.Errorf("open City DB: %w", err)
}
asn, err := geoip2.Open(geoipPath + "/GeoLite2-ASN.mmdb")
if err != nil {
city.Close()
return nil, fmt.Errorf("open ASN DB: %w", err)
}
return &geoipReaders{city: city, asn: asn}, nil
}
func (g *geoipReaders) Close() {
if g.city != nil {
g.city.Close()
}
if g.asn != nil {
g.asn.Close()
}
}
func (g *geoipReaders) lookup(ip string) (country, city string, latitude, longitude float64, isp string, err error) {
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
return "", "", 0, 0, "", fmt.Errorf("invalid IP: %s", ip)
}
record, err := g.city.City(parsedIP)
if err != nil {
return "", "", 0, 0, "", fmt.Errorf("city lookup: %w", err)
}
latitude, longitude = record.Location.Latitude, record.Location.Longitude
country = record.Country.Names["en"]
city = record.City.Names["en"]
asnRecord, err := g.asn.ASN(parsedIP)
if err != nil {
return "", "", 0, 0, "", fmt.Errorf("ASN lookup: %w", err)
}
isp = asnRecord.AutonomousSystemOrganization
return country, city, latitude, longitude, isp, nil
}
// Main
func main() {
log.SetFlags(log.LstdFlags | log.Lmsgprefix)
log.SetPrefix("[ssh-tarpit] ")
cfg := loadConfig()
// Initialise database connection pool once
logger, err := newLogger(cfg)
if err != nil {
log.Fatalf("Failed to initialise database: %v", err)
}
defer logger.Close()
// Initialise GeoIP readers once (if configured)
var geoReaders *geoipReaders
if cfg.GeoIPPath != "" {
geoReaders, err = newGeoIPReaders(cfg.GeoIPPath)
if err != nil {
log.Printf("Warning: GeoIP initialisation failed, falling back to IP-only logging: %v", err)
geoReaders = nil
} else {
defer geoReaders.Close()
}
}
addr := fmt.Sprintf(":%d", cfg.Port)
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("Failed to listen on %s: %v", addr, err)
}
log.Printf("Listening on %s", addr)
// Signal handling for graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigCh
log.Printf("Received %v, shutting down...", sig)
cancel()
ln.Close() // unblock Accept
}()
// Semaphore to limit concurrent connections
sem := make(chan struct{}, cfg.MaxConns)
var wg sync.WaitGroup
acceptLoop:
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
header := []byte("SSH-2.0-OpenSSH_9.1p1 Debian-1\r")
src := conn.RemoteAddr().String()
ip := src[:len(src)-6]
if strings.Contains(ip, "[") {
ip = ip[1 : len(ip)-1]
}
if *geoip != "" {
registerGeoip(ip)
} else {
registerConnection(ip)
}
if !*tarpit {
conn.Write(header)
time.Sleep(time.Duration(2) * time.Second)
} else {
for {
b := make([]byte, 1)
_, err := rand.Read(b)
if err != nil {
fmt.Println(err)
return
select {
case <-ctx.Done():
break acceptLoop
default:
log.Printf("Accept error: %v", err)
continue
}
conn.Write([]byte{charset[int(b[0])%len(charset)]})
time.Sleep(time.Duration(delay) * time.Second)
}
select {
case sem <- struct{}{}:
wg.Add(1)
go func() {
defer wg.Done()
defer func() { <-sem }()
handleConnection(ctx, conn, logger, geoReaders, cfg)
}()
default:
log.Printf("Connection limit reached (%d), rejecting %s", cfg.MaxConns, conn.RemoteAddr())
conn.Close()
}
}
// Wait for active connections to drain
log.Println("Waiting for active connections to finish...")
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
log.Println("All connections finished cleanly")
case <-time.After(cfg.ShutdownTimeout):
log.Printf("Timed out after %s waiting for connections", cfg.ShutdownTimeout)
}
}
func registerGeoip(ip string) {
location, err := geoip2.Open(*geoip + "/GeoLite2-City.mmdb")
if err != nil {
fmt.Println(err)
registerConnection(ip)
return
}
defer location.Close()
city, err := location.City(net.ParseIP(ip))
if err != nil {
fmt.Println(err)
registerConnection(ip)
return
}
latitude, longitude := city.Location.Latitude, city.Location.Longitude
if latitude == 0 && longitude == 0 {
registerConnection(ip)
return
}
ispdb, err := geoip2.Open(*geoip + "/GeoLite2-ASN.mmdb")
if err != nil {
fmt.Println(err)
registerConnection(ip)
return
}
defer ispdb.Close()
isp, err := ispdb.ASN(net.ParseIP(ip))
if err != nil {
fmt.Println(err)
registerConnection(ip)
return
}
if *mysql_user != "" {
_, err = mysqlInsert(ip, city.Country.Names["en"], city.City.Names["en"], latitude, longitude, isp.AutonomousSystemOrganization)
} else {
_, err = sqliteInsert(ip, city.Country.Names["en"], city.City.Names["en"], latitude, longitude, isp.AutonomousSystemOrganization)
}
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Connection from", ip, "(", city.Country.Names["en"], city.City.Names["en"], isp.AutonomousSystemOrganization, ")")
}
// Connection handler
func handleConnection(ctx context.Context, conn net.Conn, logger ConnectionLogger, geoReaders *geoipReaders, cfg Config) {
defer conn.Close()
func registerConnection(ip string) {
if *mysql_user != "" {
_, err := mysqlInsert(ip, "", "", 0, 0, "")
// Parse remote IP properly
remoteAddr := conn.RemoteAddr().String()
ip, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
log.Printf("Failed to parse remote address %q: %v", remoteAddr, err)
return
}
// Set a deadline for GeoIP / DB operations
conn.SetDeadline(time.Now().Add(30 * time.Second))
// Look up GeoIP data if available, otherwise just log the IP
country, city, isp := "", "", ""
var latitude, longitude float64
if geoReaders != nil {
country, city, latitude, longitude, isp, err = geoReaders.lookup(ip)
if err != nil {
fmt.Println(err)
log.Printf("GeoIP lookup failed for %s: %v", ip, err)
// Fall back to IP-only logging
country, city, latitude, longitude, isp = "", "", 0, 0, ""
}
}
if err := logger.LogConnection(ip, country, city, latitude, longitude, isp); err != nil {
log.Printf("Failed to log connection from %s: %v", ip, err)
}
if geoReaders != nil {
log.Printf("Connection from %s (%s, %s, %s)", ip, country, city, isp)
} else {
log.Printf("Connection from %s", ip)
}
// Reset deadline for the remainder of the connection
conn.SetDeadline(time.Time{})
if !cfg.Tarpit {
// Send banner and hold briefly
conn.Write([]byte(cfg.Banner + "\r\n"))
select {
case <-time.After(2 * time.Second):
case <-ctx.Done():
}
return
}
// Tarpit mode: drip random bytes periodically
tarpitCtx, tarpitCancel := context.WithCancel(ctx)
defer tarpitCancel()
if cfg.TarpitMaxDur > 0 {
tarpitCtx, tarpitCancel = context.WithTimeout(ctx, cfg.TarpitMaxDur)
defer tarpitCancel()
}
b := make([]byte, 1)
for {
select {
case <-tarpitCtx.Done():
return
default:
}
if _, err := rand.Read(b); err != nil {
log.Printf("rand.Read error: %v", err)
return
}
} else {
_, err := sqliteInsert(ip, "", "", 0, 0, "")
if err != nil {
fmt.Println(err)
if _, err := conn.Write([]byte{charset[int(b[0])%len(charset)]}); err != nil {
return
}
time.Sleep(cfg.TarpitDelay)
}
fmt.Println("Connection from", ip)
}
func mysqlInsert(ip, country, city string, latitude, longitude float64, isp string) (int64, error) {
sqldb, err := sql.Open("mysql", *mysql_user+":"+*mysql_pass+"@tcp("+*mysql_host+":"+*mysql_port+")/"+*mysql_db)
if err != nil {
fmt.Println(err)
return 0, err
}
defer sqldb.Close()
_, err = sqldb.Exec("CREATE TABLE IF NOT EXISTS connections (ip TEXT, country TEXT, city TEXT, latitude REAL, longitude REAL, isp TEXT, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
if err != nil {
fmt.Println(err)
return 0, err
}
res, err := sqldb.Exec("INSERT INTO connections (ip, country, city, latitude, longitude, isp, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)", ip, country, city, latitude, longitude, isp, time.Now().Format("2006-01-02 15:04:05"))
if err != nil {
fmt.Println(err)
return 0, err
}
return res.LastInsertId()
}
func sqliteInsert(ip, country, city string, latitude, longitude float64, isp string) (int64, error) {
sqldb, err := sql.Open("sqlite3", *db)
if err != nil {
fmt.Println(err)
return 0, err
}
defer sqldb.Close()
_, err = sqldb.Exec("CREATE TABLE IF NOT EXISTS connections (ip TEXT, country TEXT, city TEXT, latitude REAL, longitude REAL, isp TEXT, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP)")
if err != nil {
fmt.Println(err)
return 0, err
}
res, err := sqldb.Exec("INSERT INTO connections (ip, country, city, latitude, longitude, isp, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?)", ip, country, city, latitude, longitude, isp, time.Now().Format("2006-01-02 15:04:05"))
if err != nil {
fmt.Println(err)
return 0, err
}
return res.RowsAffected()
}