Source Code Element without Standard Prologue

Description

Source Code Element without Standard Prologue occurs when source code files or significant code elements lack consistent standardized prologues or headers throughout the project. Standard prologues typically contain information such as module name, version number, author, date, purpose, function, assumptions, limitations, accuracy considerations, security notes, and licensing information. Without consistent prologues, code understanding becomes more difficult and security-relevant information may be missing or inconsistently documented.

Risk

Missing standard prologues have indirect security implications. Security-critical modules may not be clearly identified without proper headers. Version information absence complicates security patch tracking. Missing author information makes it harder to contact developers about security issues. Assumptions and limitations not documented may lead to misuse. Security requirements for specific modules may not be communicated. Code provenance is harder to establish without consistent headers. License compliance issues may arise. Audit trails become incomplete. Code review becomes more time-consuming without context information.

Solution

Establish standard prologue templates for the project. Include module name, purpose, and description. Document version history and change log. Include author and maintainer information. List security-relevant assumptions and limitations. Document dependencies and requirements. Include licensing information. Use automated tools to enforce prologue presence. Add security classifications for sensitive modules. Document input/output specifications. Keep prologues up-to-date with code changes. Use IDE templates or snippets for consistent formatting.

Common Consequences

ImpactDetails
OtherScope: Other

Reduce Maintainability - Missing prologues make code understanding slower and more difficult, indirectly affecting security by making vulnerabilities harder to find and fix.
OtherScope: Other

Increase Analytical Complexity - Insufficient analyzability makes security review more difficult without proper module documentation.

Example Code

Vulnerable Code

// Vulnerable: No standard prologue

package com.example.security;

import java.util.*;

public class AuthenticationService {
    // No documentation about:
    // - Purpose of this class
    // - Security assumptions
    // - Required permissions
    // - Thread safety
    // - Version history

    private Map<String, User> sessions = new HashMap<>();

    public boolean authenticate(String username, String password) {
        // Implementation without context
        User user = findUser(username);
        if (user != null && checkPassword(user, password)) {
            createSession(user);
            return true;
        }
        return false;
    }

    // More methods without documentation...
}
# Vulnerable: No module prologue

import hashlib
import secrets

def hash_password(password, salt=None):
    # No documentation about:
    # - Algorithm choice rationale
    # - Salt requirements
    # - Security considerations
    if salt is None:
        salt = secrets.token_hex(16)
    return hashlib.sha256((password + salt).encode()).hexdigest(), salt


def verify_password(password, hash, salt):
    computed, _ = hash_password(password, salt)
    return computed == hash


# No module-level documentation about:
# - What this module does
# - Security requirements
# - Dependencies
# - Version history
# - Author/maintainer
// Vulnerable: No file header

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// No documentation about:
// - File purpose
// - Security considerations
// - Buffer size assumptions
// - Thread safety

void process_input(char *input) {
    char buffer[256];
    strcpy(buffer, input);  // Potential overflow - not documented
    // ...
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        process_input(argv[1]);
    }
    return 0;
}
// Vulnerable: No module documentation

const crypto = require('crypto');

// No module prologue explaining:
// - Module purpose
// - Security requirements
// - API stability
// - Dependencies

