Compare commits

...

31 Commits
v1.0.0 ... dev

Author SHA1 Message Date
16e5e9c010 upd vars 2025-03-16 01:34:01 +00:00
916d2a2d86 add docker tasks 2025-03-16 01:04:16 +00:00
github-actions[bot]
1bbe3102ce chore: auto-update Go modules 2025-03-10 00:07:55 +00:00
github-actions[bot]
f1762cf3ad chore: auto-update Go modules 2025-02-24 00:09:17 +00:00
386aab510e add update and release actions 2025-02-17 13:37:33 +00:00
c8fd7a3f22 run through formatter 2025-02-07 23:19:05 +00:00
db1c45a25b add taskfile 2025-02-03 18:25:39 +00:00
a1ecf85cbb updated changelog with dates. 2024-11-29 15:25:56 +00:00
6c83d6ad2c add multi platform targets to makefile 2024-11-29 04:34:12 +00:00
c2266ac9d9 target host is now configurable.
stale session timeout default value increased
2024-11-29 04:33:47 +00:00
b0a6ba8180 add link to q3rcon client 2024-11-29 04:29:18 +00:00
9b4a05c0f4 add .dockerignore 2024-11-12 10:12:36 +00:00
bfe31c28c8 no need to export sessionCache methods
rename upsert to insert since we only call it if there isn't a session.
2024-10-23 17:22:03 +01:00
abc1ea9d3f rename Q3RCON_STALE_SESSION_TIMEOUT to Q3RCON_SESSION_TIMEOUT 2024-10-23 16:45:05 +01:00
82ca15f70e add sessionCache, use it to store sessions. 2024-10-23 16:44:35 +01:00
8cb5bc03c5 upd comment 2024-10-19 22:01:47 +01:00
939d419438 use multi-stage build 2024-10-19 21:59:24 +01:00
c42df03858 read from env var Q3RCON_STALE_SESSION_TIMEOUT 2024-10-19 21:19:33 +01:00
64c1df645d add WithStaleTimeout Option function.
add a trace level log when a session gets deleted.
2024-10-19 21:19:03 +01:00
51f22f480b add Logging section to README. 2024-09-28 15:37:38 +01:00
3d1c8f90f3 remove init function\
remove global vars proxies, host
2024-09-28 15:36:24 +01:00
2fc0f7a74f log challenge requests 2024-09-28 15:36:04 +01:00
6cd90ae1dd reuse single buffers 2024-09-28 00:38:55 +01:00
826756eb6e rename comparand arg 2024-04-14 19:13:56 +01:00
05fb7bdd0f add compare helper method
split up long conditionals
2024-04-14 08:27:30 +01:00
e8f213fded easier to read? 2024-04-11 23:40:25 +01:00
3a8758a4d7 remove string casts
compare byte slices
2024-04-11 19:24:43 +01:00
2c8ae43303 split 3 times, log last part 2024-04-03 23:58:58 +01:00
0935fc1190 rename isBadRconRequest to isBadRconResponse 2024-04-03 20:59:37 +01:00
3e039824de log bad rcon requests at info level
include client ip in log
2024-04-03 20:54:10 +01:00
0c054377ba move validator methods into Validator struct
embed Validator into Session

unexport Session
2024-03-26 10:47:53 +00:00
20 changed files with 569 additions and 134 deletions

6
.dockerignore Normal file
View File

@ -0,0 +1,6 @@
*
!cmd/
!pkg/
!go.mod
!go.sum

31
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,31 @@
name: goreleaser
on:
push:
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10
permissions:
contents: write
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
-
name: Set up Go
uses: actions/setup-go@v5
-
name: Run GoReleaser
uses: goreleaser/goreleaser-action@v6
with:
distribution: goreleaser
version: '~> v2'
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

30
.github/workflows/update-go-modules.yml vendored Normal file
View File

