4 files changed
+362
-22
No files matched your search
@@ -23,6 +23,9 @@ All configuration is done via environment variables:
|
||||
| `SSH_TARPIT_MAX_CONNS` | `100` | Maximum concurrent connections |
|
||||
| `SSH_TARPIT_SHUTDOWN_TIMEOUT` | `30s` | Max time to wait for active connections on shutdown |
|
||||
| `SSH_TARPIT_PROXY_PROTOCOL` | `false` | Enable PROXY protocol v1/v2 support (`true`, `1`, `yes`, `on`) |
|
||||
| `SSH_TARPIT_AUTH` | `false` | Enable fake SSH authentication + command logging (`true`, `1`, `yes`, `on`). Cannot be used with tarpit mode. |
|
||||
| `SSH_TARPIT_AUTH_CREDENTIALS` | `admin:admin,root:root,...` | Comma-separated `user:pass` pairs that bots can "crack" to reach the fake shell |
|
||||
| `SSH_TARPIT_AUTH_IDLE_TIMEOUT` | `5m` | Max idle time for authenticated SSH sessions |
|
||||
|
||||
## Deployment
|
||||
|
||||
@@ -62,6 +65,7 @@ Use [geoipupdate](https://github.com/maxmind/geoipupdate) to download the GeoLit
|
||||
|
||||
## Database Schema
|
||||
|
||||
### connections
|
||||
```sql
|
||||
CREATE TABLE connections (
|
||||
ip TEXT,
|
||||
@@ -73,3 +77,36 @@ CREATE TABLE connections (
|
||||
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
```
|
||||
|
||||
### auth_attempts
|
||||
```sql
|
||||
CREATE TABLE auth_attempts (
|
||||
ip TEXT NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
password TEXT,
|
||||
public_key_fingerprint TEXT,
|
||||
success INTEGER DEFAULT 0,
|
||||
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
```
|
||||
|
||||
### commands
|
||||
```sql
|
||||
CREATE TABLE commands (
|
||||
ip TEXT NOT NULL,
|
||||
command TEXT NOT NULL,
|
||||
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
```
|
||||
|
||||
## Auth Mode
|
||||
|
||||
When `SSH_TARPIT_AUTH=true` (and tarpit is disabled), the honeypot runs a fake SSH server:
|
||||
|
||||
1. Performs real SSH key exchange using `golang.org/x/crypto/ssh`
|
||||
2. Logs every authentication attempt (username, password, public key fingerprint) to the `auth_attempts` table
|
||||
3. Only grants access if the credentials match one of the `SSH_TARPIT_AUTH_CREDENTIALS` pairs
|
||||
4. After successful auth, presents a fake `root@localhost:~# ` shell prompt
|
||||
5. Every command typed is logged to the `commands` table
|
||||
|
||||
Default credentials include: `admin:admin`, `root:root`, `root:123456`, `guest:guest`, and others. Bots brute-forcing common passwords will eventually hit one and start issuing commands — all of which get logged.
|
||||
@@ -5,6 +5,8 @@ go 1.26
|
||||
require (
|
||||
github.com/go-sql-driver/mysql v1.7.0
|
||||
github.com/oschwald/geoip2-golang v1.8.0
|
||||
github.com/pires/go-proxyproto v0.15.0
|
||||
golang.org/x/crypto v0.24.0
|
||||
modernc.org/sqlite v1.29.10
|
||||
)
|
||||
|
||||
@@ -15,9 +17,8 @@ require (
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/oschwald/maxminddb-golang v1.10.0 // indirect
|
||||
github.com/pires/go-proxyproto v0.15.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/sys v0.19.0 // indirect
|
||||
golang.org/x/sys v0.21.0 // indirect
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
|
||||
modernc.org/libc v1.49.3 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
|
||||
@@ -26,11 +26,15 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI=
|
||||
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
|
||||
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
|
||||
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
|
||||
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.21.0 h1:WVXCp+/EBEHOj53Rvu+7KiT/iElMrO8ACK16SMZ3jaA=
|
||||
golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0=
|
||||
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
|
||||
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
+316
-18
@@ -1,9 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
@@ -21,6 +24,7 @@ import (
|
||||
_ "modernc.org/sqlite"
|
||||
"github.com/oschwald/geoip2-golang"
|
||||
"github.com/pires/go-proxyproto"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// Config holds all configuration sourced from environment variables.
|
||||
@@ -40,11 +44,17 @@ type Config struct {
|
||||
MaxConns int
|
||||
ShutdownTimeout time.Duration
|
||||
ProxyProtocol bool
|
||||
Auth bool
|
||||
AuthCredentials map[string]string // username -> password
|
||||
AuthIdleTimeout time.Duration
|
||||
}
|
||||
|
||||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
|
||||
func loadConfig() Config {
|
||||
creds := parseCredentials(getEnv("SSH_TARPIT_AUTH_CREDENTIALS",
|
||||
"admin:admin,root:root,root:123456,admin:123456,root:password,admin:password,guest:guest,test:test,user:user,ubuntu:ubuntu,root:toor,pi:raspberry"))
|
||||
|
||||
return Config{
|
||||
Port: getEnvInt("SSH_TARPIT_PORT", 2222),
|
||||
Tarpit: getEnvBool("SSH_TARPIT_TARPIT", false),
|
||||
@@ -61,9 +71,39 @@ func loadConfig() Config {
|
||||
MaxConns: getEnvInt("SSH_TARPIT_MAX_CONNS", 100),
|
||||
ShutdownTimeout: getEnvDuration("SSH_TARPIT_SHUTDOWN_TIMEOUT", 30*time.Second),
|
||||
ProxyProtocol: getEnvBool("SSH_TARPIT_PROXY_PROTOCOL", false),
|
||||
Auth: getEnvBool("SSH_TARPIT_AUTH", false),
|
||||
AuthCredentials: creds,
|
||||
AuthIdleTimeout: getEnvDuration("SSH_TARPIT_AUTH_IDLE_TIMEOUT", 5*time.Minute),
|
||||
}
|
||||
}
|
||||
|
||||
// parseCredentials parses a comma-separated list of username:password pairs.
|
||||
func parseCredentials(raw string) map[string]string {
|
||||
m := make(map[string]string)
|
||||
if raw == "" {
|
||||
return m
|
||||
}
|
||||
for _, pair := range strings.Split(raw, ",") {
|
||||
pair = strings.TrimSpace(pair)
|
||||
if pair == "" {
|
||||
continue
|
||||
}
|
||||
parts := strings.SplitN(pair, ":", 2)
|
||||
if len(parts) != 2 {
|
||||
log.Printf("Warning: invalid credential pair %q (expected user:pass), skipping", pair)
|
||||
continue
|
||||
}
|
||||
user := strings.TrimSpace(parts[0])
|
||||
pass := strings.TrimSpace(parts[1])
|
||||
if user == "" {
|
||||
log.Printf("Warning: empty username in credential pair %q, skipping", pair)
|
||||
continue
|
||||
}
|
||||
m[user] = pass
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// Env helpers
|
||||
func getEnv(key, defaultVal string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
@@ -111,9 +151,11 @@ func getEnvDuration(key string, defaultVal time.Duration) time.Duration {
|
||||
return d
|
||||
}
|
||||
|
||||
// ConnectionLogger persists connection records.
|
||||
// ConnectionLogger persists connection, auth, and command records.
|
||||
type ConnectionLogger interface {
|
||||
LogConnection(ip, country, city string, latitude, longitude float64, isp string) error
|
||||
LogAuthAttempt(ip, username, password, publicKeyFingerprint string, success bool) error
|
||||
LogCommand(ip, command string) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
@@ -130,6 +172,22 @@ func (l *dbLogger) LogConnection(ip, country, city string, latitude, longitude f
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *dbLogger) LogAuthAttempt(ip, username, password, publicKeyFingerprint string, success bool) error {
|
||||
_, err := l.db.Exec(
|
||||
"INSERT INTO auth_attempts (ip, username, password, public_key_fingerprint, success) VALUES (?, ?, ?, ?, ?)",
|
||||
ip, username, password, publicKeyFingerprint, success,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *dbLogger) LogCommand(ip, command string) error {
|
||||
_, err := l.db.Exec(
|
||||
"INSERT INTO commands (ip, command) VALUES (?, ?)",
|
||||
ip, command,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *dbLogger) Close() error {
|
||||
return l.db.Close()
|
||||
}
|
||||
@@ -163,19 +221,37 @@ func newLogger(cfg Config) (ConnectionLogger, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
// Create tables once at startup
|
||||
tables := []string{
|
||||
`CREATE TABLE IF NOT EXISTS connections (
|
||||
ip TEXT,
|
||||
country TEXT,
|
||||
city TEXT,
|
||||
latitude REAL,
|
||||
longitude REAL,
|
||||
isp TEXT,
|
||||
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS auth_attempts (
|
||||
ip TEXT NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
password TEXT,
|
||||
public_key_fingerprint TEXT,
|
||||
success INTEGER DEFAULT 0,
|
||||
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS commands (
|
||||
ip TEXT NOT NULL,
|
||||
command TEXT NOT NULL,
|
||||
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)`,
|
||||
}
|
||||
|
||||
for _, ddl := range tables {
|
||||
if _, err := db.Exec(ddl); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("create table: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("Database ready (driver=%s)", driverName)
|
||||
@@ -233,6 +309,22 @@ func (g *geoipReaders) lookup(ip string) (country, city string, latitude, longit
|
||||
return country, city, latitude, longitude, isp, nil
|
||||
}
|
||||
|
||||
// buildHostKey generates an ephemeral Ed25519 host key for the fake SSH server.
|
||||
func buildHostKey() (ssh.Signer, error) {
|
||||
_, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate host key: %w", err)
|
||||
}
|
||||
signer, err := ssh.NewSignerFromSigner(priv)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create signer: %w", err)
|
||||
}
|
||||
return signer, nil
|
||||
}
|
||||
|
||||
// fakeShellPrompt is the prompt shown to authenticated clients.
|
||||
const fakeShellPrompt = "root@localhost:~# "
|
||||
|
||||
// Main
|
||||
func main() {
|
||||
log.SetFlags(log.LstdFlags | log.Lmsgprefix)
|
||||
@@ -240,6 +332,14 @@ func main() {
|
||||
|
||||
cfg := loadConfig()
|
||||
|
||||
if cfg.Auth && cfg.Tarpit {
|
||||
log.Fatalf("SSH_TARPIT_AUTH and SSH_TARPIT_TARPIT cannot both be enabled")
|
||||
}
|
||||
|
||||
if cfg.Auth && len(cfg.AuthCredentials) == 0 {
|
||||
log.Fatalf("SSH_TARPIT_AUTH is enabled but no credentials configured (use SSH_TARPIT_AUTH_CREDENTIALS)")
|
||||
}
|
||||
|
||||
// Initialise database connection pool once
|
||||
logger, err := newLogger(cfg)
|
||||
if err != nil {
|
||||
@@ -259,6 +359,16 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// Generate SSH host key if auth mode is enabled
|
||||
var hostKey ssh.Signer
|
||||
if cfg.Auth {
|
||||
hostKey, err = buildHostKey()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to generate host key: %v", err)
|
||||
}
|
||||
log.Printf("Auth mode enabled with %d credential pair(s)", len(cfg.AuthCredentials))
|
||||
}
|
||||
|
||||
addr := fmt.Sprintf(":%d", cfg.Port)
|
||||
rawLn, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
@@ -268,7 +378,7 @@ func main() {
|
||||
var ln net.Listener
|
||||
if cfg.ProxyProtocol {
|
||||
ln = &proxyproto.Listener{
|
||||
Listener: rawLn,
|
||||
Listener: rawLn,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
log.Printf("Listening on %s (PROXY protocol enabled)", addr)
|
||||
@@ -294,7 +404,7 @@ func main() {
|
||||
sem := make(chan struct{}, cfg.MaxConns)
|
||||
var wg sync.WaitGroup
|
||||
|
||||
acceptLoop:
|
||||
acceptLoop:
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
@@ -313,7 +423,7 @@ func main() {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
handleConnection(ctx, conn, logger, geoReaders, cfg)
|
||||
handleConnection(ctx, conn, logger, geoReaders, cfg, hostKey)
|
||||
}()
|
||||
default:
|
||||
log.Printf("Connection limit reached (%d), rejecting %s", cfg.MaxConns, conn.RemoteAddr())
|
||||
@@ -337,7 +447,7 @@ func main() {
|
||||
}
|
||||
|
||||
// Connection handler
|
||||
func handleConnection(ctx context.Context, conn net.Conn, logger ConnectionLogger, geoReaders *geoipReaders, cfg Config) {
|
||||
func handleConnection(ctx context.Context, conn net.Conn, logger ConnectionLogger, geoReaders *geoipReaders, cfg Config, hostKey ssh.Signer) {
|
||||
defer conn.Close()
|
||||
|
||||
// Parse remote IP properly
|
||||
@@ -377,6 +487,12 @@ func handleConnection(ctx context.Context, conn net.Conn, logger ConnectionLogge
|
||||
// Reset deadline for the remainder of the connection
|
||||
conn.SetDeadline(time.Time{})
|
||||
|
||||
// Auth mode (non-tarpit): run a fake SSH server
|
||||
if cfg.Auth && !cfg.Tarpit {
|
||||
handleAuthMode(ctx, conn, ip, logger, cfg, hostKey)
|
||||
return
|
||||
}
|
||||
|
||||
if !cfg.Tarpit {
|
||||
// Send banner and hold briefly
|
||||
conn.Write([]byte(cfg.Banner + "\r\n"))
|
||||
@@ -412,3 +528,185 @@ func handleConnection(ctx context.Context, conn net.Conn, logger ConnectionLogge
|
||||
time.Sleep(cfg.TarpitDelay)
|
||||
}
|
||||
}
|
||||
|
||||
// handleAuthMode runs a fake SSH server that logs auth attempts and commands.
|
||||
func handleAuthMode(ctx context.Context, conn net.Conn, ip string, logger ConnectionLogger, cfg Config, hostKey ssh.Signer) {
|
||||
sshConfig := &ssh.ServerConfig{
|
||||
ServerVersion: cfg.Banner,
|
||||
MaxAuthTries: 6,
|
||||
AuthLogCallback: nil,
|
||||
PasswordCallback: makePasswordCallback(ip, logger, cfg.AuthCredentials),
|
||||
PublicKeyCallback: makePublicKeyCallback(ip, logger),
|
||||
}
|
||||
sshConfig.AddHostKey(hostKey)
|
||||
|
||||
// Set a deadline for the SSH handshake
|
||||
conn.SetDeadline(time.Now().Add(30 * time.Second))
|
||||
|
||||
sshConn, chans, reqs, err := ssh.NewServerConn(conn, sshConfig)
|
||||
if err != nil {
|
||||
// Handshake failed — client didn't complete SSH setup, which is fine
|
||||
log.Printf("SSH handshake failed from %s: %v", ip, err)
|
||||
return
|
||||
}
|
||||
defer sshConn.Close()
|
||||
|
||||
// Reset deadline; individual sessions will set their own idle timeouts
|
||||
conn.SetDeadline(time.Time{})
|
||||
|
||||
// Discard global requests (keepalives, etc.)
|
||||
go ssh.DiscardRequests(reqs)
|
||||
|
||||
log.Printf("SSH authenticated from %s (user=%s)", ip, sshConn.User())
|
||||
|
||||
// Handle channels (sessions)
|
||||
for newChannel := range chans {
|
||||
if newChannel.ChannelType() != "session" {
|
||||
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
|
||||
continue
|
||||
}
|
||||
|
||||
channel, requests, err := newChannel.Accept()
|
||||
if err != nil {
|
||||
log.Printf("Failed to accept channel from %s: %v", ip, err)
|
||||
continue
|
||||
}
|
||||
|
||||
go handleSession(ctx, channel, requests, ip, logger, cfg.AuthIdleTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
// makePasswordCallback returns a PasswordCallback that logs attempts and checks
|
||||
// against the configured easy credentials.
|
||||
func makePasswordCallback(ip string, logger ConnectionLogger, creds map[string]string) func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
|
||||
return func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
|
||||
username := conn.User()
|
||||
pass := string(password)
|
||||
|
||||
expectedPass, exists := creds[username]
|
||||
success := exists && pass == expectedPass
|
||||
|
||||
if err := logger.LogAuthAttempt(ip, username, pass, "", success); err != nil {
|
||||
log.Printf("Failed to log auth attempt: %v", err)
|
||||
}
|
||||
|
||||
if success {
|
||||
log.Printf("Successful password auth from %s: user=%s", ip, username)
|
||||
return &ssh.Permissions{}, nil
|
||||
}
|
||||
log.Printf("Failed password auth from %s: user=%s password=%q", ip, username, pass)
|
||||
return nil, fmt.Errorf("permission denied")
|
||||
}
|
||||
}
|
||||
|
||||
// makePublicKeyCallback returns a PublicKeyCallback that logs attempts.
|
||||
// Public key auth always fails (credentials only support password auth).
|
||||
func makePublicKeyCallback(ip string, logger ConnectionLogger) func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
|
||||
return func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
|
||||
username := conn.User()
|
||||
fingerprint := ssh.FingerprintSHA256(key)
|
||||
|
||||
if err := logger.LogAuthAttempt(ip, username, "", fingerprint, false); err != nil {
|
||||
log.Printf("Failed to log auth attempt: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("Failed public key auth from %s: user=%s fingerprint=%s", ip, username, fingerprint)
|
||||
return nil, fmt.Errorf("permission denied")
|
||||
}
|
||||
}
|
||||
|
||||
// handleSession manages a single SSH session (shell or exec).
|
||||
func handleSession(ctx context.Context, channel ssh.Channel, requests <-chan *ssh.Request, ip string, logger ConnectionLogger, idleTimeout time.Duration) {
|
||||
defer channel.Close()
|
||||
|
||||
// Handle in-band channel requests: pty-req, shell, exec, env, window-change.
|
||||
var command string
|
||||
|
||||
for req := range requests {
|
||||
switch req.Type {
|
||||
case "pty-req":
|
||||
// Accept PTY allocation; allows interactive shell to work
|
||||
if req.WantReply {
|
||||
req.Reply(true, nil)
|
||||
}
|
||||
case "shell":
|
||||
if req.WantReply {
|
||||
req.Reply(true, nil)
|
||||
}
|
||||
runFakeShell(ctx, channel, ip, logger, idleTimeout)
|
||||
return
|
||||
case "exec":
|
||||
// Payload format: uint32(length) + string(command)
|
||||
if len(req.Payload) >= 4 {
|
||||
cmdLen := binary.BigEndian.Uint32(req.Payload[0:4])
|
||||
if int(cmdLen)+4 <= len(req.Payload) {
|
||||
command = string(req.Payload[4 : 4+cmdLen])
|
||||
}
|
||||
}
|
||||
if req.WantReply {
|
||||
req.Reply(true, nil)
|
||||
}
|
||||
// Log the exec command
|
||||
if command != "" {
|
||||
if err := logger.LogCommand(ip, command); err != nil {
|
||||
log.Printf("Failed to log command from %s: %v", ip, err)
|
||||
}
|
||||
log.Printf("Command (exec) from %s: %q", ip, command)
|
||||
}
|
||||
// Send exit status and close
|
||||
channel.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
|
||||
return
|
||||
case "env":
|
||||
if req.WantReply {
|
||||
req.Reply(true, nil)
|
||||
}
|
||||
case "window-change":
|
||||
if req.WantReply {
|
||||
req.Reply(true, nil)
|
||||
}
|
||||
default:
|
||||
if req.WantReply {
|
||||
req.Reply(false, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runFakeShell presents a fake interactive shell, logging every line of input.
|
||||
func runFakeShell(ctx context.Context, channel ssh.Channel, ip string, logger ConnectionLogger, idleTimeout time.Duration) {
|
||||
prompt := fakeShellPrompt
|
||||
channel.Write([]byte(prompt))
|
||||
|
||||
scanner := bufio.NewScanner(channel)
|
||||
// bufio.Scanner has a default max token size of 64KB; keep that
|
||||
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" {
|
||||
channel.Write([]byte(prompt))
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle exit/logout
|
||||
lower := strings.ToLower(line)
|
||||
if lower == "exit" || lower == "logout" {
|
||||
log.Printf("Session from %s closed by client (%q)", ip, line)
|
||||
channel.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
|
||||
return
|
||||
}
|
||||
|
||||
// Log the command
|
||||
if err := logger.LogCommand(ip, line); err != nil {
|
||||
log.Printf("Failed to log command from %s: %v", ip, err)
|
||||
}
|
||||
log.Printf("Command from %s: %q", ip, line)
|
||||
|
||||
// Send the prompt back, pretending the command produced no output
|
||||
channel.Write([]byte("\r\n" + prompt))
|
||||
}
|
||||
|
||||
// Scanner stopped (client disconnected or EOF)
|
||||
if err := scanner.Err(); err != nil {
|
||||
log.Printf("Session read error from %s: %v", ip, err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user