Security and Authentication

Hash Tables

  • Explanation of Hash Tables .

    • "The memory location where the value will go (index) is determined by the value of the object itself."

    • Great video.

  • Conflict resolution :

    • Best case (no collisions):

      • $O(1)$.

    • 'Open addressing' techniques:

      • Linear Probing.

        • Worst case:

          • $O(n)$.

      • Quadratic Probing.

        • Worst case:

          • $O(?)$.

    • 'Closed addressing' techniques:

      • Linked List (Chained List).

Token Authentication

  • My interpretation :

    • The Token is the access key for the connection between the Client and the GameServer. The Client verifies its credentials with the GatewayServer -> AuthenticationServer just to obtain a Token that will be accepted by the GameServer.

    • Upon successful authentication, the Client and the GameServer receive the same Token, so the connection can only be established between the two if there is a match.

    • This extra security layer is for the case the Client tries to connect to the GameServer without confirming its credential.

      • Supposedly this could happen if the Client manages to call the connection functions to the GameServer via "recompile" of the code, who knows.

  • Allows players to stay connected without sending their credentials (username and password) for every action in the game.

  • Login flow:

    • The player logs in with credentials. The server validates the information.

    • After successful verification, the server issues a token (like a JWT - JSON Web Token), representing the player's identity and some permissions.

    • This token is sent to the client (the player's device) and temporarily stored (in memory or local storage).

    • For each interaction with the server (requesting game progress, buying items, etc.), the client sends the token instead of the credentials.

  • Advantages:

    • Session and Logout Control:

      • Token expiration also allows stricter session control. If the player disconnects from a session or changes devices, an expired token can prevent the player from being considered "logged in" in multiple locations simultaneously, which can cause conflicts in online games.

      • This allows developers to "end" an active session in case of suspicious activity or in response to a player logout request.

  • Duration:

    • In games, tokens commonly last between 1 to 12 hours, allowing the player to have a continuous session without needing to re-login. This provides security without compromising user experience.

  • Alternatives to Token Authentication:

    • Login Session with Cookies:

      • Common in websites and some web apps, where the server stores each user's session and identifies them via cookies.

      • In online games, especially MMOs, maintaining sessions at scale can be complicated and resource-intensive, making it less scalable than token authentication.

    • Constant Credential Resending:

      • The client would send credentials (username and password) for each new request.

      • This exposes credentials to more interception attacks and is insecure, especially on unstable networks. Each new request represents a risk of credential capture, increasing system vulnerability.

    • Certificate-based Authentication:

      • In some critical applications, digital certificates are used for mutual authentication, where both the client and server have private keys.

      • It is secure, but very complex to implement in games and difficult to manage for each player, especially in amateur or smaller-scale games.

  • Token creation and verification .

    • Random number -> convert to String with sha256 -> unix_time as String -> concatenate the two strings (just put one in front of the other).

      • The 'unix_time' is based on the user's computer date, which may be questionable.

    • {~13:50}

      • Token verification process, via comparing the current time and the clock concatenated at the end of the Token; if greater than 30 (seconds), the Token is removed from the "expected Tokens" list.

    • Once the Token is used to login, it is removed from the 'expected Tokens' list.

Authentication Server

  • In GameDev:

    • Defined in a separate project.

  • Responsible for verifying credentials and issuing tokens. In games, it acts as the "security gatekeeper."

  • Login process (without the Gateway):

    • The player opens the game and sends credentials to the authentication server.

    • The server checks the password hash and salt in the database to confirm the player's identity.

    • If everything is correct, the authentication server generates a token and returns it to the client.

    • This token is used in subsequent client communications with the game server.

Gateway

  • In GameDev:

    • Defined in a separate project.

  • Acts as an intermediary between the client (player's device) and the game servers. It acts as a "gate," facilitating communication and protecting main servers from direct access, while providing centralized traffic and security control.

  • Purposes

    • Security against attacks:

      • The gateway is the first point of contact for all client requests. This allows it to filter suspicious or malicious traffic before it reaches main game servers.

      • It can block common attacks like DDoS (many requests sent to overload the system) and code injection attacks (hackers inserting malicious code).

      • In some systems, it also checks authentication tokens, ensuring only authenticated players access game features.

    • Authentication Server Security:

      • The gateway works with the authentication server: it receives initial login requests and forwards them to the authentication server. Once the player is authenticated, the gateway can redirect the request to the correct game server.

      • This adds an extra protection layer since the authentication server is never directly exposed to clients.

    • Encryption:

      • The gateway is responsible for implementing and managing connection encryption. It ensures all communication between client and servers is secure, using protocols like HTTPS or TLS (Transport Layer Security).

      • This means that even if an attacker intercepts the communication, they cannot read the data due to encryption.

    • Load Balancing

      • As online games attract many players simultaneously, the gateway can act as a load balancer, distributing requests across servers evenly, avoiding overload.

      • The gateway ensures all player connections flow smoothly and the system continues to work even under heavy load.

    • Monitoring:

      • As the gateway receives all player requests, it serves as a central point to monitor and log traffic. Useful for developers to analyze usage patterns, detect errors, and suspicious activity.

      • It also allows the security team to quickly identify unusual behaviors, like login spikes or unusual activity, and take preventive measures.

  • Login process:

    • The player opens the game and enters credentials.

    • The client (game app) sends the login request to the gateway.

    • The gateway redirects the request to the authentication server, which verifies credentials.

    • After authentication, the server issues a token and the gateway sends it back to the client.

    • With the token, the client sends a new request (e.g., to start a match) to the gateway.

    • The gateway verifies the token and, if valid, redirects the request to the correct game server.

  • "Initially, a Gateway may not be necessary. For a small MMO, you can manage traffic directly with the game server and authentication server. If the game grows and requires multiple servers, the gateway becomes very useful for load balancing and security."

Local Network

  • Yes, you can connect the GameServer , GatewayServer , and AuthenticationServer  all on the same local network, and this is common practice for MMOs and other online games requiring fast and secure communication between different server components. This setup benefits from reduced latency, security, and simplicity.

  • Recommended to do so. There are significant advantages to managing everything within the same internal network. It's safer.

  • Complications:

    • Local Network Bottleneck :

      • Depending on the number of players, traffic may overload the local network. Ensure the infrastructure (routers and switches) supports the required load.

    • Single Point of Failure Dependency :

      • With all servers on the same network, a failure in the local network infrastructure can affect all of them. Redundancy for the network and backups for each server can mitigate this.

  • Keeping GameServer , GatewayServer , and AuthenticationServer  on a single machine can be viable, especially considering an initial number of 10 players.

TLS (Transport Layer Security), SSL (Secure Sockets Layer) and DTLS

TLS
  • SSL is a security protocol designed to ensure secure communication on the internet, mainly between browsers and servers.

  • It creates an encrypted connection that protects transmitted data, preventing third parties from intercepting or altering the information.

  • When you access a website using SSL (indicated by "https://" in the URL), the server presents an SSL certificate issued by a trusted certificate authority (such as VeriSign, DigiCert). The browser verifies the validity of this certificate before establishing the connection.

  • In addition to encrypting and authenticating, SSL also ensures that data has not been altered or corrupted during transit. It uses functions called hashes to verify data integrity.

  • A website using SSL displays a padlock in the browser and uses "https://" instead of "http://".

  • Characteristics :

    • TLS uses TCP:

      • TCP is a connection-oriented protocol, ensuring the order and delivery of all packets. If a packet is lost, TCP automatically attempts to retransmit it and puts the packets in the correct order for the application.

TLS vs SSL
  • The most current and secure version of the protocol is TLS, which is an evolution of SSL and provides greater security and efficiency.

  • Nowadays, most secure communications on the internet use TLS, but the term "SSL" continues to be used as a general reference.

DTLS (Datagram Transport Layer Security)
  • It is a version of the TLS (Transport Layer Security) protocol, but for UDP (User Datagram Protocol).

  • It is mainly used in network applications that require secure communication, but where speed and low latency are priorities, such as voice and video calls, online games , and streaming.

  • Main Features of DTLS :

    • Low-latency security : DTLS allows fast and secure communication without the delivery and ordering guarantees of TCP, which is essential for real-time applications.

    • Connection independence : Since UDP does not establish a formal "connection," DTLS must also handle sessions securely even without the guaranteed connection steps of TCP.

    • Optional retransmission support : DTLS tries to retransmit important data (such as parts of the initial handshake) if packet loss compromises the authentication process, but this retransmission is limited since UDP's priority is to minimize latency.

  • Generating an X509 Certificate for the DTLS Security Protocol in Godot .

    • A .crt file (certificate) and a .key file (encryption key) are generated.

    • The certificate is created and used during the Client-to-Server connection process.

  • Usage in Godot 4 with ENetMultiplayerPeer :

    • Server:

    const _certificado_x509 : X509Certificate = preload('res://certificados/X509_certificado.crt')
    const _key : CryptoKey = preload('res://certificados/X509_key.key')
    
    func _criar_servidor_gateway() -> Error:
        var peer := ENetMultiplayerPeer.new()
        var erro : Error = peer.create_server(_PORTA_GATEWAY, _CONEXOES_MAXIMAS)
        if erro:
            return erro
            
        peer.get_host().dtls_server_setup(TLSOptions.server(_key, _certificado_x509))
            
        get_tree().set_multiplayer(_servidor_gateway, get_path())
        _servidor_gateway.set_multiplayer_peer(peer)
    
        return OK
    
    • Client:

    const _certificado_x509 : X509Certificate = preload('res://certificados/X509_certificado.crt')
    
    func entrar_no_servidor_gateway() -> Error: 
        var peer := ENetMultiplayerPeer.new()
        var erro := peer.create_client(_SERVER_IP_DEFAULT, _PORTA_GATEWAY)
        if erro:
            return erro
            
        peer.get_host().dtls_client_setup(_SERVER_IP_DEFAULT, TLSOptions.client_unsafe(_certificado_x509))
            
        get_tree().set_multiplayer(_servidor_gateway, get_path())
        _servidor_gateway.set_multiplayer_peer(peer)
            
        return OK
    
    • Tested and works 100%.

      • If you use TLSOptions.client()  instead of TLSOptions.client_unsafe() , errors occur and the connection is not established, as expected.

      • If the certificate differs between Client and Server, errors occur and the connection is not established, as expected.

X.509 Certificate
  • An X.509 certificate is a requirement for TLS/SSL protocols.

  • It is a type of digital certificate that follows a widely used standard to authenticate and establish secure connections in communication systems, such as in Public Key Infrastructure (PKI). It is crucial to ensure data security and the authenticity of online identities, especially in protocols like TLS/SSL , used for secure HTTPS connections.

  • The relationship between X.509 and DTLS lies in the USE  of digital certificates (X.509) as part of the authentication and encryption process in secure connections established with DTLS.

.crt File
  • A .crt file is a type of file that contains a digital certificate, usually in the X.509  format.

OAuth (Open Authorization)

OAuth vs Auth0
  • OAuth (Open Authorization) is an authorization protocol that allows you to grant access to protected resources on a server (for example, accessing information from a Google or Facebook account) without sharing your credentials (such as username and password). It is widely used to delegate permissions securely between different systems.

    • Example: When using Google or Facebook login on a website, OAuth enables this authentication.

  • Auth0 is an identity-as-a-service platform that provides complete authentication and authorization solutions. It can be used to implement protocols like OAuth , OpenID Connect, SAML, among others, but Auth0 is a complete solution  that abstracts and simplifies authentication and authorization implementation.