@ -0,0 +1,30 @@
name: Auto-Update Go Modules
on:
schedule:
- cron: "0 0 * * 1" # Runs every Monday at midnight
jobs:
update-go-modules:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: stable
- name: Update Dependencies
run: |
go get -u ./...
go mod tidy
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add go.mod go.sum
git commit -m "chore: auto-update Go modules"
git push

7
.gitignore vendored
View File

@ -1,3 +1,5 @@
# Auto-generated .gitignore by gignore: github.com/onyx-and-iris/gignore
### Go ###
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
@ -7,6 +9,7 @@
*.dll
*.so
*.dylib
bin/
# Test binary, built with `go test -c`
*.test
@ -19,3 +22,7 @@
# Go workspace file
go.work
# End of gignore: github.com/onyx-and-iris/gignore
# Added by goreleaser init:
dist/

55
.goreleaser.yaml Normal file
View File

@ -0,0 +1,55 @@
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com
# The lines below are called `modelines`. See `:help modeline`
# Feel free to remove those if you don't want/need to use them.
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
version: 2
before:
hooks:
# You may remove this if you don't use go modules.
- go mod tidy
# you may remove this if you don't need go generate
- go generate ./...
builds:
- main: ./cmd/q3rcon-proxy/
env:
- CGO_ENABLED=0
goos:
- linux
- windows
goarch:
- amd64
archives:
- formats: ['tar.gz']
# this name template makes the OS and Arch compatible with the results of `uname`.
name_template: >-
{{ .ProjectName }}_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
# use zip for windows archives
format_overrides:
- goos: windows
formats: ['zip']
changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
release:
footer: >-
---
Released by [GoReleaser](https://github.com/goreleaser/goreleaser).

View File

@ -11,6 +11,38 @@ Before any major/minor/patch bump all unit tests will be run to verify they pass
- [x]
## [1.4.0] - 2024-11-29
### Added
- new environment variable `Q3RCON_TARGET_HOST` for setting the host the gameserver is on.
### Changed
- environment variable `Q3RCON_HOST` renamed to `Q3RCON_PROXY_HOST`
- environment variable `Q3RCON_PROXY` renamed to `Q3RCON_TARGET_PORTS`.
- default session timeout changed from 5 to 20 minutes.
## [1.3.0] - 2024-10-23
### Added
- Add sessionCache for tracking sessions.
- Functional option `WithStaleTimeout` renamed to `WithSessionTimeout`
## [1.2.0] - 2024-10-19
### Added
- optional function `WithStaleTimeout`, use it to configure the session timeout value.
- it defaults to 5 minutes.
## [1.1.0] - 2024-09-28
### Added
- connection (challenge) requests are now logged.
## [0.6.0] - 2024-03-21
### Added

View File

@ -1,14 +0,0 @@
FROM golang:1.21
WORKDIR /usr/src/app
# pre-copy/cache go.mod for pre-downloading dependencies and only redownloading them in subsequent builds if they change
COPY go.mod go.sum ./
RUN go mod download && go mod verify
# build binary and place into /usr/local/bin/
COPY . .
RUN go build -v -o /usr/local/bin/q3rcon-proxy ./cmd/q3rcon-proxy/
# Command to run when starting the container
ENTRYPOINT [ "q3rcon-proxy" ]

View File

@ -1,2 +1,40 @@
go-build:
go build ./cmd/q3rcon-proxy/
PROGRAM = q3rcon-proxy
GO = @go
BIN_DIR := bin
WINDOWS=$(BIN_DIR)/$(PROGRAM)_windows_amd64.exe
LINUX=$(BIN_DIR)/$(PROGRAM)_linux_amd64
VERSION=$(shell git log -n 1 --format=%h)
.DEFAULT_GOAL := build
.PHONY: fmt vet build windows linux test clean
fmt:
$(GO) fmt ./...
vet: fmt
$(GO) vet ./...
build: vet windows linux | $(BIN_DIR)
@echo version: $(VERSION)
windows: $(WINDOWS)
linux: $(LINUX)
$(WINDOWS):
env GOOS=windows GOARCH=amd64 go build -v -o $(WINDOWS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
$(LINUX):
env GOOS=linux GOARCH=amd64 go build -v -o $(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/$(PROGRAM)/
test:
$(GO) test ./...
$(BIN_DIR):
@mkdir -p $@
clean:
@rm -rv $(BIN_DIR)

View File

@ -2,23 +2,29 @@
A modification of [lilproxy][lilproxy_url] that forwards only Q3 rcon/query packets. Useful for separating the rcon port from the game server port.
### Why
Unfortunately the Q3Rcon engine ties the rcon port to the game servers public port used for client connections. This proxy will allow you to run rcon through a separate whitelisted port.
### Use
Run one or multiple rcon proxies by setting an environment variable `Q3RCON_PROXY`
Run one or multiple rcon proxies by setting an environment variable `Q3RCON_TARGET_PORTS`
for example:
```bash
export Q3RCON_PROXY="20000:28960;20001:28961;20002:28962"
export Q3RCON_TARGET_PORTS="20000:28960;20001:28961;20002:28962"
```
This would configure q3rcon-proxy to run 3 proxy servers listening on ports `20000`, `20001` and `20002` that redirect rcon requests to game servers on ports `28960`, `28961` and `28962` respectively.
Then just run the binary which you can compile yourself, download from `Releases` or use the included Dockerfile.
### Why
### Logging
Avoid sending plaintext rcon commands to the public game server port. In general I would advise anyone using rcon remotely to use a secured connection but perhaps you've passed rcon to a clan friend who doesn't know about secured connections. Now you can instruct them to use rcon only through a whitelisted port.
Set the log level with environment variable `Q3RCON_LOGLEVEL`:
`0 = Panic, 1 = Fatal, 2 = Error, 3 = Warning, 4 = Info, 5 = Debug, 6 = Trace`
### Special Thanks
@ -26,3 +32,9 @@ Avoid sending plaintext rcon commands to the public game server port. In general
[lilproxy_url]: https://github.com/dgparker/lilproxy
[user_link]: https://github.com/dgparker
### Further Notes
For a compatible rcon client also written in Go consider checking out the [Q3 Rcon][q3rcon] package.
[q3rcon]: https://github.com/onyx-and-iris/q3rcon

60
Taskfile.yml Normal file
View File

@ -0,0 +1,60 @@
version: '3'
includes:
docker: ./docker/Taskfile.docker.yml
vars:
PROGRAM: q3rcon-proxy
SHELL: '{{if eq .OS "Windows_NT"}}powershell{{end}}'
BIN_DIR: bin
WINDOWS: '{{.BIN_DIR}}/{{.PROGRAM}}_windows_amd64.exe'
LINUX: '{{.BIN_DIR}}/{{.PROGRAM}}_linux_amd64'
GIT_COMMIT:
sh: git log -n 1 --format=%h
tasks:
default:
desc: Build the q3rcon-proxy project
cmds:
- task: build
build:
desc: Build the q3rcon-proxy project
deps: [vet]
cmds:
- task: build-windows
- task: build-linux
vet:
desc: Vet the code
deps: [fmt]
cmds:
- go vet ./...
fmt:
desc: Fmt the code
cmds:
- go fmt ./...
build-windows:
desc: Build the q3rcon-proxy project for Windows
cmds:
- GOOS=windows GOARCH=amd64 go build -o {{.WINDOWS}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/
internal: true
build-linux:
desc: Build the q3rcon-proxy project for Linux
cmds:
- GOOS=linux GOARCH=amd64 go build -o {{.LINUX}} -ldflags="-X main.Version={{.GIT_COMMIT}}" ./cmd/{{.PROGRAM}}/
internal: true
test:
desc: Run tests
cmds:
- go test ./...
clean:
desc: Clean the build artifacts
cmds:
- '{{.SHELL}} rm -r {{.BIN_DIR}}'

View File

@ -3,74 +3,71 @@ package main
import (
"fmt"
"os"
"strconv"
"slices"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/onyx-and-iris/q3rcon-proxy/pkg/udpproxy"
)
func start(proxy string) {
port, target := func() (string, string) {
x := strings.Split(proxy, ":")
func main() {
logLevel, err := getEnvInt("Q3RCON_LOGLEVEL")
if err != nil {
log.Fatalf("unable to parse Q3RCON_LEVEL: %s", err.Error())
}
if slices.Contains(log.AllLevels, log.Level(logLevel)) {
log.SetLevel(log.Level(logLevel))
}
proxyHost := os.Getenv("Q3RCON_PROXY_HOST")
if proxyHost == "" {
proxyHost = "0.0.0.0"
}
targetHost := os.Getenv("Q3RCON_TARGET_HOST")
if targetHost == "" {
targetHost = "127.0.0.1"
}
proxies := os.Getenv("Q3RCON_TARGET_PORTS")
if proxies == "" {
log.Fatal("env Q3RCON_TARGET_PORTS required")
}
sessionTimeout, err := getEnvInt("Q3RCON_SESSION_TIMEOUT")
if err != nil {
log.Fatalf("unable to parse Q3RCON_SESSION_TIMEOUT: %s", err.Error())
}
if sessionTimeout == 0 {
sessionTimeout = 20
}
for _, proxy := range strings.Split(proxies, ";") {
go start(proxyHost, targetHost, proxy, sessionTimeout)
}
<-make(chan struct{})
}
func start(proxyHost, targetHost, ports string, sessionTimeout int) {
proxyPort, targetPort := func() (string, string) {
x := strings.Split(ports, ":")
return x[0], x[1]
}()
c, err := udpproxy.New(fmt.Sprintf("%s:%s", host, port), fmt.Sprintf("127.0.0.1:%s", target))
hostAddr := fmt.Sprintf("%s:%s", proxyHost, proxyPort)
proxyAddr := fmt.Sprintf("%s:%s", targetHost, targetPort)
c, err := udpproxy.New(
hostAddr, proxyAddr,
udpproxy.WithSessionTimeout(time.Duration(sessionTimeout)*time.Minute))
if err != nil {
log.Fatal(err)
}
log.Printf("q3rcon-proxy initialized: [proxy] (%s:%s) [target] (127.0.0.1:%s)", host, port, target)
log.Printf("q3rcon-proxy initialized: [proxy] (%s) [target] (%s)", hostAddr, proxyAddr)
log.Fatal(c.ListenAndServe())
}
var (
proxies, host string
)
func getenvInt(key string) (int, error) {
s := os.Getenv(key)
if s == "" {
return 0, nil
}
v, err := strconv.Atoi(s)
if err != nil {
return 0, err
}
return v, nil
}
func init() {
proxies = os.Getenv("Q3RCON_PROXY")
if proxies == "" {
log.Fatal("env Q3RCON_PROXY required")
}
host = os.Getenv("Q3RCON_HOST")
if host == "" {
host = "0.0.0.0"
}
debug, err := getenvInt("Q3RCON_DEBUG")
if err != nil {
log.Fatal(err)
}
if debug == 1 {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
}
func main() {
for _, proxy := range strings.Split(proxies, ";") {
go start(proxy)
}
<-make(chan int)
}

18
cmd/q3rcon-proxy/util.go Normal file
View File

@ -0,0 +1,18 @@
package main
import (
"os"
"strconv"
)
func getEnvInt(key string) (int, error) {
s := os.Getenv(key)
if s == "" {
return 0, nil
}
v, err := strconv.Atoi(s)
if err != nil {
return 0, err
}
return v, nil
}

21
docker/Dockerfile Normal file
View File

@ -0,0 +1,21 @@
FROM golang:1.24 AS build_image
WORKDIR /usr/src/app
# pre-copy/cache go.mod for pre-downloading dependencies and only redownloading them in subsequent builds if they change
COPY go.mod go.sum ./
RUN go mod download && go mod verify
COPY . .
# build binary, place into ./bin/
RUN CGO_ENABLED=0 GOOS=linux go build -o ./bin/q3rcon-proxy ./cmd/q3rcon-proxy/
FROM scratch AS final_image
WORKDIR /bin/
COPY --from=build_image /usr/src/app/bin/q3rcon-proxy .
# Command to run when starting the container
ENTRYPOINT [ "./q3rcon-proxy" ]

View File

@ -0,0 +1,26 @@
version: '3'
vars:
IMAGE: q3rcon-proxy
tasks:
build:
desc: Build the Docker image
cmds:
- docker build -t {{.IMAGE}} -f docker/Dockerfile .
dir: .
login:
desc: Login to Github Container Registry
cmds:
- docker login ghcr.io -u {{.GHCR_USER}} --password-stdin <<< {{.GHCR_TOKEN}}
internal: true
push:
desc: Push the Docker image to Github Container Registry
deps:
- task: build
- task: login
cmds:
- docker tag {{.IMAGE}} ghcr.io/{{.GHCR_USER}}/{{.IMAGE}}:latest
- docker push ghcr.io/{{.GHCR_USER}}/{{.IMAGE}}:latest

6
go.mod
View File

@ -1,7 +1,9 @@
module github.com/onyx-and-iris/q3rcon-proxy
go 1.18
go 1.24.0
toolchain go1.24.1
require github.com/sirupsen/logrus v1.9.3
require golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
require golang.org/x/sys v0.31.0 // indirect

3
go.sum
View File

@ -8,8 +8,9 @@ github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVs
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -2,6 +2,7 @@ package udpproxy
import (
"errors"
"fmt"
"net"
"strings"
"time"
@ -9,24 +10,27 @@ import (
log "github.com/sirupsen/logrus"
)
type Session struct {
type session struct {
serverConn *net.UDPConn
proxyConn *net.UDPConn
caddr *net.UDPAddr
updateTime time.Time
validator
}
func newSession(caddr *net.UDPAddr, raddr *net.UDPAddr, proxyConn *net.UDPConn) (*Session, error) {
func newSession(caddr *net.UDPAddr, raddr *net.UDPAddr, proxyConn *net.UDPConn) (*session, error) {
serverConn, err := net.DialUDP("udp", nil, raddr)
if err != nil {
return nil, err
}
session := &Session{
session := &session{
serverConn: serverConn,
proxyConn: proxyConn,
caddr: caddr,
updateTime: time.Now(),
validator: newValidator(),
}
go session.listen()
@ -34,33 +38,9 @@ func newSession(caddr *net.UDPAddr, raddr *net.UDPAddr, proxyConn *net.UDPConn)
return session, nil
}
func (s *Session) isRconRequestPacket(buf []byte) bool {
return string(buf[:8]) == "\xff\xff\xff\xffrcon"
}
func (s *Session) isQueryRequestPacket(buf []byte) bool {
return string(buf[:13]) == "\xff\xff\xff\xffgetstatus" || string(buf[:11]) == "\xff\xff\xff\xffgetinfo"
}
func (s *Session) isValidRequestPacket(buf []byte) bool {
return s.isRconRequestPacket(buf) || s.isQueryRequestPacket(buf)
}
func (s *Session) isRconResponsePacket(buf []byte) bool {
return string(buf[:9]) == "\xff\xff\xff\xffprint"
}
func (s *Session) isQueryResponsePacket(buf []byte) bool {
return string(buf[:18]) == "\xff\xff\xff\xffstatusResponse" || string(buf[:16]) == "\xff\xff\xff\xffinfoResponse"
}
func (s *Session) isValidResponsePacket(buf []byte) bool {
return s.isRconResponsePacket(buf) || s.isQueryResponsePacket(buf)
}
func (s *Session) listen() error {
func (s *session) listen() error {
buf := make([]byte, 2048)
for {
buf := make([]byte, 2048)
n, err := s.serverConn.Read(buf)
if err != nil {
log.Error(err)
@ -71,7 +51,7 @@ func (s *Session) listen() error {
}
}
func (s *Session) proxyFrom(buf []byte) error {
func (s *session) proxyFrom(buf []byte) error {
if !s.isValidResponsePacket(buf) {
err := errors.New("not a rcon or query response packet")
log.Error(err.Error())
@ -86,15 +66,25 @@ func (s *Session) proxyFrom(buf []byte) error {
}
if s.isRconResponsePacket(buf) {
log.Debugf("Response: %s", string(buf[10:]))
if s.isBadRconResponse(buf) {
log.Infof("Response: Bad rcon from %s", s.caddr.IP)
} else {
log.Debugf("Response: %s", string(buf[len(s.rconResponseHeader):]))
}
}
return nil
}
func (s *Session) proxyTo(buf []byte) error {
func (s *session) proxyTo(buf []byte) error {
if !s.isValidRequestPacket(buf) {
err := errors.New("not a rcon or query request packet")
var err error
if s.isChallengeRequestPacket(buf) {
parts := strings.SplitN(string(buf), " ", 3)
err = fmt.Errorf("invalid challenge from %s with GUID: %s", s.caddr.IP, parts[len(parts)-1])
} else {
err = errors.New("not a rcon or query request packet")
}
log.Error(err.Error())
return err
}
@ -107,8 +97,8 @@ func (s *Session) proxyTo(buf []byte) error {
}
if s.isRconRequestPacket(buf) {
parts := strings.Split(string(buf), " ")
log.Infof("From [%s] To [%s] Command: %s", s.caddr.IP, s.serverConn.RemoteAddr(), strings.Join(parts[2:], " "))
parts := strings.SplitN(string(buf), " ", 3)
log.Infof("From [%s] To [%s] Command: %s", s.caddr.IP, s.serverConn.RemoteAddr(), parts[len(parts)-1])
}
return nil

View File

@ -0,0 +1,41 @@
package udpproxy
import "sync"
// sessionCache tracks connection sessions
type sessionCache struct {
mu sync.RWMutex
data map[string]*session
}
// newSessionCache creates a usable sessionCache.
func newSessionCache() sessionCache {
return sessionCache{
data: make(map[string]*session),
}
}
// read returns the associated session for an addr
func (sc *sessionCache) read(addr string) (*session, bool) {
sc.mu.RLock()
defer sc.mu.RUnlock()
v, ok := sc.data[addr]
return v, ok
}
// insert adds a session for a given addr.
func (sc *sessionCache) insert(addr string, session *session) {
sc.mu.Lock()
defer sc.mu.Unlock()
sc.data[addr] = session
}
// delete removes the session for the given addr.
func (sc *sessionCache) delete(addr string) {
sc.mu.Lock()
defer sc.mu.Unlock()
delete(sc.data, addr)
}

View File

@ -2,24 +2,38 @@ package udpproxy
import (
"net"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
// Option is a functional option type that allows us to configure the Client.
type Option func(*Client)
// WithSessionTimeout is a functional option to set the session timeout
func WithSessionTimeout(timeout time.Duration) Option {
return func(c *Client) {
if timeout < time.Minute {
log.Warnf("cannot set stale session timeout to less than 1 minute.. defaulting to 20 minutes")
return
}
c.sessionTimeout = timeout
}
}
type Client struct {
laddr *net.UDPAddr
raddr *net.UDPAddr
proxyConn *net.UDPConn
mutex sync.RWMutex
sessions map[string]*Session
sessionCache sessionCache
sessionTimeout time.Duration
}
func New(port, target string) (*Client, error) {
laddr, err := net.ResolveUDPAddr("udp", port)
func New(proxy, target string, options ...Option) (*Client, error) {
laddr, err := net.ResolveUDPAddr("udp", proxy)
if err != nil {
return nil, err
}
@ -29,12 +43,18 @@ func New(port, target string) (*Client, error) {
return nil, err
}
return &Client{
laddr: laddr,
raddr: raddr,
mutex: sync.RWMutex{},
sessions: map[string]*Session{},
}, nil
c := &Client{
laddr: laddr,
raddr: raddr,
sessionCache: newSessionCache(),
sessionTimeout: 20 * time.Minute,
}
for _, o := range options {
o(c)
}
return c, nil
}
func (c *Client) ListenAndServe() error {
@ -46,22 +66,22 @@ func (c *Client) ListenAndServe() error {
go c.pruneSessions()
buf := make([]byte, 2048)
for {
buf := make([]byte, 2048)
n, caddr, err := c.proxyConn.ReadFromUDP(buf)
if err != nil {
log.Error(err)
}
session, found := c.sessions[caddr.String()]
if !found {
session, ok := c.sessionCache.read(caddr.String())
if !ok {
session, err = newSession(caddr, c.raddr, c.proxyConn)
if err != nil {
log.Error(err)
continue
}
c.sessions[caddr.String()] = session
c.sessionCache.insert(caddr.String(), session)
}
go session.proxyTo(buf[:n])
@ -71,15 +91,12 @@ func (c *Client) ListenAndServe() error {
func (c *Client) pruneSessions() {
ticker := time.NewTicker(1 * time.Minute)
// the locks here could be abusive and i dont even know if this is a real
// problem but we definitely need to clean up stale sessions
for range ticker.C {
for _, session := range c.sessions {
c.mutex.RLock()
if time.Since(session.updateTime) > time.Minute*5 {
delete(c.sessions, session.caddr.String())
for _, session := range c.sessionCache.data {
if time.Since(session.updateTime) > c.sessionTimeout {
c.sessionCache.delete(session.caddr.String())
log.Tracef("session for %s deleted", session.caddr)
}
c.mutex.RUnlock()
}
}
}

65
pkg/udpproxy/validator.go Normal file
View File

@ -0,0 +1,65 @@
package udpproxy
import "bytes"
type validator struct {
rconRequestHeader []byte
getstatusRequestHeader []byte
getinfoRequestHeader []byte
getchallengeRequestHeader []byte
rconResponseHeader []byte
getstatusResponseHeader []byte
getinfoResponseHeader []byte
badRconIdentifier []byte
}
func newValidator() validator {
return validator{
rconRequestHeader: []byte("\xff\xff\xff\xffrcon"),
getstatusRequestHeader: []byte("\xff\xff\xff\xffgetstatus"),
getinfoRequestHeader: []byte("\xff\xff\xff\xffgetinfo"),
getchallengeRequestHeader: []byte("\xff\xff\xff\xffgetchallenge"),
rconResponseHeader: []byte("\xff\xff\xff\xffprint\n"),
getstatusResponseHeader: []byte("\xff\xff\xff\xffstatusResponse\n"),
getinfoResponseHeader: []byte("\xff\xff\xff\xffinfoResponse\n"),
badRconIdentifier: []byte("Bad rcon"),
}
}
func (v validator) compare(buf, c []byte) bool {
return bytes.Equal(buf[:len(c)], c)
}
func (v validator) isRconRequestPacket(buf []byte) bool {
return v.compare(buf, v.rconRequestHeader)
}
func (v validator) isQueryRequestPacket(buf []byte) bool {
return v.compare(buf, v.getstatusRequestHeader) ||
v.compare(buf, v.getinfoRequestHeader)
}
func (v validator) isValidRequestPacket(buf []byte) bool {
return v.isRconRequestPacket(buf) || v.isQueryRequestPacket(buf)
}
func (v validator) isChallengeRequestPacket(buf []byte) bool {
return v.compare(buf, v.getchallengeRequestHeader)
}
func (v validator) isRconResponsePacket(buf []byte) bool {
return v.compare(buf, v.rconResponseHeader)
}
func (v validator) isQueryResponsePacket(buf []byte) bool {
return v.compare(buf, v.getstatusResponseHeader) ||
v.compare(buf, v.getinfoResponseHeader)
}
func (v validator) isValidResponsePacket(buf []byte) bool {
return v.isRconResponsePacket(buf) || v.isQueryResponsePacket(buf)
}
func (v validator) isBadRconResponse(buf []byte) bool {
return v.compare(buf[len(v.rconResponseHeader):], v.badRconIdentifier)
}