mirror of
https://github.com/onyx-and-iris/q3rcon-proxy.git
synced 2026-04-07 15:53:29 +00:00
Compare commits
36 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a1ecf85cbb | |||
| 6c83d6ad2c | |||
| c2266ac9d9 | |||
| b0a6ba8180 | |||
| 9b4a05c0f4 | |||
| bfe31c28c8 | |||
| abc1ea9d3f | |||
| 82ca15f70e | |||
| 8cb5bc03c5 | |||
| 939d419438 | |||
| c42df03858 | |||
| 64c1df645d | |||
| 51f22f480b | |||
| 3d1c8f90f3 | |||
| 2fc0f7a74f | |||
| 6cd90ae1dd | |||
| 826756eb6e | |||
| 05fb7bdd0f | |||
| e8f213fded | |||
| 3a8758a4d7 | |||
| 2c8ae43303 | |||
| 0935fc1190 | |||
| 3e039824de | |||
| 0c054377ba | |||
| 5ac3f805e2 | |||
| ab548d669a | |||
| 107f914d3b | |||
| 0fdf9d10c3 | |||
| 690fabddaf | |||
| f6f0044a84 | |||
| 725e6cfb3d | |||
| ca33a6a390 | |||
| dfcdb6a96a | |||
| 15e4cf6e42 | |||
| f2fd9354f0 | |||
| 94a683fb3f |
6
.dockerignore
Normal file
6
.dockerignore
Normal file
@@ -0,0 +1,6 @@
|
||||
*
|
||||
!cmd/
|
||||
!pkg/
|
||||
|
||||
!go.mod
|
||||
!go.sum
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -7,6 +7,7 @@
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
bin/
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
@@ -19,3 +20,7 @@
|
||||
|
||||
# Go workspace file
|
||||
go.work
|
||||
|
||||
# testing
|
||||
run.sh
|
||||
server.yaml
|
||||
67
CHANGELOG.md
67
CHANGELOG.md
@@ -11,8 +11,73 @@ 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
|
||||
|
||||
- new environment variable `Q3RCON_DEBUG` for enabling debug logging. Defaults to 0.
|
||||
- rcon responses are now logged at debug level
|
||||
- invalid responses (rcon and query) now logged
|
||||
|
||||
### Changed
|
||||
|
||||
- All packet header checking methods moved into Session struct.
|
||||
|
||||
### Fixed
|
||||
|
||||
- a bug causing the proxy not to send back query responses
|
||||
|
||||
## [0.3.0] - 2024-03-08
|
||||
|
||||
### Added
|
||||
|
||||
- outgoing rcon requests now logged at info level
|
||||
- new environment variable `Q3RCON_HOST` for specifying which ip to bind the proxy to. Defaults to `0.0.0.0`.
|
||||
|
||||
### Changed
|
||||
|
||||
- now using [logrus][logrus] package for logging.
|
||||
|
||||
### Fixed
|
||||
|
||||
- a `slice bounds out of range` error due to query packets being logged.
|
||||
|
||||
## [0.1.0] - 2024-01-27
|
||||
|
||||
### Added
|
||||
|
||||
- only forward packets if the header matches q3 rcon/query.
|
||||
|
||||
## [0.0.1] - 2024-01-27
|
||||
@@ -20,3 +85,5 @@ Before any major/minor/patch bump all unit tests will be run to verify they pass
|
||||
### Added
|
||||
|
||||
- All source files for lilproxy including full commit history.
|
||||
|
||||
[logrus]: https://github.com/sirupsen/logrus
|
||||
|
||||
15
Dockerfile
15
Dockerfile
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.21
|
||||
FROM golang:1.21 AS build_image
|
||||
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
@@ -6,9 +6,16 @@ WORKDIR /usr/src/app
|
||||
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/
|
||||
|
||||
# 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" ]
|
||||
ENTRYPOINT [ "./q3rcon-proxy" ]
|
||||
42
Makefile
42
Makefile
@@ -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 describe --tags --always --long --dirty)
|
||||
|
||||
.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/q3rcon-proxy/
|
||||
|
||||
$(LINUX):
|
||||
env GOOS=linux GOARCH=amd64 go build -v -o $(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/q3rcon-proxy/
|
||||
|
||||
test:
|
||||
$(GO) test ./...
|
||||
|
||||
$(BIN_DIR):
|
||||
@mkdir -p $@
|
||||
|
||||
clean:
|
||||
@rm -rv $(BIN_DIR)
|
||||
22
README.md
22
README.md
@@ -2,27 +2,39 @@
|
||||
|
||||
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
|
||||
|
||||
[Dylan][user_link] For writing this proxy.
|
||||
[Dylan][user_link] For writing [lilproxy][lilproxy_url].
|
||||
|
||||
[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
|
||||
@@ -2,49 +2,72 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"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 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"
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
for _, proxy := range strings.Split(proxies, ";") {
|
||||
go start(proxy)
|
||||
}
|
||||
|
||||
<-make(chan int)
|
||||
}
|
||||
|
||||
18
cmd/q3rcon-proxy/util.go
Normal file
18
cmd/q3rcon-proxy/util.go
Normal 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
|
||||
}
|
||||
18
debian/q3rcon-proxy.service
vendored
Normal file
18
debian/q3rcon-proxy.service
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
[Unit]
|
||||
Description=Q3Rcon Proxy Service
|
||||
Wants=network.target
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=gameservers
|
||||
Environment="Q3RCON_PROXY=20000:28960;20001:28961;20002:28962"
|
||||
Environment="Q3RCON_HOST=0.0.0.0"
|
||||
Environment="Q3RCON_DEBUG=0"
|
||||
|
||||
ExecStart=/usr/local/bin/q3rcon-proxy
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -1,6 +1,8 @@
|
||||
package udpproxy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -8,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 createSession(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()
|
||||
@@ -33,12 +38,12 @@ func createSession(caddr *net.UDPAddr, raddr *net.UDPAddr, proxyConn *net.UDPCon
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *Session) listen() error {
|
||||
for {
|
||||
func (s *session) listen() error {
|
||||
buf := make([]byte, 2048)
|
||||
for {
|
||||
n, err := s.serverConn.Read(buf)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Error(err)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -46,29 +51,54 @@ 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())
|
||||
return err
|
||||
}
|
||||
|
||||
s.updateTime = time.Now()
|
||||
_, err := s.proxyConn.WriteToUDP(buf, s.caddr)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
|
||||
if s.isRconResponsePacket(buf) {
|
||||
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) {
|
||||
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
|
||||
}
|
||||
|
||||
s.updateTime = time.Now()
|
||||
_, err := s.serverConn.Write(buf)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Error(err)
|
||||
return err
|
||||
}
|
||||
|
||||
cmd := string(buf)
|
||||
if cmd[:8] == "\xff\xff\xff\xffrcon" {
|
||||
parts := strings.Split(cmd, " ")
|
||||
log.Info("From [", s.caddr.IP, "] To [", s.serverConn.RemoteAddr().String(), "] Command: ", strings.Join(parts[2:], " "))
|
||||
if s.isRconRequestPacket(buf) {
|
||||
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
|
||||
|
||||
41
pkg/udpproxy/sessioncache.go
Normal file
41
pkg/udpproxy/sessioncache.go
Normal 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)
|
||||
}
|
||||
@@ -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,16 +43,18 @@ func New(port, target string) (*Client, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Client{
|
||||
c := &Client{
|
||||
laddr: laddr,
|
||||
raddr: raddr,
|
||||
mutex: sync.RWMutex{},
|
||||
sessions: map[string]*Session{},
|
||||
}, nil
|
||||
}
|
||||
sessionCache: newSessionCache(),
|
||||
sessionTimeout: 20 * time.Minute,
|
||||
}
|
||||
|
||||
func (c *Client) isValidPacket(header []byte) bool {
|
||||
return string(header[:8]) == "\xff\xff\xff\xffrcon" || string(header[:13]) == "\xff\xff\xff\xffgetstatus" || string(header[:11]) == "\xff\xff\xff\xffgetinfo"
|
||||
for _, o := range options {
|
||||
o(c)
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListenAndServe() error {
|
||||
@@ -50,26 +66,22 @@ func (c *Client) ListenAndServe() error {
|
||||
|
||||
go c.pruneSessions()
|
||||
|
||||
for {
|
||||
buf := make([]byte, 2048)
|
||||
for {
|
||||
n, caddr, err := c.proxyConn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Error(err)
|
||||
}
|
||||
|
||||
if !c.isValidPacket(buf[:16]) {
|
||||
continue
|
||||
}
|
||||
|
||||
session, found := c.sessions[caddr.String()]
|
||||
if !found {
|
||||
session, err = createSession(caddr, c.raddr, c.proxyConn)
|
||||
session, ok := c.sessionCache.read(caddr.String())
|
||||
if !ok {
|
||||
session, err = newSession(caddr, c.raddr, c.proxyConn)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
log.Error(err)
|
||||
continue
|
||||
}
|
||||
|
||||
c.sessions[caddr.String()] = session
|
||||
c.sessionCache.insert(caddr.String(), session)
|
||||
}
|
||||
|
||||
go session.proxyTo(buf[:n])
|
||||
@@ -79,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
65
pkg/udpproxy/validator.go
Normal 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)
|
||||
}
|
||||
Reference in New Issue
Block a user