Inappropriate Source Code Style or Formatting

Description

Inappropriate Source Code Style or Formatting occurs when source code does not follow desired style or formatting conventions for indentation, whitespace, comments, or other stylistic elements. Inconsistent formatting makes code harder to read and understand, increasing the cognitive load required for code review and maintenance. While style may seem superficial, inconsistent formatting can hide logical errors and make security vulnerabilities harder to spot during code review.

Risk

Inappropriate formatting has indirect security implications. Inconsistent indentation can hide the actual control flow, making security-relevant code blocks appear different than they actually are. Code reviewers may miss vulnerabilities in poorly formatted code. Copy-paste errors are more likely with inconsistent formatting. Security tools may have difficulty parsing non-standard formatting. Misleading indentation can cause developers to misunderstand code behavior. The famous "goto fail" bug (CVE-2014-1266) was hidden by misleading indentation.

Solution

Establish and enforce code style guidelines for the project. Use automated formatters (Prettier, Black, clang-format, gofmt) in the development workflow. Configure IDEs to format on save. Use pre-commit hooks to enforce formatting. Include style checks in CI/CD pipelines. Use linters to detect style violations. Choose established style guides (Google, Airbnb, PEP 8) rather than creating custom ones. Document any deviations from standard styles. Use editor configurations (.editorconfig) to maintain consistency across tools.

Common Consequences

ImpactDetails
OtherScope: Other

Increase Analytical Complexity - Inconsistent style makes code harder to understand and review.
OtherScope: Other

Reduce Maintainability - Poorly formatted code is harder to modify safely.
OtherScope: Other

Hide Logical Errors - Misleading formatting can obscure actual code behavior.

Example Code

Vulnerable Code

// Vulnerable: Misleading indentation (similar to "goto fail" bug)
static int verify_signature(const unsigned char *sig, size_t siglen,
                           const unsigned char *data, size_t datalen)
{
    int result = -1;

    if (!sig || !data)
        goto fail;

    if (siglen == 0)
        goto fail;

    // Vulnerable: This line ALWAYS executes, but indentation suggests
    // it's part of the if statement above
    if (siglen != EXPECTED_SIZE)
        goto fail;
        goto fail;  // ALWAYS EXECUTED - signature check bypassed!

    // This code is never reached
    result = perform_actual_verification(sig, data);

fail:
    return result;
}
// Vulnerable: Inconsistent formatting hiding logic errors
public class VulnerableProcessor {

    public void processRequest(Request request)
    {
        // Inconsistent brace style
        if(request.isAuthenticated()){
            processAuthenticated(request);
        }else
        // Missing braces - only first statement is conditional!
        if (request.isAdmin())
            grantAdminAccess(request);
            grantFullPermissions(request);  // ALWAYS EXECUTED!

        // Vulnerable: Misleading indentation
        if (request.getData() != null)
            validateData(request);
            processData(request);  // Looks conditional but isn't!

        // Inconsistent spacing makes comparison hard to read
        if(request.getCount()==0||request.getCount( )>100) {
            // What does this even check?
        }
    }

    // Methods with wildly different formatting
    public void methodOne(){System.out.println("one");}

    public void methodTwo()
    {
        System.out.println("two");
    }

    public void methodThree() { System.out.println("three"); }
}
# Vulnerable: Inconsistent Python indentation
class VulnerableAuth:
    def authenticate(self, username, password):
        """Check user credentials."""
        if username == "admin":
          # 2-space indent
          if password == "secret":
             # 3-space indent - inconsistent!
             return True
        # Tab and space mixed - can cause IndentationError
	    if self.check_db(username, password):  # Tab here!
            return True
        return False

    def validate_input(self,input):  # No space after comma
        if input is None:
            return False
        if len(input)>100:  # No spaces around operator
            return False
        #No space after hash in comment
        return True

    # Inconsistent blank lines between methods


    def another_method( self ):  # Weird spacing
        """Some method."""
        pass
// Vulnerable: Inconsistent JavaScript formatting
class VulnerableService{
    constructor() {
        this.data = []
    }  // Missing semicolons

    // Method 1: K&R style
    processData(data) {
        if (data) {
            return data.map(x=>x*2)  // Inconsistent arrow function spacing
        }
    }

    // Method 2: Allman style
    validateInput(input)
    {
        if (!input)
        {
            return false;
        }
        return true;
    }

    // Method 3: One-liner chaos
    async fetchData(id){try{const r=await fetch('/api/'+id);return r.json();}catch(e){console.log(e)}}

    // Inconsistent quote styles
    getMessage() {
        return "Hello " + 'World' + `!`;
    }
}

Fixed Code

