Inaccurate Comments
Description
Inaccurate Comments occur when source code contains comments that do not accurately describe or explain aspects of the portion of the code with which the comment is associated. This includes outdated comments that no longer reflect the current code behavior, comments that describe incorrect functionality, misleading explanations of algorithms or logic, copy-pasted comments that weren't updated, and comments that contradict what the code actually does. Inaccurate comments can mislead developers and security reviewers, potentially causing them to miss vulnerabilities or introduce new bugs.
Risk
Inaccurate comments have significant indirect security implications. Security reviewers may trust misleading comments instead of analyzing the actual code. Developers may maintain code based on incorrect comment descriptions. Bugs may be introduced when fixing code according to wrong comments. Security-critical behavior may be misunderstood. Auditors may overlook vulnerabilities if comments suggest code is safe. Code modifications may break functionality that comments incorrectly describe. Compliance audits may be affected by misleading documentation. Time is wasted trying to reconcile comment descriptions with actual behavior.
Solution
Keep comments synchronized with code changes. Review comments during code reviews for accuracy. Delete comments rather than leaving outdated ones. Use self-documenting code to reduce need for explanatory comments. Write comments that explain "why" rather than "what" (the code shows what). Update comments immediately when changing associated code. Use automated tools to detect stale comments. Remove commented-out code instead of leaving it. Verify comments against actual code behavior. Establish team processes for comment maintenance.
Common Consequences
| Impact | Details |
|---|---|
| Other | Scope: Other Reduce Maintainability - Difficulty maintaining the product indirectly affects security by making vulnerabilities harder to find and fix. |
| Other | Scope: Other Increase Analytical Complexity - Mismatched comments confuse reviewers and complicate validation of intended behavior. |
Example Code
Vulnerable Code
// Vulnerable: Inaccurate comments throughout
public class MedicationCalculator {
/**
* Add the patient weight and Mg/Kg to get the daily dose.
*
* NOTE: Comment says "Add" but code multiplies!
* This could lead to severe dosing errors if someone
* "fixes" the code to match the comment.
*/
public double calculateDailyDose(double weightKg, double mgPerKg) {
return weightKg * mgPerKg; // Actually multiplies, not adds
}
// Validates that password meets security requirements
// (Actually this just checks if it's not null!)
public boolean validatePassword(String password) {
return password != null;
}
/**
* Encrypts data using AES-256 encryption.
*
* NOTE: Comment is completely wrong - this uses XOR "encryption"
* which provides no real security!
*/
public byte[] encryptData(byte[] data, byte[] key) {
byte[] result = new byte[data.length];
for (int i = 0; i < data.length; i++) {
result[i] = (byte) (data[i] ^ key[i % key.length]);
}
return result;
}
// Returns the user's role from the database
// (Actually returns a hardcoded admin role - security issue!)
public String getUserRole(String userId) {
return "admin"; // TODO: implement actual lookup
}
}
# Vulnerable: Python with inaccurate comments
class SecurityValidator:
def validate_input(self, user_input):
"""
Sanitizes input to prevent SQL injection.
Actually does nothing to prevent SQL injection!
The comment is completely misleading.
"""
# Just returns the input unchanged
return user_input
def check_admin_access(self, user):
# Only allow access if user is authenticated
#
# WRONG: Actually allows access if user is NOT authenticated
# This is a critical security bug hidden by inaccurate comment
if not user.is_authenticated:
return True # Comment says authenticated required, but...
return False
def hash_password(self, password):
"""
Uses bcrypt with 12 rounds for secure password hashing.
Actually uses MD5 which is cryptographically broken!
"""
import hashlib
return hashlib.md5(password.encode()).hexdigest()
# Rate limits to 100 requests per minute
# (Actually limits to 1000 requests - 10x the documented limit)
def rate_limit(self, requests):
return len(requests) < 1000
# Authenticates user with two-factor authentication
# (Actually only checks password - no 2FA implemented!)
def authenticate(username, password):
user = find_user(username)
return user and user.password == password
// Vulnerable: JavaScript with misleading comments
class PaymentProcessor {
/**
* Validates credit card number using Luhn algorithm
* and checks against known fraudulent patterns.
*
* REALITY: Just checks if it's 16 digits - no Luhn, no fraud check!
*/
validateCard(cardNumber) {
return /^\d{16}$/.test(cardNumber);
}
// Securely processes payment through PCI-compliant gateway
// (Actually logs card number to console - huge security violation!)
processPayment(cardNumber, amount) {
console.log(`Processing card: ${cardNumber}`); // INSECURE!
return { success: true, amount: amount };
}
/**
* Refunds are limited to the original transaction amount.
*
* BUG: No limit check implemented - can refund any amount!
*/
refund(transactionId, amount) {
// Missing validation that comment claims exists
return this.gateway.refund(transactionId, amount);
}
// Encrypted storage of sensitive payment data
// (Actually stores in plain text!)
storePaymentData(data) {
localStorage.setItem('payment', JSON.stringify(data));
}
}
// Vulnerable: C with dangerous inaccurate comments
/**
* Copies src to dest safely with bounds checking.
* Buffer overflow is prevented by this function.
*
* WRONG: Uses strcpy with no bounds checking!
*/
void safe_copy(char *dest, const char *src) {
strcpy(dest, src); // No bounds checking whatsoever!
}
// Validates that input length is within safe limits
// (Actually has off-by-one error in comparison)
int validate_length(const char *input, int max_len) {
// Comment says validates "within" limits
// but <= should be < (allows one extra byte)
return strlen(input) <= max_len;
}
/**
* Frees memory and sets pointer to NULL to prevent use-after-free.
*
* WRONG: Doesn't set pointer to NULL!
*/
void secure_free(void *ptr) {
free(ptr);
// Missing: ptr = NULL;
}
// Thread-safe counter implementation
// (Actually not thread-safe - no synchronization!)
static int counter = 0;
int increment_counter() {
return ++counter; // Race condition!
}
Fixed Code
// Fixed: Accurate comments that match code behavior
public class MedicationCalculator {
/**
* Calculate the daily medication dose.
*
* <p>Multiplies the patient's weight by the prescribed mg/kg ratio
* to determine the total daily dose in milligrams.
*
* @param weightKg Patient weight in kilograms
* @param mgPerKg Prescribed milligrams per kilogram
* @return Total daily dose in milligrams
*/
public double calculateDailyDose(double weightKg, double mgPerKg) {
return weightKg * mgPerKg;
}
/**
* Check if password is provided.
*
* <p><strong>Note:</strong> This only checks for null. Additional
* validation (length, complexity) should be done by PasswordValidator.
*
* @param password The password to check
* @return true if password is not null, false otherwise
* @see PasswordValidator#validateStrength for full validation
*/
public boolean isPasswordProvided(String password) {
return password != null;
}
/**
* XOR operation on data (NOT secure encryption).
*
* <p><strong>WARNING:</strong> This is NOT cryptographic encryption!
* XOR provides no security against determined attackers.
* Use {@link AESEncryptor} for actual encryption needs.
*
* @param data The data to transform
* @param key The XOR key
* @return XOR-transformed data
* @deprecated Use AESEncryptor.encrypt() for secure encryption
*/
@Deprecated
public byte[] xorTransform(byte[] data, byte[] key) {
byte[] result = new byte[data.length];
for (int i = 0; i < data.length; i++) {
result[i] = (byte) (data[i] ^ key[i % key.length]);
}
return result;
}
/**
* Get user role from the database.
*
* @param userId The user ID to look up
* @return The user's role, or "guest" if not found
*/
public String getUserRole(String userId) {
User user = userRepository.findById(userId);
return user != null ? user.getRole() : "guest";
}
}
# Fixed: Python with accurate comments
class SecurityValidator:
def get_raw_input(self, user_input):
"""
Return user input as-is without modification.
Note:
This method does NOT sanitize input. Use SqlParameterizer
for database queries and HtmlEscaper for output.
Args:
user_input: Raw input string from user
Returns:
The input unchanged
See Also:
SqlParameterizer: For safe database query construction
HtmlEscaper: For safe HTML output
"""
return user_input
def is_unauthenticated(self, user):
"""
Check if user is NOT authenticated.
Returns:
True if user is unauthenticated, False if authenticated
"""
return not user.is_authenticated
def hash_password_md5_unsafe(self, password):
"""
Hash password using MD5.
Warning:
MD5 is cryptographically broken and should NOT be used
for password hashing! Use bcrypt_hash_password() instead.
This method exists only for legacy compatibility.
Args:
password: The password to hash
Returns:
MD5 hash (INSECURE)
Deprecated:
Use bcrypt_hash_password() for secure password hashing.
"""
import hashlib
import warnings
warnings.warn("MD5 is insecure. Use bcrypt_hash_password().",
DeprecationWarning)
return hashlib.md5(password.encode()).hexdigest()
def check_rate_limit(self, requests, limit=1000):
"""
Check if request count is within rate limit.
Args:
requests: List of recent requests
limit: Maximum allowed requests (default: 1000)
Returns:
True if under limit, False if limit exceeded
"""
return len(requests) < limit
def authenticate_password_only(username, password):
"""
Authenticate user with password only.
Warning:
This does NOT implement two-factor authentication.
For 2FA, use TwoFactorAuthenticator class.
Args:
username: User's username
password: User's password
Returns:
True if credentials are valid, False otherwise
"""
user = find_user(username)
return user and secure_compare(user.password_hash, hash_password(password))
CVE Examples
This CWE is marked as PROHIBITED for direct CVE mapping as it represents a code quality concern rather than a direct security vulnerability.
Related CWEs
- CWE-1078: Inappropriate Source Code Style or Formatting (parent)
- CWE-1006: Bad Coding Practices (category member)
- CWE-1113: Inappropriate Comment Style (related)
- CWE-1110: Incomplete Design Documentation (related)
References
- MITRE Corporation. "CWE-1116: Inaccurate Comments." https://cwe.mitre.org/data/definitions/1116.html
- "Code Complete" by Steve McConnell - Chapter on Code Documentation
- "Clean Code" by Robert C. Martin - Chapter on Comments