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 Scripting.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 Scripting.Dictionary
Set GetValidationRules = Nothing
Dim rules As New Scripting.Dictionary
Select Case path
Case "/api/users/create"
Dim userRules As New Scripting.Dictionary
userRules("required") = True
userRules("type") = "string"
userRules("maxLength") = 50
rules("username") = userRules
Dim emailRules As New Scripting.Dictionary
emailRules("required") = True
emailRules("type") = "email"
rules("email") = emailRules
Set GetValidationRules = rules
End Select
End FunctionSQL 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 IfInput 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 FunctionXSS Protection
HTML Encoding Output
vb
' cSecurityUtils.bas
Public Function HtmlEncode(text As String) As String
Dim result As String
result = text
result = Replace(result, "&", "&")
result = Replace(result, "<", "<")
result = Replace(result, ">", ">")
result = Replace(result, """, """)
result = Replace(result, "'", "'")
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 SubCookie HttpOnly
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 WithCSRF 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 SubToken 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 Scripting.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 FunctionPassword 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 FunctionRate Limiting
vb
' cRateLimitMiddleware.cls (complete version)
Option Explicit
Dim RequestLog As Scripting.Dictionary ' IP -> Request record
Dim BlockList As Scripting.Dictionary ' IP -> Unblock time
Private Sub Class_Initialize()
Set RequestLog = New Scripting.Dictionary
Set BlockList = New Scripting.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 Scripting.Dictionary
record("count") = 0
record("startTime") = Now
record("urls") = New Scripting.Dictionary
Set RequestLog(ip) = record
End If
Dim rec As Scripting.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 Scripting.Dictionary
End If
' Count
rec("count") = rec("count") + 1
Dim urls As Scripting.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 SubSecurity 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 SubLogging 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 SubSecurity Configuration Checklist
| Check Item | Status | Description |
|---|---|---|
| Force HTTPS | ☐ | Production must use HTTPS |
| Parameterized Query | ☐ | All database operations use parameterized |
| XSS Filtering | ☐ | Encode HTML in output |
| CSRF Token | ☐ | Verify CSRF token on modifications |
| HttpOnly Cookie | ☐ | Session cookie with HttpOnly |
| Secure Cookie | ☐ | Set Secure in HTTPS environment |
| Password Hashing | ☐ | Use bcrypt or secure algorithm |
| Rate Limiting | ☐ | Limit endpoint request frequency |
| Security Headers | ☐ | Add X-Frame-Options etc. |
| Logging | ☐ | Log sensitive operations and security events |
Last Updated: 2026-05-17