Skip to content

A guide on setting up a TF2 server with the best anti-DDoS, FastDL, SourceBans++, watchdog / heartbeat checker, auto updating, auto restarts, etc.

License

Notifications You must be signed in to change notification settings

felikcat/TF2-Server-Setup

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

40 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Background info

This guide is oriented towards security and minimalism.

You can use Steam Datagram Relay (SDR) to hide the server’s IP address, lower ping to players, and protect from DDoS attacks. This also allows for much cheaper hosting options, or self-hosting.
  • The downside: No consistent IP address or port, so players can’t bookmark the server or even find it in some cases.

  • Instructions for using SDR will be shown, but if your provider has a great anti-DDoS, don’t use it.

    • Good providers with great anti-DDoS; be sure to look for coupon / discount codes:

      • RoyaleHosting (not as fast as Pyro or Physgun’s CPU)

      • Pyro (might be better than Physgun in the future)

      • Physgun (ol' reliable for US and EU gaming VPSes)

      • Streamline Servers (cheaper than Gcore for Asia and South America; do not fall for their "free" FastDL, if you use it outside of their servers they will suspend your account)

      • NFOservers (used to be king, now they’re overpriced and dated)

      • Gcore (suitable for Asia and South America, expensive)

      • OVHcloud (GAME or Rise Game dedicated servers only, expensive)

For FastDL and SourceBans++, NFOServer’s web hosting is used for its unlimited traffic, reasonable max connection limits, and great DDoS protection. Avoid Physgun’s web hosting as they screw you over regarding the data usage, for example, they only allowed 5GB bandwidth initially as "fair usage" for their Starter plan.

TLD-list is what to use for finding who has the cheapest pricing for a domain. You can optionally have at least one domain to professionally host a game server.

0.5. Physgun VPS anti-DDoS setup

This is necessary for their VPS options to protect against DDoS attacks. Do not buy their game servers, they are overpriced.

  • Go to the Physgun VPS' (cloud.physgun.com) firewall portal, and create a new rule (in the Rules section, located on the left) with the following; be sure to change the IP Address to your game server:
    port punch

    • The web server IP is that of your NFOservers web host for FastDL (up to you to setup) & Sourcebans++ (which will be setup later).

  • Go to the "Filters" category, then click "Create Game Preset", put the IP address of your game server in (not the web server), then select HL2/Garry’s Mod Server, and put the port range from 27005 to 27020.

  • Click "Create Filter", put the IP address of your game server in, then select TCP Service (symmetric), and put the port as 22 (or your custom SSH port).

  • Go to the "Rules" category, click "Create Rule", put the IP address of your game server in, then Protocol: TCP, Name: Allow SSH, Action: Whitelist, and Destination Port: 22.

  • Click "Create Rule", put the IP address of your game server in, then Protocol: All (Port Punch), Name: Block all else, and Action: Deny; this will block all other ports except 27015 to 27020, and port 22.

1. (VPS only) Initial setup

  • Download and install Ubuntu Server LTS 24.04, or choose that as your image for hosting provider.

    • If installing manually / self-hosting:

      • Use the Minimized install and do not search for third-party drivers.

      • Do not setup the disk as an LVM group.

      • Install the OpenSSH server to access that server PC from your own PC through the local network (do not port forward port 22).

      • Do not install any snaps, they are shit.

      • After reboot, login and run ip a to see your local IP address. You can use that to login via SSH.

      • NOTE: If you’re using a laptop as a server, set HandleLidSwitchExternalPower=ignore in /etc/systemd/logind.conf; you can optionally set the other HandleLidSwitch options to ignore as well in case it’s running temporarily off the battery during a power outage or other event.
        Then run: sudo systemctl restart systemd-logind

2. (VPS only) Securing the server

Install sudo, and optionally nano (a text editor):
# apt install sudo nano

If the current user is root, make an administrator account instead to avoid mistakes. By default it’ll be a user, unprivileged, but can escalate to root via using sudo before a command:
# useradd -m -G sudo -s /bin/bash server

Setting up SSH key authentication:
  1. Use the 'server' user instead of 'root':
    # sudo -u server -i

  2. This will make the '/home/server/.ssh' directory:
    mkdir -p ~/.ssh

  3. If you already set an SSH Key via Physgun’s VPS panel or other means, copy the key to the 'server' user:
    exit
    # cp /root/.ssh/authorized_keys /home/server/.ssh/ && chown -R server: /home/server/.ssh

  4. If you used Bitwarden to generate the SSH key, put the Public Key into /home/server/.ssh/authorized_keys on the server.

Only skip these instructions if Bitwarden was used
  1. Run ssh-keygen on your local computer/PC, or alternatively generate an SSH key using Bitwarden. Use the default location unless you already have an SSH key there (in that case, put it elsewhere and remember it), then set the passphrase to something moderately complex using a password manager like Bitwarden (be sure to save it in there too). I recommend at least 30 characters long, lower & upper case characters with numbers, and no symbols.

  2. Include -i /DIRECTORY/TO/YOUR/id_ed25519.pub if you put a custom location and/or name (i.e. not id_ed25519.pub or id_rsa.pub):
    ssh-copy-id -p YOUR_SSH_PORT server@YOUR_SERVER_IP

    • On Windows, use PowerShell and do this instead: type C:\Users\$Env:UserName\.ssh\id_ed25519.pub | ssh -p YOUR_SSH_PORT server@YOUR_SERVER_IP 'cat >> ~/.ssh/authorized_keys'

  3. Check on the server to see if your key was installed successfully:
    cat ~/.ssh/authorized_keys

  4. Get the file contents of your id_ed25519 file (private key) along with the public key and put it into Bitwarden (or other password manager), as you never want to lose this SSH key.

Login with only the SSH key for the 'server' user, and if it works, proceed with the next hardening step.

Enforce SSH key login only:
sudo sed -i -E \
  -e 's/^#?PasswordAuthentication\s+.*/PasswordAuthentication no/' \
  -e 's/^#?ChallengeResponseAuthentication\s+.*/ChallengeResponseAuthentication no/' \
  /etc/ssh/sshd_config

sudo systemctl restart ssh

Set the password to something you can remember, but is also secure, so use a password manager to generate a 12 character length password:
# passwd server

Login to 'server' and test if sudo works (it should output → root):
sudo whoami

The 'server' user is now going to be used instead of using 'root' directly.

💡
irqbalance balances interrupts across CPU cores to handle high load more efficiently, which can prevent low networking performance.
AppArmor is to stop software from doing what they shouldn’t, hence better security.
auditd is to allow viewing AppArmor logs, but also installing auditd allows AppArmor profiles to be created by you.
Unattended upgrades is so you don’t accidentally forget to update packages, which would cause security issues.
apt-transport-https is to allow apt to operate over HTTPS to prevent security flaws such as RCEs.

sudo apt update && sudo apt install -y irqbalance apparmor apparmor-utils auditd unattended-upgrades apt-listchanges apt-transport-https

Update the server, be sure to "keep the local version currently installed" whenever possible:
sudo apt upgrade

Reboot if all went well with the apt upgrade:
sudo reboot

Setting up kernel hotpatching support, to update the kernel automatically without rebooting, and hardening with CIS level 1.
  1. sudo apt install -y ubuntu-advantage-tools

  2. You have to make an Ubuntu Pro account to use Ubuntu Pro’s functionality, then run:
    sudo ua attach

  3. sudo pro enable usg && sudo apt install usg

  4. Don’t reboot when it tells you to do so, yet:
    sudo usg fix cis_level1_server

Enforce the repositories to use HTTPS:
sudo sed -i 's/http:\/\//https:\/\//g' /etc/apt/sources.list.d/ubunt*.sources

Ensure security updates are automatically downloaded and installed:
sudo dpkg-reconfigure unattended-upgrades

Sudo edit /etc/fstab and add "noatime" to the ext4 or XFS partition:
Fstab configuration with noatime

AIDE is a useful intrusion detection system, but for our needs it won’t be used, and may end up needlessly using a lot of CPU:
sudo apt remove -y aide

Reboot to complete the USG fix process:
sudo reboot

3. (VPS only) Setting up cm2network/tf2, a Docker image for TF2 server hosting

  • Follow the official instructions to install Docker using the apt repository.

  • Make the 2fort (or whatever type of server you plan on) directory.
    mkdir -p ~/2fort && cd ~/2fort

  • Read here on what the environment variables in the docker-compose.yml file mean, such as SRCDS_TOKEN.

  • Edit: docker-compose.yml

services:
  tf2:
    # Allocates a stdin (docker run -i)
    stdin_open: true
    # Allocates a tty (docker run -t)
    tty: true
    # Max CPUs to allocate, float, so e.g. 3.5 can be set.
    cpus: 2
    # Specific CPUs to allocate, 0-3 is first 4 CPUs, "0,1,2,3" can be used as well
    # Ensure these are pinned to P-cores if using an Intel CPU with P and E-cores
    cpuset: 0-1
    # Use the host network, RECOMMENDED.
    network_mode: host
    # Binds /srv/tf2-dir to /home/steam/tf-dedicated in the container
    # Usually you can share the same sourcemod directory with other servers, if you can't, change '/srv/tf2-dir' to something like '/srv/tf2-dir-2'
    volumes:
      - /srv/tf2-dir:/home/steam/tf-dedicated
    # Rename the container_name to something like 'tf2-dedicated-mge' if running multiple servers
    container_name: tf2-dedicated
    environment:
      SRCDS_TOKEN: "0123456789DEADB33F"
      SRCDS_PW: ""
      SRCDS_PORT: "27015"
      SRCDS_MAXPLAYERS: "24"
      SRCDS_STARTMAP: "ctf_2fort"
      SRCDS_CFG: "server_2fort.cfg"
      # Only if you have great DDoS protection: set this to "0"
      SRCDS_SDR_FAKEIP: "1"
      # 1 = VAC secured
      SRCDS_SECURED: "0"
      # Rest of your env vars...
    image: cm2network/tf2:sourcemod-x64
  • Create the directory that the TF2 server will use and set the correct permissions:
    sudo mkdir -p /srv/tf2-dir && sudo chown -R 1000:1000 /srv/tf2-dir

  • We want to ensure the server is fully working before running it as a daemon; press Ctrl+c when the server is successfully ran and you did a test connection to it through TF2:
    sudo docker compose up

4. Setting up a TF2 server’s configs & plugins

ℹ️
MGE is used as an example, however these instructions work for other types of servers too.
- Keep in mind that you want the map to change at least every 35 minutes (mp_timelimit 35) to prevent the server from "lagging", which is likely due to TF2’s math precision bugs.
- The directories will be different if you were not using the VPS instructions, adapt accordingly.

nano /srv/tf2-dir/tf/cfg/server_mge.cfg

// Please do NOT set RCON here, use SRCDS_RCONPW in the Docker Compose file instead.

// General Settings //

// Hostname for server.
// This name will appear in the server list.
hostname "Example MGE server"

// Control where the client gets content from
// 0 = anywhere, 1 = anywhere listed in white list, 2 = steam official content only
sv_pure -1

// Disallow sprays
sv_allowupload 0

sv_tags "mge,and,your,other,tags,here"

mapcyclefile mapcycle_mge.txt


// Region //


// The region of the world to report this server in.
// -1 is the world, 0 is USA east coast, 1 is USA west coast
// 2 south america, 3 europe, 4 asia, 5 australia, 6 middle east, 7 africa
sv_region -1


// Rcon Settings //

// Number of minutes to ban users who fail rcon authentication
sv_rcon_banpenalty 1440

// Max number of times a user can fail rcon authentication before being banned
sv_rcon_maxfailures 5


/////////////////////
// Gameplay CVars //
///////////////////

// Maximum number of rounds to play before server changes maps
mp_maxrounds 5

// Team Balancing //

// Enable team balancing
mp_autoteambalance 1

// Time after the teams become unbalanced to attempt to switch players.
mp_autoteambalance_delay 60

// Time after the teams become unbalanced to print a balance warning
mp_autoteambalance_warning_delay 30

// Teams are unbalanced when one team has this many more players than the other team. (0 disables check)
mp_teams_unbalance_limit 1



// Round and Game Times //

// Enable timers to wait between rounds. WARNING: Setting this to 0 has been known to cause a bug with setup times lasting 5:20 (5 minutes 20 seconds) on some servers!
mp_enableroundwaittime 1

// Time after round win until round restarts
mp_bonusroundtime 8

// If non-zero, the current round will restart in the specified number of seconds
mp_restartround 0

// Enable sudden death
mp_stalemate_enable 1

// Timelimit (in seconds) of the stalemate round.
mp_stalemate_timelimit 300

// Game time per map in minutes
mp_timelimit 35



// Client CVars //

// Restricts spectator modes for dead players
mp_forcecamera 0

// Toggles whether the server allows spectator mode or not
mp_allowspectators 1

// Toggles footstep sounds
mp_footsteps 1

// Toggles game cheats
sv_cheats 0

// After this many seconds without a message from a client, the client is dropped
sv_timeout 900

// Maximum time a player is allowed to be idle (in minutes), made this and sv_timeout equal same time?
mp_idlemaxtime 15

// Deals with idle players 1=send to spectator 2=kick
mp_idledealmethod 1

// Time (seconds) between decal sprays
decalfrequency 30


// Communications //

// enable voice communications
sv_voiceenable 1

// Players can hear all other players, no team restrictions 0=off 1=on
sv_alltalk 1

// Amount of time players can chat after the game is over
mp_chattime 10

// Enable party mode
tf_birthday 0


// Logging Settings //
log on
sv_log_onefile 1
sv_logfile 1
sv_logbans 1
sv_logecho 1


// Execute Banned Users //
exec banned_user.cfg
exec banned_ip.cfg
writeid
writeip

5. Setting up SourceBans++

  • Log in to the NFOServers control panel, and go to your website.

  • Go to "Databases" and add a new database with the prefix "sb", then check "Allow external connections" and click "Submit changes".

  • Go to "File manager" and find the hostname, username, and password to login to the web server using SSH (you can optionally use SFTP later on).

  • cd ~/public && wget https://github.com/sbpp/sourcebans-pp/releases/download/1.7.0/sourcebans-pp-1.7.0.webpanel-only.tar.gz

  • tar -xvf sourcebans-pp-1.7.0.webpanel-only.tar.gz && mv sourcebans-pp-1.7.0.webpanel-only sourcebans && rm sourcebans-pp-1.7.0.webpanel-only.tar.gz

  • Follow the official installation instructions (don’t scroll up, those instructions are meant to be skipped).

    • http://example.site.nfoservers.com/sourcebans/install is the correct URL for installing SourceBans++, be sure to change 'example' to your web server name or custom domain.

    • MySQL is codeword for your database, keep that in mind.

    • Use "localhost" for the Server Hostname.

    • Ensure the "host" for /tf/addons/sourcemod/configs/databases.cfg on your game server(s) is set to the IP address (not web domain) of your web server, as the database won’t be hosted on the game server(s).

    • nfoservers db
      sb database

    • After the SourceBans++ install is complete and it tells you to delete the 'install' directory, run this command:
      rm -r ~/public/sourcebans/{install,updater}

Setting up FastDL for an MGE server

This continues on past SourceBans++, I assume you’ll use both.

Managing TF2 servers

List all running Docker containers:
sudo docker ps

Show logs for the 'tf2-dedicated' container:
sudo docker logs tf2-dedicated

Enter the terminal / shell of said container, allowing you to type in and run commands on the TF2 server.
NOTE: Do not press Ctrl+c while attached, it will kill the server; press Ctrl+p then Ctrl+q instead:
sudo docker attach tf2-dedicated

About

A guide on setting up a TF2 server with the best anti-DDoS, FastDL, SourceBans++, watchdog / heartbeat checker, auto updating, auto restarts, etc.

Topics

Resources

License

Stars

Watchers

Forks