// Fixed: Consistent style prevents misleading indentation
static int verify_signature(const unsigned char *sig, size_t siglen,
                           const unsigned char *data, size_t datalen)
{
    int result = -1;

    /* Fixed: Always use braces, even for single statements */
    if (!sig || !data) {
        goto fail;
    }

    if (siglen == 0) {
        goto fail;
    }

    if (siglen != EXPECTED_SIZE) {
        goto fail;
    }

    /* Fixed: Code structure is now clear */
    result = perform_actual_verification(sig, data);

fail:
    return result;
}

/* Fixed: Consistent style guide application */
/*
 * Style conventions used:
 * - 4-space indentation
 * - Opening brace on same line
 * - Always use braces for if/else/while/for
 * - Space after keywords (if, while, for)
 * - No space before function call parentheses
 */
// Fixed: Consistent Java formatting
public class FixedProcessor {

    public void processRequest(Request request) {
        // Fixed: Consistent brace style (K&R)
        if (request.isAuthenticated()) {
            processAuthenticated(request);
        } else if (request.isAdmin()) {
            // Fixed: Always use braces
            grantAdminAccess(request);
            grantFullPermissions(request);
        }

        // Fixed: Clear control flow
        if (request.getData() != null) {
            validateData(request);
            processData(request);
        }

        // Fixed: Consistent spacing
        if (request.getCount() == 0 || request.getCount() > 100) {
            handleInvalidCount(request);
        }
    }

    // Fixed: Consistent method formatting
    public void methodOne() {
        System.out.println("one");
    }

    public void methodTwo() {
        System.out.println("two");
    }

    public void methodThree() {
        System.out.println("three");
    }
}

/*
 * Style guide: Google Java Style
 * - 4-space indentation (no tabs)
 * - 100-character line limit
 * - Braces required for all control structures
 * - One statement per line
 */
# Fixed: PEP 8 compliant Python
class FixedAuth:
    """Authentication handler following PEP 8."""

    def authenticate(self, username: str, password: str) -> bool:
        """Check user credentials.

        Args:
            username: The username to authenticate
            password: The password to verify

        Returns:
            True if authentication successful, False otherwise
        """
        # Fixed: Consistent 4-space indentation
        if username == "admin":
            if password == "secret":
                return True

        if self.check_db(username, password):
            return True

        return False

    def validate_input(self, user_input: str) -> bool:
        """Validate user input.

        Args:
            user_input: The input to validate

        Returns:
            True if valid, False otherwise
        """
        # Fixed: Consistent spacing around operators
        if user_input is None:
            return False

        if len(user_input) > 100:
            return False

        # Fixed: Space after hash in comments
        return True

    def another_method(self) -> None:
        """Placeholder method."""
        pass


# Style: PEP 8
# - 4-space indentation
# - Spaces around operators
# - Blank lines between top-level definitions
# - Two blank lines around class definitions
// Fixed: Consistent JavaScript/ES6 formatting
class FixedService {
    constructor() {
        this.data = [];
    }

    // Fixed: Consistent method style
    processData(data) {
        if (data) {
            return data.map((x) => x * 2);
        }
        return [];
    }

    // Fixed: Consistent brace placement
    validateInput(input) {
        if (!input) {
            return false;
        }
        return true;
    }

    // Fixed: Readable async method
    async fetchData(id) {
        try {
            const response = await fetch(`/api/${id}`);
            return response.json();
        } catch (error) {
            console.error('Fetch error:', error);
            throw error;
        }
    }

    // Fixed: Consistent quote style (single quotes)
    getMessage() {
        return 'Hello World!';
    }
}

/*
 * Style: Airbnb JavaScript Style Guide
 * - 2-space indentation
 * - Single quotes for strings
 * - Semicolons required
 * - Spaces around operators
 * - No trailing whitespace
 */

// ESLint and Prettier configuration ensures consistency

CVE Examples

  • CVE-2014-1266: Apple's "goto fail" SSL vulnerability was hidden by misleading indentation that made a critical security bypass appear to be part of error handling code.

  • CWE-1076: Insufficient Adherence to Expected Conventions (parent)
  • CWE-546: Suspicious Comment (child)
  • CWE-547: Use of Hard-coded, Security-relevant Constants (child)
  • CWE-1099: Inconsistent Naming Conventions for Identifiers (child)

References

  1. MITRE Corporation. "CWE-1078: Inappropriate Source Code Style or Formatting." https://cwe.mitre.org/data/definitions/1078.html
  2. Google Style Guides. https://google.github.io/styleguide/
  3. PEP 8 - Style Guide for Python Code. https://peps.python.org/pep-0008/