Mitigation Strategy: Strict Rule-Based Input Validation (gvalid)
-
Mitigation Strategy: Enforce strict and comprehensive input validation using
gf
'sgvalid
package. -
Description:
- Identify all input points: Determine every point where the application receives data from external sources, focusing on points where
gf
handles input (e.g.,ghttp.Request
parameters,ghttp.UploadFile
). - Define validation rules: For each input field, define specific validation rules using
gvalid
's built-in rules (e.g.,required
,email
,integer
,min
,max
,length
,regex
, etc.). Use the most restrictive rules possible. - Implement custom rules (if needed): For complex validation logic, create custom validation rules using
gvalid.RegisterRule
. Thoroughly test these custom rules. - Chain rules: Use rule chaining to combine multiple validation checks (e.g.,
email|length:6,64
). Order rules logically. - Struct validation: Use struct tags to define validation rules directly within data structures, leveraging
gf
's integration withgvalid
. - Check validation results: Always check the return value of
gvalid.Check*
functions (or the result of struct validation). Handle validation errors appropriately. - Return user-friendly errors: Provide clear and concise error messages to the user, using
gf
's error handling mechanisms, but never reveal sensitive information. - Log detailed errors: Log detailed validation errors internally for debugging, using
glog
. - Bail Early (Optional): Consider using the
bail
rule to stop on the first error.
- Identify all input points: Determine every point where the application receives data from external sources, focusing on points where
-
Threats Mitigated:
- SQL Injection (Critical): By validating input types and formats before they reach
gdb
, you prevent malicious SQL code. - Cross-Site Scripting (XSS) (High): Validating input and preventing malicious scripts mitigates XSS, especially when combined with
gview
's output encoding. - Command Injection (Critical): Validating input to prevent execution of arbitrary commands, particularly relevant if using
gf
to interact with system processes. - Data Type Mismatches (Medium): Ensuring data conforms to expected types prevents unexpected behavior within
gf
components. - Business Logic Errors (Variable): Custom validation rules can enforce application-specific business logic constraints within the
gf
framework.
- SQL Injection (Critical): By validating input types and formats before they reach
-
Impact:
- SQL Injection: Risk significantly reduced (near elimination if combined with
gdb
's parameterized queries). - XSS: Risk significantly reduced (effectiveness depends on
gview
's output encoding as well). - Command Injection: Risk significantly reduced.
- Data Type Mismatches: Risk eliminated for validated fields within
gf
. - Business Logic Errors: Risk reduced depending on the comprehensiveness of custom rules within
gf
.
- SQL Injection: Risk significantly reduced (near elimination if combined with
-
Currently Implemented:
/api/user/register
: Basic validation rules (required
,email
,password
) are implemented using struct tags andgf
's integration./api/product/create
: Validation rules for product name, description, and price are implemented usinggvalid.CheckMap
within agf
handler.
-
Missing Implementation:
/api/user/profile
: No validation is currently implemented for user profile updates (e.g., address, phone number) handled bygf
. High Priority/api/search
: The search query parameter, processed bygf
, is not validated. Medium Priority- Custom validation rules are not used anywhere. Medium Priority (Assess if needed based on business logic within
gf
handlers).
Mitigation Strategy: Parameterized Queries (gdb - Always)
-
Mitigation Strategy: Exclusively use parameterized queries (prepared statements) for all database interactions using
gf
'sgdb
ORM. -
Description:
- Identify all
gdb
interactions: Locate all instances where the application usesgf
'sgdb
to interact with the database. - Use ORM methods: Prefer using
gdb
's ORM methods (e.g.,Model
,Data
,Where
,Insert
,Update
,Delete
) over raw SQL. These methods are designed to use parameterized queries. - Avoid string concatenation: Never construct SQL queries by concatenating strings with user-supplied data within
gdb
calls. - Use placeholders: Use placeholders (e.g.,
?
) in yourWhere
clauses and other query parts withingdb
methods. - Pass data separately: Pass user-supplied data as separate arguments to the
gdb
methods (e.g.,Where("id = ?", userID)
). - Avoid
Raw
: Minimize the use ofgdb.Raw
. If unavoidable, ensure the SQL is static and contains no user input. Even then, be extremely cautious.
- Identify all
-
Threats Mitigated:
- SQL Injection (Critical): Parameterized queries within
gdb
are the primary defense against SQL injection.
- SQL Injection (Critical): Parameterized queries within
-
Impact:
- SQL Injection: Risk virtually eliminated if implemented correctly and consistently within all
gdb
interactions.
- SQL Injection: Risk virtually eliminated if implemented correctly and consistently within all
-
Currently Implemented:
- Most database interactions in
/api/product
use parameterized queries viagdb
's ORM.
- Most database interactions in
-
Missing Implementation:
/api/report
: A custom report generation feature uses string concatenation within agdb
call to build a dynamic SQL query. Critical Priority (Immediate remediation required).- Review all uses of
db.Raw
to ensure they are safe. High Priority
Mitigation Strategy: Secure Session Management (gsession)
-
Mitigation Strategy: Configure and use
gf
'sgsession
package with secure settings and practices. -
Description:
- Choose secure storage: Use a secure session storage backend supported by
gsession
(e.g., Redis, database) instead of in-memory storage for production. - Configure session ID length: Ensure the session ID length is sufficiently long (check
gf
'sgsession
default). - Set timeouts: Configure appropriate session idle and absolute timeouts using
gsession
's configuration options. - Enable HTTPOnly: Verify that the
HTTPOnly
flag is set for session cookies (should be the default ingsession
, but verify). - Enable Secure: Verify that the
Secure
flag is set for session cookies (should be automatic with HTTPS andgsession
, but verify). - Set SameSite: Set the
SameSite
attribute toStrict
orLax
usinggsession
's configuration. - Regenerate ID: Regenerate the session ID after a successful login using
gsession.SetId
. - Validate session: On each request handled by
gf
, verify the session's validity (e.g., check for expiration, user ID) usinggsession
's methods. - Implement logout: Provide a logout function that destroys the session using
gsession.Destroy
.
- Choose secure storage: Use a secure session storage backend supported by
-
Threats Mitigated:
- Session Hijacking (High): Secure flags and proper
gsession
management reduce the risk. - Session Fixation (High): Session ID regeneration after login prevents fixation.
- Cross-Site Request Forgery (CSRF) (High): The
SameSite
attribute, set viagsession
, helps mitigate CSRF. - Session Prediction (Medium): A sufficiently long and random session ID, managed by
gsession
, makes prediction difficult.
- Session Hijacking (High): Secure flags and proper
-
Impact:
- Session Hijacking: Risk significantly reduced.
- Session Fixation: Risk virtually eliminated.
- CSRF: Risk significantly reduced (especially with
SameSite=Strict
). - Session Prediction: Risk significantly reduced.
-
Currently Implemented:
- Basic session management is implemented using
gsession
with default settings. - Redis is used as the session storage backend, configured through
gf
.
- Basic session management is implemented using
-
Missing Implementation:
- Session ID regeneration after login (using
gsession.SetId
) is not implemented. High Priority SameSite
attribute is not explicitly set viagsession
's configuration. Medium Priority- Session validation on each request is basic (only checks for existence using
gsession
). Medium Priority (Enhance to check user ID and other attributes).
- Session ID regeneration after login (using
Mitigation Strategy: Secure File Uploads (ghttp.UploadFile)
-
Mitigation Strategy: Implement strict file upload validation and secure storage practices, leveraging
gf
'sghttp.UploadFile
features. -
Description:
- Content-Based Type Validation: Validate the file type based on its content (magic numbers), not just the extension or MIME type provided by the client. Use a library like
filetype
in conjunction withghttp.UploadFile.Content
. - Size Limits: Enforce strict file size limits using
ghttp.Request.SetMaxMemory
. - Filename Sanitization: Sanitize filenames to remove dangerous characters, using
gstr
functions or generating unique filenames (UUIDs) within yourgf
handler. - Storage Outside Web Root: Store uploaded files outside of the web root directory, ensuring the path is configured correctly within your
gf
application.
- Content-Based Type Validation: Validate the file type based on its content (magic numbers), not just the extension or MIME type provided by the client. Use a library like
-
Threats Mitigated:
- File Upload Vulnerabilities (Critical): Uploading and executing malicious files (e.g., shells) via
gf
's upload handling. - Directory Traversal (High): Uploading files to unintended locations through manipulation of
ghttp.UploadFile
. - Cross-Site Scripting (XSS) (High): Uploading malicious HTML or JavaScript files that could be served by
gf
.
- File Upload Vulnerabilities (Critical): Uploading and executing malicious files (e.g., shells) via
-
Impact:
- File Upload Vulnerabilities: Risk significantly reduced.
- Directory Traversal: Risk significantly reduced.
- XSS: Risk reduced (effectiveness depends on other factors).
-
Currently Implemented:
- File size limits are enforced using
ghttp.Request.SetMaxMemory
. - Uploaded files are stored in a separate directory, configured within the
gf
application.
- File size limits are enforced using
-
Missing Implementation:
- Content-based file type validation is not implemented. Critical Priority (Must be done in conjunction with
ghttp.UploadFile
). - Filename sanitization is basic (only removes spaces). High Priority (Implement more robust sanitization or UUID generation within the
gf
handler).
- Content-based file type validation is not implemented. Critical Priority (Must be done in conjunction with
Mitigation Strategy: Safe Logging Practices (glog)
-
Mitigation Strategy: Prevent sensitive data leakage in logs by using
gf
'sglog
package with appropriate logging levels, masking sensitive data, and securing log storage. -
Description:
- Identify Sensitive Data: Determine all types of sensitive data handled by the application.
- Avoid Logging Sensitive Data: Never log sensitive data directly using
glog
. - Masking/Redaction: Use
glog
's formatting capabilities or a dedicated library to mask or redact sensitive data before logging. - Log Level Control: Use appropriate log levels (Debug, Info, Warning, Error, Critical) provided by
glog
. Use a higher level (Info or Warning) in production. - Log Rotation: Configure log rotation using
glog
's built-in features to prevent files from growing indefinitely.
-
Threats Mitigated:
- Information Leakage (High): Exposure of sensitive data in logs generated by
glog
.
- Information Leakage (High): Exposure of sensitive data in logs generated by
-
Impact:
- Information Leakage: Risk significantly reduced if sensitive data is never logged or is properly masked using
glog
's features.
- Information Leakage: Risk significantly reduced if sensitive data is never logged or is properly masked using
-
Currently Implemented:
glog
is used for logging throughout the application.- Log rotation is configured using
glog
's settings.
-
Missing Implementation:
- Sensitive data masking is not implemented within
glog
calls. Critical Priority (Review allglog
usage and implement masking). - Log level is set to
Debug
in production. High Priority (Change toInfo
orWarning
usingglog
's configuration).
- Sensitive data masking is not implemented within
Mitigation Strategy: Generic Error Handling (gerror)
-
Mitigation Strategy: Prevent information leakage through error messages by returning generic messages to users and logging detailed errors internally using
gf
'sgerror
package. -
Description:
- Identify Error Points: Locate all places where errors can occur, particularly within
gf
components (e.g.,gdb
,ghttp
handlers). - Catch Errors: Use
try...catch
blocks (or equivalent error handling) to catch potential errors, especially those returned bygf
functions. - Generic User Messages: Return generic error messages to the user (e.g., "An error occurred. Please try again later.") within your
gf
handlers. - Detailed Internal Logging: Log detailed error information (including stack traces using
gerror.Stack()
) internally for debugging, usingglog
. - Custom Error Handling: Implement custom error handling logic using
gerror
to manage and wrap errors within yourgf
application.
- Identify Error Points: Locate all places where errors can occur, particularly within
-
Threats Mitigated:
- Information Leakage (Medium): Exposure of internal application details (including
gf
internals) through error messages.
- Information Leakage (Medium): Exposure of internal application details (including
-
Impact:
- Information Leakage: Risk significantly reduced.
-
Currently Implemented:
- Basic error handling is implemented in some areas using
gerror
.
- Basic error handling is implemented in some areas using
-
Missing Implementation:
- Consistent use of generic error messages within
gf
handlers is not enforced. Medium Priority (Review all error handling and ensure generic messages are returned). - Detailed internal logging with stack traces (using
gerror.Stack()
) is inconsistent. Medium Priority
- Consistent use of generic error messages within
Mitigation Strategy: Secure HTTP Request Handling (ghttp)
-
Mitigation Strategy: Use
gf
'sghttp
middleware, validate request components, restrict HTTP methods, and configure CORS properly, all within thegf
framework. -
Description:
- Middleware: Create
ghttp
middleware to:- Validate request headers.
- Enforce rate limiting.
- Implement CSRF protection.
- Check authentication/authorization.
- Input Validation (Again): Validate all request parameters, headers, and the body using
gvalid
within yourghttp
handlers. - HTTP Methods: Explicitly define allowed HTTP methods for each route using
ghttp.Server.BindHandlerMethod
. - CORS Configuration: Configure CORS using
ghttp.Server.SetCors
with appropriate restrictions (avoidAllowAllOrigins: true
).
- Middleware: Create
-
Threats Mitigated:
- Cross-Site Request Forgery (CSRF) (High):
ghttp
middleware andgsession
'sSameSite
cookies can mitigate CSRF. - Request Smuggling (Medium): Proper header validation within
ghttp
handlers can help. - Header Injection (Medium): Validating headers within
ghttp
prevents injection attacks. - Unauthorized Access (High): Authentication/authorization middleware within
ghttp
prevents unauthorized access. - CORS Misconfiguration (Medium): Proper CORS settings using
ghttp.Server.SetCors
prevent unauthorized cross-origin requests.
- Cross-Site Request Forgery (CSRF) (High):
-
Impact:
- CSRF: Risk significantly reduced with proper
ghttp
middleware andgsession
cookie settings. - Request Smuggling/Header Injection: Risk reduced with header validation within
ghttp
. - Unauthorized Access: Risk significantly reduced with authentication/authorization middleware in
ghttp
. - CORS Misconfiguration: Risk eliminated with correct CORS configuration using
ghttp.Server.SetCors
.
- CSRF: Risk significantly reduced with proper
-
Currently Implemented:
- Basic authentication middleware is implemented using
ghttp
.
- Basic authentication middleware is implemented using
-
Missing Implementation:
- CSRF protection middleware is not implemented within
ghttp
. High Priority - Rate limiting middleware is not implemented within
ghttp
. Medium Priority - CORS is not explicitly configured using
ghttp.Server.SetCors
. Medium Priority - HTTP methods are not explicitly restricted for all routes using
ghttp.Server.BindHandlerMethod
. Low Priority
- CSRF protection middleware is not implemented within