Skip to content

Security Best Practices Guide

Overview

This document introduces security best practices in HttpServer development, including input validation, SQL injection prevention, XSS protection, CSRF protection, etc.

Input Validation

Parameter Validation Middleware

vb
' cValidationMiddleware.cls
Option Explicit

Public Sub Entry(ctx As cHttpServerContext)
    Dim rules As Dictionary
    Set rules = GetValidationRules(ctx.Request.PathInfo)

    If Not rules Is Nothing Then
        Dim field As Variant
        Dim errors As String
        errors = ""

        For Each field In rules.Keys
            Dim value As String
            value = ctx.Request(field)

            ' Required check
            If rules(field)("required") And value = "" Then
                errors = errors & field & " cannot be empty; "
            End If

            ' Type check
            If rules(field)("type") = "number" And value <> "" Then
                If Not IsNumeric(value) Then
                    errors = errors & field & " must be a number; "
                End If
            End If

            ' Length check
            If rules(field).Exists("maxLength") Then
                If Len(value) > rules(field)("maxLength") Then
                    errors = errors & field & " length cannot exceed " & rules(field)("maxLength") & "; "
                End If
            End If
        Next

        If errors <> "" Then
            ctx.Response.State400 "Parameter error: " & errors
            ctx.fIsAbort = True
        End If
    End If
End Sub

Private Function GetValidationRules(path As String) As Dictionary
    Set GetValidationRules = Nothing

    Dim rules As New Dictionary

    Select Case path
        Case "/api/users/create"
            Dim userRules As New Dictionary
            userRules("required") = True
            userRules("type") = "string"
            userRules("maxLength") = 50
            rules("username") = userRules

            Dim emailRules As New Dictionary
            emailRules("required") = True
            emailRules("type") = "email"
            rules("email") = emailRules

            Set GetValidationRules = rules
    End Select
End Function

SQL Injection Prevention

Wrong Example

vb
' Dangerous! Direct SQL concatenation
Dim sql As String
sql = "SELECT * FROM users WHERE username='" & ctx.Request("username") & "'"

Correct Approach: Parameterized Query

vb
' Safe: Using parameterized query
If ctx.Db.Sql("SELECT * FROM users WHERE username=?") _
    .Param("username", ctx.Request("username"), adVarChar) _
    .Fetch Then
    ' ...
End If

Input Filtering Helper

vb
' Filter dangerous characters
Public Function SqlSafe(input As String) As String
    Dim result As String
    result = input
    result = Replace(result, "'", "''")  ' Escape single quote
    result = Replace(result, ";", "")   ' Remove semicolon
    result = Replace(result, "--", "")  ' Remove comment
    SqlSafe = result
End Function

XSS Protection

HTML Encoding Output

vb
' cSecurityUtils.bas