function encryptData(data, key) {
    const cipher = crypto.createCipher('aes-256-cbc', key);
    let encrypted = cipher.update(data, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;
}

function decryptData(encryptedData, key) {
    const decipher = crypto.createDecipher('aes-256-cbc', key);
    let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

module.exports = { encryptData, decryptData };

Fixed Code

/*
 * ============================================================================
 * Module:      AuthenticationService.java
 * Package:     com.example.security
 * Version:     2.3.0
 * Author:      Security Team <[email protected]>
 * Created:     2024-01-15
 * Modified:    2024-03-20
 * ============================================================================
 *
 * PURPOSE:
 * Provides user authentication and session management services.
 * This is a security-critical component that handles credential validation.
 *
 * SECURITY CLASSIFICATION: HIGH
 *
 * SECURITY REQUIREMENTS:
 * - All password comparisons must be constant-time to prevent timing attacks
 * - Session tokens must be cryptographically random (256 bits minimum)
 * - Failed authentication attempts must be rate-limited
 * - All authentication events must be logged for audit
 *
 * ASSUMPTIONS:
 * - User passwords are already hashed using bcrypt (cost factor 12+)
 * - Database connections are encrypted (TLS 1.2+)
 * - This service runs in a trusted network zone
 *
 * LIMITATIONS:
 * - Maximum concurrent sessions per user: 5
 * - Session timeout: 30 minutes of inactivity
 * - Not designed for multi-tenant deployments without modification
 *
 * THREAD SAFETY:
 * This class is thread-safe. All shared state is properly synchronized.
 *
 * DEPENDENCIES:
 * - BCrypt library (org.mindrot:jbcrypt:0.4)
 * - SLF4J logging framework
 *
 * CHANGELOG:
 * 2.3.0 (2024-03-20) - Added rate limiting for failed attempts
 * 2.2.0 (2024-02-10) - Improved session token generation
 * 2.1.0 (2024-01-20) - Added audit logging
 * 2.0.0 (2024-01-15) - Initial secure implementation
 *
 * LICENSE: Proprietary - Internal Use Only
 * ============================================================================
 */

package com.example.security;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Authentication service for user credential validation and session management.
 *
 * <p><strong>Security Note:</strong> This service handles sensitive credentials.
 * All implementations must follow secure coding guidelines.</p>
 *
 * @author Security Team
 * @version 2.3.0
 * @since 2.0.0
 * @see SessionManager
 * @see AuditLogger
 */
public class AuthenticationService {

    private final ConcurrentHashMap<String, User> sessions;
    private final RateLimiter rateLimiter;
    private final AuditLogger auditLogger;

    /**
     * Authenticate a user with username and password.
     *
     * <p><strong>Security:</strong> Password comparison uses constant-time
     * algorithm. Failed attempts are rate-limited and logged.</p>
     *
     * @param username The username (must not be null or empty)
     * @param password The password (must not be null, handled securely)
     * @return true if authentication successful, false otherwise
     * @throws RateLimitExceededException if too many failed attempts
     */
    public boolean authenticate(String username, String password) {
        // Implementation with documented security measures
        Objects.requireNonNull(username, "Username must not be null");
        Objects.requireNonNull(password, "Password must not be null");

        rateLimiter.checkLimit(username);

        User user = findUser(username);
        if (user != null && securePasswordCheck(user, password)) {
            createSession(user);
            auditLogger.logSuccess(username);
            return true;
        }

        auditLogger.logFailure(username);
        return false;
    }
}
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
============================================================================
Module:     password_utils.py
Version:    1.2.0
Author:     Security Team <[email protected]>
Created:    2024-01-15
Modified:   2024-03-20
============================================================================

Password hashing and verification utilities.

This module provides secure password hashing using modern algorithms
with proper salt handling and timing-attack resistant comparison.

Security Classification: HIGH

Security Requirements:
    - Uses PBKDF2 with SHA-256 (100,000 iterations minimum)
    - Salts are 32 bytes of cryptographic random data
    - All comparisons are constant-time
    - Passwords are never logged or stored in plain text

Assumptions:
    - Running on a system with secure random number generation
    - Python 3.8+ with hashlib supporting PBKDF2

Limitations:
    - Maximum password length: 128 characters (to prevent DoS)
    - Minimum password length: 8 characters (enforced externally)

Thread Safety:
    All functions are thread-safe and stateless.

Dependencies:
    - hashlib (standard library)
    - secrets (standard library)
    - hmac (standard library)

Example:
    >>> hashed, salt = hash_password("secure_password")
    >>> verify_password("secure_password", hashed, salt)
    True

Changelog:
    1.2.0 (2024-03-20) - Increased iterations to 100,000
    1.1.0 (2024-02-10) - Added constant-time comparison
    1.0.0 (2024-01-15) - Initial implementation

License: MIT
============================================================================
"""

import hashlib
import secrets
import hmac
from typing import Tuple

# Security constants - documented for audit
HASH_ALGORITHM = 'sha256'
ITERATIONS = 100_000  # OWASP recommended minimum for PBKDF2-SHA256
SALT_LENGTH = 32  # 256 bits
HASH_LENGTH = 32  # 256 bits


def hash_password(password: str, salt: bytes = None) -> Tuple[str, bytes]:
    """
    Hash a password using PBKDF2-SHA256.

    Security Notes:
        - Uses cryptographically secure salt generation
        - 100,000 iterations as per OWASP guidelines
        - Salt must be stored alongside the hash

    Args:
        password: The plaintext password to hash (max 128 chars)
        salt: Optional salt bytes. If None, generates secure random salt.

    Returns:
        Tuple of (hex-encoded hash, salt bytes)

    Raises:
        ValueError: If password exceeds maximum length
    """
    if len(password) > 128:
        raise ValueError("Password exceeds maximum length")

    if salt is None:
        salt = secrets.token_bytes(SALT_LENGTH)

    hash_bytes = hashlib.pbkdf2_hmac(
        HASH_ALGORITHM,
        password.encode('utf-8'),
        salt,
        ITERATIONS,
        dklen=HASH_LENGTH
    )

    return hash_bytes.hex(), salt


def verify_password(password: str, expected_hash: str, salt: bytes) -> bool:
    """
    Verify a password against a stored hash.

    Security Notes:
        - Uses constant-time comparison to prevent timing attacks
        - Does not reveal which character was incorrect

    Args:
        password: The plaintext password to verify
        expected_hash: The stored hash (hex-encoded)
        salt: The salt used when creating the hash

    Returns:
        True if password matches, False otherwise
    """
    computed_hash, _ = hash_password(password, salt)
    # Constant-time comparison
    return hmac.compare_digest(computed_hash, expected_hash)

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.


  • 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

  1. MITRE Corporation. "CWE-1115: Source Code Element without Standard Prologue." https://cwe.mitre.org/data/definitions/1115.html
  2. IEEE Std 830 - Software Requirements Specifications
  3. Various language style guides (PEP 257, Javadoc, JSDoc)