Security performance improvements #1

Merged
marvin merged 6 commits from security-performance-improvements into main 2026-10-22 12:08:53 +00:00
5 changed files with 159 additions and 71 deletions
Showing only changes of commit 7d25ef3804 - Show all commits

No files matched your search

+31 -1
View File
@@ -4,15 +4,45 @@ on:
push:
branches:
- "main"
- "security-performance-improvements"
pull_request:
branches:
- "main"
jobs:
test:
runs-on: ubuntu-latest
container:
image: golang:1.27-alpine
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: go mod download
run: go mod download
- name: go build
run: go build -v ./...
- name: go vet
run: go vet ./...
- name: gofmt check
run: test -z "$(gofmt -l .)" || (echo "gofmt issues found:" && gofmt -l . && exit 1)
- name: go test
run: go test -v ./...
build:
needs: test
runs-on: ubuntu-latest
container:
image: registry.rznet.fr/tchivert/ubuntu:act-latest
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
fetch-depth: 0 # all history for all branches and tags
+5 -1
View File
@@ -10,7 +10,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build -o tbin .
FROM alpine:3.24
RUN addgroup -S tbin && adduser -S tbin -G tbin
RUN addgroup -S tbin && adduser -S -u 1000 -G tbin tbin
WORKDIR /app
@@ -18,8 +18,12 @@ COPY --from=build /build/tbin ./
COPY --chown=tbin:tbin index.html ./
COPY --chown=tbin:tbin favicon.png ./
RUN mkdir -p /app/data && chown tbin:tbin /app/data
USER tbin
VOLUME /app/data
EXPOSE 4242
EXPOSE 8080
+11 -6
View File
@@ -28,6 +28,8 @@ tbin can also be started using Docker. To do this, follow these steps:
4. Start the application using Docker Compose: `docker-compose up -d`
5. tbin will be started as a Docker container and will be accessible via telnet and HTTP.
The Docker container runs as a non-root user (UID 1000) and uses a named volume (`tbin-data`) for data persistence.
## Usage
To submit a text snippet using the telnet interface, follow these steps:
@@ -36,7 +38,7 @@ To submit a text snippet using the telnet interface, follow these steps:
2. Use the `nc` command to connect to the tbin server: `echo "Your text snippet" | nc localhost 4242`
3. The server will generate a unique URL for your text snippet, which will be displayed in the terminal.
Purges can be trigged with the `/purge` endpoint.
Purges can be trigged with the `/purge` endpoint (localhost only).
It will remove all snippets olders than the configuered TTL (default: 48 hours).
## Configuration
@@ -61,11 +63,11 @@ tbin can be configured using command-line flags when starting the application.
## Monitoring
tbin exposes Prometheus metrics when `--metrics-addr` is set. Available metrics:
tbin exposes Prometheus metrics when `--metrics-addr` is set. The metrics server runs on a separate port and is not exposed on the main HTTP port. Available metrics:
- `tbin_pastes_total`: Total pastes created
- `tbin_pastes_bytes_total`: Total bytes of pastes created
- `tbin_http_requests_total`: HTTP requests by method, path, and status
- `tbin_http_requests_total`: HTTP requests by method, endpoint, and status
- `tbin_tcp_connections_total`: Total TCP connections accepted
- `tbin_tcp_active_connections`: Current active TCP connections
- `tbin_purge_runs_total`: Total purge operations executed
@@ -78,11 +80,14 @@ A `/health` endpoint is also available on the HTTP port for health checks.
- HTTP server has read/write/idle timeouts to prevent slowloris attacks
- Request body size is limited via `http.MaxBytesReader`
- TCP connections are rate-limited and capped with `--max-conns`
- Paste files are created with 0600 permissions
- TCP connections are rate-limited per-IP and capped with `--max-conns`
- HTTP requests are rate-limited per-IP
- Paste files are created with 0600 permissions and O_EXCL to prevent races
- The `/purge` endpoint is restricted to localhost
- Security headers (CSP, X-Frame-Options, etc.) are set on all responses
- Graceful shutdown on SIGTERM/SIGINT
- Graceful shutdown on SIGTERM/SIGINT with WaitGroup tracking of in-flight requests
- Docker container runs as non-root user (UID 1000)
- Docker base images are pinned (golang:1.27-alpine, alpine:3.24)
## License
+4 -1
View File
@@ -7,6 +7,9 @@ services:
image: git.rznet.fr/tchivert/tbin
restart: always
volumes:
- ./data:/app/data
- tbin-data:/app/data
command:
- --http-url=http://localhost:8080/
volumes:
tbin-data:
+108 -62
View File
@@ -45,13 +45,11 @@ var (
)
var (
logger *slog.Logger
connSem chan struct{}
activeConns atomic.Int64
purgeMu sync.Mutex
purgeRunning atomic.Bool
tcpLimiter *rate.Limiter
httpLimiter *rate.Limiter
logger *slog.Logger
connSem chan struct{}
activeConns atomic.Int64
wg sync.WaitGroup
purgeMu sync.Mutex
metricPastesTotal prometheus.Counter
metricPastesBytes prometheus.Counter
@@ -63,6 +61,53 @@ var (
metricRemovesTotal prometheus.Counter
)
type ipLimiter struct {
mu sync.Mutex
limiters map[string]*rate.Limiter
limit rate.Limit
burst int
}
func newIPLimiter(limit rate.Limit, burst int) *ipLimiter {
il := &ipLimiter{
limiters: make(map[string]*rate.Limiter),
limit: limit,
burst: burst,
}
go il.cleanup()
return il
}
func (il *ipLimiter) get(ip string) *rate.Limiter {
il.mu.Lock()
defer il.mu.Unlock()
l, ok := il.limiters[ip]
if !ok {
l = rate.NewLimiter(il.limit, il.burst)
il.limiters[ip] = l
}
return l
}
func (il *ipLimiter) cleanup() {
ticker := time.NewTicker(10 * time.Minute)
defer ticker.Stop()
for range ticker.C {
il.mu.Lock()
for ip, l := range il.limiters {
if l.Tokens() == float64(il.burst) {
delete(il.limiters, ip)
}
}
il.mu.Unlock()
}
}
var (
httpIPLimiter *ipLimiter
tcpIPLimiter *ipLimiter
)
func initMetrics() {
metricPastesTotal = prometheus.NewCounter(prometheus.CounterOpts{
Name: "tbin_pastes_total",
@@ -74,8 +119,8 @@ func initMetrics() {
})
metricHTTPRequests = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "tbin_http_requests_total",
Help: "Total HTTP requests by method and path",
}, []string{"method", "path", "status"})
Help: "Total HTTP requests by method, endpoint, and status",
}, []string{"method", "endpoint", "status"})
metricTCPConnections = prometheus.NewCounter(prometheus.CounterOpts{
Name: "tbin_tcp_connections_total",
Help: "Total TCP connections accepted",
@@ -176,8 +221,8 @@ func main() {
connSem = make(chan struct{}, *maxConns)
if *rateLimit > 0 {
tcpLimiter = rate.NewLimiter(rate.Limit(*rateLimit), *rateLimit*2)
httpLimiter = rate.NewLimiter(rate.Limit(*rateLimit), *rateLimit*2)
httpIPLimiter = newIPLimiter(rate.Limit(*rateLimit), *rateLimit*2)
tcpIPLimiter = newIPLimiter(rate.Limit(*rateLimit), *rateLimit*2)
}
logger.Info("starting tbin",
@@ -198,6 +243,9 @@ func main() {
}
listenHTTP(ctx)
wg.Wait()
logger.Info("shutdown complete")
}
func listenTCP(ctx context.Context) {
@@ -226,7 +274,11 @@ func listenTCP(ctx context.Context) {
}
}
metricTCPConnections.Inc()
go handleTCP(conn)
wg.Add(1)
go func() {
defer wg.Done()
handleTCP(conn)
}()
}
}
@@ -243,8 +295,6 @@ func listenHTTP(ctx context.Context) {
handleHTTP(w, r)
})
mux.Handle("/metrics", promhttp.Handler())
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"ok"}`))
@@ -297,23 +347,16 @@ func listenMetrics(ctx context.Context) {
}
}
func getClientIP(r *http.Request) string {
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
parts := strings.Split(fwd, ",")
return strings.TrimSpace(parts[0])
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
func getRemoteIP(addr string) string {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return r.RemoteAddr
return addr
}
return host
}
func isLocalhost(addr string) bool {
host, _, err := net.SplitHostPort(addr)
if err != nil {
host = addr
}
host := getRemoteIP(addr)
return host == "127.0.0.1" || host == "::1" || host == "localhost"
}
@@ -322,9 +365,10 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) {
logger.Debug("http request", "remote", r.RemoteAddr, "method", r.Method, "path", r.URL.Path)
}
if httpLimiter != nil {
if !httpLimiter.Allow() {
metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "429").Inc()
if httpIPLimiter != nil {
ip := getRemoteIP(r.RemoteAddr)
if !httpIPLimiter.get(ip).Allow() {
metricHTTPRequests.WithLabelValues(r.Method, "rate_limited", "429").Inc()
http.Error(w, "Too many requests", http.StatusTooManyRequests)
return
}
@@ -332,7 +376,7 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) {
id := strings.TrimPrefix(r.URL.Path, "/")
if strings.Contains(id, "..") || strings.Contains(id, "/") {
metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "400").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "invalid_path", "400").Inc()
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
@@ -343,35 +387,49 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) {
switch id {
case "paste":
if err := r.ParseForm(); err != nil {
metricHTTPRequests.WithLabelValues(r.Method, "paste", "400").Inc()
http.Error(w, "Invalid form data", http.StatusBadRequest)
return
}
data := r.FormValue("paste")
if data == "" {
metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "400").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "paste", "400").Inc()
http.Error(w, "Empty data", http.StatusBadRequest)
return
}
if len(data) > *buff {
metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "413").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "paste", "413").Inc()
http.Error(w, "Data too large", http.StatusRequestEntityTooLarge)
return
}
newID := handleData([]byte(data))
if newID == "" {
metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "500").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "paste", "500").Inc()
http.Error(w, "Error generating file", http.StatusInternalServerError)
return
}
metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "303").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "paste", "303").Inc()
http.Redirect(w, r, "/"+newID, http.StatusSeeOther)
case "remove":
if err := r.ParseForm(); err != nil {
metricHTTPRequests.WithLabelValues(r.Method, "remove", "400").Inc()
http.Error(w, "Invalid form data", http.StatusBadRequest)
return
}
removeID := r.FormValue("remove")
if removeID != "" {
metricRemovesTotal.Inc()
go handleRemove(removeID)
wg.Add(1)
go func() {
defer wg.Done()
handleRemove(removeID)
}()
}
metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "303").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "remove", "303").Inc()
http.Redirect(w, r, "/", http.StatusSeeOther)
default:
metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "404").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "not_found", "404").Inc()
http.Error(w, "Not found", http.StatusNotFound)
}
case "GET":
@@ -380,35 +438,34 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "public, max-age=3600")
serveFile(w, "index.html")
metricHTTPRequests.WithLabelValues(r.Method, "/", "200").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "index", "200").Inc()
case strings.HasPrefix(id, "favicon"):
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Cache-Control", "public, max-age=86400")
serveFile(w, "favicon.png")
metricHTTPRequests.WithLabelValues(r.Method, "/favicon", "200").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "favicon", "200").Inc()
case id == "example":
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("Hello there\n"))
metricHTTPRequests.WithLabelValues(r.Method, "/example", "200").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "example", "200").Inc()
return
case id == "purge":
if !isLocalhost(r.RemoteAddr) {
logger.Warn("unauthorized purge attempt", "remote", r.RemoteAddr)
metricHTTPRequests.WithLabelValues(r.Method, "/purge", "401").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "purge", "401").Inc()
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
logger.Info("purge requested", "remote", r.RemoteAddr)
metricHTTPRequests.WithLabelValues(r.Method, "/purge", "200").Inc()
go handlePurge()
metricHTTPRequests.WithLabelValues(r.Method, "purge", "200").Inc()
wg.Add(1)
go func() {
defer wg.Done()
handlePurge()
}()
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("OK\n"))
return
case id == "health":
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"ok"}`))
metricHTTPRequests.WithLabelValues(r.Method, "/health", "200").Inc()
return
default:
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Robots-Tag", "noindex,nofollow")
@@ -424,7 +481,7 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) {
io.CopyN(w, f, int64(*buff))
}
default:
metricHTTPRequests.WithLabelValues(r.Method, r.URL.Path, "405").Inc()
metricHTTPRequests.WithLabelValues(r.Method, "method_not_allowed", "405").Inc()
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
@@ -460,17 +517,13 @@ func handleTCP(conn net.Conn) {
conn.Close()
}()
if tcpLimiter != nil {
host, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
host = remoteAddr
}
if !tcpLimiter.Allow() {
if tcpIPLimiter != nil {
ip := getRemoteIP(remoteAddr)
if !tcpIPLimiter.get(ip).Allow() {
logger.Warn("rate limit exceeded", "remote", remoteAddr)
conn.Write([]byte("Error: rate limit exceeded, slow down\n"))
return
}
_ = host
}
logger.Debug("tcp connection", "remote", remoteAddr)
@@ -622,7 +675,6 @@ func handleRemove(id string) {
logger.Error("error removing file", "file", filename, "error", err)
} else {
logger.Info("file removed", "file", filename)
metricRemovesTotal.Inc()
}
}
@@ -633,12 +685,6 @@ func handlePurge() {
}
defer purgeMu.Unlock()
if !purgeRunning.CompareAndSwap(false, true) {
logger.Debug("purge already in progress, skipping")
return
}
defer purgeRunning.Store(false)
metricPurgeRuns.Inc()
logger.Info("purge started")