11 Commits

Author SHA1 Message Date
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
7 changed files with 158 additions and 77 deletions

4
.gitignore vendored
View File

@@ -19,3 +19,7 @@
# Go workspace file
go.work
# testing
run.sh
server.yaml

View File

@@ -2,6 +2,10 @@
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`
@@ -16,9 +20,11 @@ This would configure q3rcon-proxy to run 3 proxy servers listening on ports `200
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

View File

@@ -3,21 +3,56 @@ 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) {
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))
}
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"
}
staleTimeout, err := getEnvInt("Q3RCON_STALE_SESSION_TIMEOUT")
if err != nil {
log.Fatalf("unable to parse Q3RCON_STALE_SESSION_TIMEOUT: %s", err.Error())
}
for _, proxy := range strings.Split(proxies, ";") {
go start(host, proxy, staleTimeout)
}
<-make(chan int)
}
func start(host, proxy string, staleTimeout int) {
port, target := func() (string, string) {
x := strings.Split(proxy, ":")
return x[0], x[1]
}()
c, err := udpproxy.New(fmt.Sprintf("%s:%s", host, port), fmt.Sprintf("127.0.0.1:%s", target))
c, err := udpproxy.New(
fmt.Sprintf("%s:%s", host, port),
fmt.Sprintf("127.0.0.1:%s", target),
udpproxy.WithStaleTimeout(time.Duration(staleTimeout)*time.Minute))
if err != nil {
log.Fatal(err)
}
@@ -26,51 +61,3 @@ func start(proxy string) {
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
}

View File

@@ -2,6 +2,7 @@ package udpproxy
import (
"errors"
"fmt"
"net"
"strings"
"time"
@@ -29,6 +30,7 @@ func newSession(caddr *net.UDPAddr, raddr *net.UDPAddr, proxyConn *net.UDPConn)
proxyConn: proxyConn,
caddr: caddr,
updateTime: time.Now(),
validator: newValidator(),
}
go session.listen()
@@ -37,8 +39,8 @@ func newSession(caddr *net.UDPAddr, raddr *net.UDPAddr, proxyConn *net.UDPConn)
}
func (s *session) listen() error {
for {
buf := make([]byte, 2048)
for {
n, err := s.serverConn.Read(buf)
if err != nil {
log.Error(err)
@@ -67,7 +69,7 @@ func (s *session) proxyFrom(buf []byte) error {
if s.isBadRconResponse(buf) {
log.Infof("Response: Bad rcon from %s", s.caddr.IP)
} else {
log.Debugf("Response: %s", string(buf[10:]))
log.Debugf("Response: %s", string(buf[len(s.rconResponseHeader):]))
}
}
@@ -76,7 +78,13 @@ func (s *session) proxyFrom(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
}
@@ -89,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

@@ -8,6 +8,21 @@ import (
log "github.com/sirupsen/logrus"
)
// Option is a functional option type that allows us to configure the Client.
type Option func(*Client)
// WithStaleTimeout is a functional option to set the stale session timeout
func WithStaleTimeout(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 5 minutes")
return
}
c.timeout = timeout
}
}
type Client struct {
laddr *net.UDPAddr
raddr *net.UDPAddr
@@ -16,9 +31,11 @@ type Client struct {
mutex sync.RWMutex
sessions map[string]*session
timeout time.Duration
}
func New(port, target string) (*Client, error) {
func New(port, target string, options ...Option) (*Client, error) {
laddr, err := net.ResolveUDPAddr("udp", port)
if err != nil {
return nil, err
@@ -29,12 +46,19 @@ 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
timeout: 5 * time.Minute,
}
for _, o := range options {
o(c)
}
return c, nil
}
func (c *Client) ListenAndServe() error {
@@ -46,15 +70,15 @@ 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.Error(err)
}
session, found := c.sessions[caddr.String()]
if !found {
session, ok := c.sessions[caddr.String()]
if !ok {
session, err = newSession(caddr, c.raddr, c.proxyConn)
if err != nil {
log.Error(err)
@@ -76,8 +100,9 @@ func (c *Client) pruneSessions() {
for range ticker.C {
for _, session := range c.sessions {
c.mutex.RLock()
if time.Since(session.updateTime) > time.Minute*5 {
if time.Since(session.updateTime) > c.timeout {
delete(c.sessions, session.caddr.String())
log.Tracef("session for %s deleted", session.caddr)
}
c.mutex.RUnlock()
}

View File

@@ -1,32 +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 (v *validator) isRconRequestPacket(buf []byte) bool {
return string(buf[:8]) == "\xff\xff\xff\xffrcon"
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) isQueryRequestPacket(buf []byte) bool {
return string(buf[:13]) == "\xff\xff\xff\xffgetstatus" || string(buf[:11]) == "\xff\xff\xff\xffgetinfo"
func (v validator) compare(buf, c []byte) bool {
return bytes.Equal(buf[:len(c)], c)
}
func (v *validator) isValidRequestPacket(buf []byte) bool {
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) isRconResponsePacket(buf []byte) bool {
return string(buf[:9]) == "\xff\xff\xff\xffprint"
func (v validator) isChallengeRequestPacket(buf []byte) bool {
return v.compare(buf, v.getchallengeRequestHeader)
}
func (v *validator) isQueryResponsePacket(buf []byte) bool {
return string(buf[:18]) == "\xff\xff\xff\xffstatusResponse" || string(buf[:16]) == "\xff\xff\xff\xffinfoResponse"
func (v validator) isRconResponsePacket(buf []byte) bool {
return v.compare(buf, v.rconResponseHeader)
}
func (v *validator) isValidResponsePacket(buf []byte) bool {
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 string(buf[10:18]) == "Bad rcon"
func (v validator) isBadRconResponse(buf []byte) bool {
return v.compare(buf[len(v.rconResponseHeader):], v.badRconIdentifier)
}