Public Function HtmlEncode(text As String) As String
    Dim result As String
    result = text
    result = Replace(result, "&", "&amp;")
    result = Replace(result, "<", "&lt;")
    result = Replace(result, ">", "&gt;")
    result = Replace(result, """", "&quot;")
    result = Replace(result, "'", "&#x27;")
    HtmlEncode = result
End Function

' Usage in controller
Public Sub Search(ctx As cHttpServerContext)
    Dim keyword As String
    keyword = ctx.Request.QueryString("q")

    ' Encode before output
    ctx.Response.Html "<p>Search results: " & HtmlEncode(keyword) & "</p>"
End Sub
vb
' Set secure session cookie
With ctx.Cookies.Cookie("SESSIONID")
    .Value = ctx.Session.SessionID
    .HttpOnly = True   ' Disable JavaScript access
    .Secure = True     ' HTTPS only
    .SameSite = "Strict"
End With

CSRF Protection

Token Verification

vb
' cCsrfMiddleware.cls
Option Explicit

Public Sub Entry(ctx As cHttpServerContext)
    ' Only verify data-modifying requests
    If ctx.Request.Method <> ReqGet And _
       ctx.Request.Method <> ReqOptions Then

        Dim token As String
        token = ctx.Request.Header("X-CSRF-Token")

        If token = "" Then
            token = ctx.Request.Form("_csrf")
        End If

        ' Verify token
        If token <> ctx.Session("csrf_token") Then
            ctx.Response.State403 "CSRF Token invalid"
            ctx.fIsAbort = True
        End If
    End If
End Sub

Token Generation

vb
' Generate CSRF token on login
Public Sub Login(ctx As cHttpServerContext)
    ' ... Validate credentials ...

    ' Generate random token
    ctx.Session("csrf_token") = GenerateRandomToken()

    ' Return to client
    Dim result As New Dictionary
    result("csrf_token") = ctx.Session("csrf_token")
    ctx.Response.Json result
End Sub

Private Function GenerateRandomToken() As String
    ' Use GUID as token
    GenerateRandomToken = Replace(ToolsStr.GetGUID(False), "-", "")
End Function

Password Security

Password Hashing

vb
' Use bcrypt or similar algorithm
Public Function HashPassword(password As String) As String
    ' Use bcrypt in real projects
    ' This demonstrates basic hash + salt
    Dim salt As String
    salt = GenerateSalt()

    HashPassword = salt & "$" & SHA256(salt & password)
End Function

Public Function VerifyPassword(password As String, hashed As String) As Boolean
    Dim parts() As String
    parts = Split(hashed, "$")

    If UBound(parts) = 1 Then
        Dim salt As String
        salt = parts(0)

        VerifyPassword = (SHA256(salt & password) = parts(1))
    End If
End Function

Rate Limiting

vb
' cRateLimitMiddleware.cls (complete version)
Option Explicit

Dim RequestLog As Dictionary  ' IP -> Request record
Dim BlockList As Dictionary   ' IP -> Unblock time

Private Sub Class_Initialize()
    Set RequestLog = New Dictionary
    Set BlockList = New Dictionary
End Sub

Public Sub Entry(ctx As cHttpServerContext)
    Dim ip As String
    ip = ctx.ClientInfo.IP

    ' Check if in blacklist
    If BlockList.Exists(ip) Then
        If Now < BlockList(ip) Then
            ctx.Response.State403 "IP blocked, try again in " & DateDiff("n", Now, BlockList(ip)) & " minutes"
            ctx.fIsAbort = True
            Exit Sub
        Else
            BlockList.Remove ip
        End If
    End If

    ' Get/create request record
    If Not RequestLog.Exists(ip) Then
        Dim record As New Dictionary
        record("count") = 0
        record("startTime") = Now
        record("urls") = New Dictionary
        Set RequestLog(ip) = record
    End If

    Dim rec As Dictionary
    Set rec = RequestLog(ip)

    ' Reset if more than 1 minute
    If DateDiff("n", rec("startTime"), Now) >= 1 Then
        rec("count") = 0
        rec("startTime") = Now
        Set rec("urls") = New Dictionary
    End If

    ' Count
    rec("count") = rec("count") + 1

    Dim urls As Dictionary
    Set urls = rec("urls")
    urls(ctx.Request.PathInfo) = urls.Exists(ctx.Request.PathInfo) + 1

    ' Check limit
    If rec("count") > 100 Then  ' 100 per minute
        BlockList(ip) = DateAdd("n", 10, Now)  ' Block for 10 minutes
        ctx.Response.State429 "Too many requests, IP has been blocked"
        ctx.fIsAbort = True
        Exit Sub
    End If

    ' Single URL rate check
    If urls(ctx.Request.PathInfo) > 30 Then  ' 30 per minute per URL
        BlockList(ip) = DateAdd("n", 5, Now)
        ctx.Response.State429 "This endpoint has too many requests"
        ctx.fIsAbort = True
    End If
End Sub

Security Headers

vb
' cSecurityHeadersMiddleware.cls
Option Explicit

Public Sub Entry(ctx As cHttpServerContext)
    ' HSTS (Force HTTPS)
    ctx.Response.Header("Strict-Transport-Security") = "max-age=31536000; includeSubDomains"

    ' Prevent clickjacking
    ctx.Response.Header("X-Frame-Options") = "DENY"

    ' XSS protection
    ctx.Response.Header("X-Content-Type-Options") = "nosniff"
    ctx.Response.Header("X-XSS-Protection") = "1; mode=block"

    ' Content Security Policy
    ctx.Response.Header("Content-Security-Policy") = _
        "default-src 'self'; " & _
        "script-src 'self' 'unsafe-inline'; " & _
        "style-src 'self' 'unsafe-inline';"

    ' Referrer Policy
    ctx.Response.Header("Referrer-Policy") = "strict-origin-when-cross-origin"
End Sub

Logging Security

vb
' cSecurityLogMiddleware.cls
Option Explicit

Public Sub Entry(ctx As cHttpServerContext)
    ' Log sensitive operations
    If IsSensitiveOperation(ctx.Request.PathInfo) Then
        Dim log As String
        log = Now & " | " & _
              ctx.ClientInfo.IP & " | " & _
              ctx.Request.MethodName & " | " & _
              ctx.Request.PathInfo & " | " & _
              ctx.Session("user_id")

        Call WriteSecurityLog(log)
    End If
End Sub

Private Function IsSensitiveOperation(path As String) As Boolean
    IsSensitiveOperation = (InStr(path, "/login") > 0 Or _
                           InStr(path, "/password") > 0 Or _
                           InStr(path, "/delete") > 0 Or _
                           InStr(path, "/admin") > 0)
End Function

Private Sub WriteSecurityLog(msg As String)
    Dim f As Integer
    f = FreeFile
    Open "C:\Logs\security.log" For Append As #f
    Print #f, msg
    Close #f
End Sub

Request Body Size Limit

MaxRequestSize Configuration

Prevents malicious clients from sending oversized request bodies that could cause server OOM crashes.

vb
' Configure before starting
Server.MaxRequestSize = 5242880  ' 5MB

' When exceeded, connection is automatically closed and logged
' Client receives 413 Payload Too Large response

Description: Default 10MB. Adjust based on business needs:

  • Pure API services: 1-5MB
  • File upload support: Set based on maximum file size

Maximum Connection Limit

vb
Server.MaxConnections = 500  ' Max 500 simultaneous connections

Description: Default 1000. When exceeded, new connections are rejected and OnLogs event records a WARN log.


Security Configuration Checklist

Check ItemStatusDescription
Force HTTPSProduction must use HTTPS
Parameterized QueryAll database operations use parameterized
XSS FilteringEncode HTML in output
CSRF TokenVerify CSRF token on modifications
HttpOnly CookieSession cookie with HttpOnly
Secure CookieSet Secure in HTTPS environment
Password HashingUse bcrypt or secure algorithm
Rate LimitingLimit endpoint request frequency
Security HeadersAdd X-Frame-Options etc.
LoggingLog sensitive operations and security events
Request Body Size LimitConfigure MaxRequestSize to prevent OOM
Connection LimitConfigure MaxConnections to prevent resource exhaustion
Idle Connection TimeoutConfigure IdleTimeoutSeconds to clean zombie connections
Session Auto CleanupBuilt-in timer auto cleans expired sessions, or manually call CleanupExpiredSessions
SSE Client ReleaseCloseClient auto closes Socket and cleans all references, preventing resource leaks

Last Updated: 2026-06-13

VB6 and LOGO copyright of Microsoft Corporation