
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































Static Code Analysis and SAST Tool Interpretation Python Logging Configuration and Secure Audit Trails Log Injection Prevention and Sensitive Data Redaction Exception Handling and Fail-Closed Design Assertion Behavior Under Optimization Debugging Methodologies and Root-Cause Analysis Unit Testing with Pytest and Test Validation Flask Application Security and Defensive Coding Input Validation and Taint Analysis Secure SDLC, CWE Mapping, and Professional Ethics INTRODUCTION This comprehensive examination is designed to evaluate the foundational knowledge and applied clinical judgment essential for identifying, remediating, and verifying security defects in Python applications. It assesses proficiency in static code analysis using tools such as Bandit and Flake8, secure logging configuration to prevent injection and data leakage, structured exception handling with fail-closed behavior, assertion limitations under optimized execution, and unit test design using Pytest. The exam employs a multiple-choice and scenario-based structure to challenge candidates to apply theoretical concepts to realistic Flask application workflows, including log file interpretation, vulnerability remediation, and evidence documentation. Emphasis is placed on critical thinking, decision-making, and the prevention of security regressions, ensuring that future software security professionals are prepared to deliver defensible, testable, and compliant code in diverse development environments. SECTION ONE: QUESTIONS 1– 150 Question 1 A developer is preparing to run a static analysis scan on a Python Flask application. Which tool is specifically designed to identify common security issues such as hardcoded passwords, use of eval(), and insecure deserialization? A. Flake B. Bandit
C. Pylint D. Black B. Bandit RATIONALE: Bandit is a static application security testing (SAST) tool built specifically for Python. It scans source code for common security anti-patterns, including hardcoded secrets, shell injection risks, and unsafe deserialization, making it the appropriate tool for security- focused analysis rather than pure style linting. Question 2 A Flake8 report flags an E722 error in a Python file. What does this finding indicate? A. An unused import statement. B. A bare except: clause without a specified exception type. C. A line exceeding the maximum length. D. An undefined variable name. B. A bare except: clause without a specified exception type. RATIONALE: Flake8 error code E722 indicates a bare except: clause. This is a security and reliability concern because it catches all exceptions, including system-exiting exceptions such as KeyboardInterrupt and SystemExit, and can mask critical errors or vulnerabilities. Question 3 A developer reviews a Bandit finding labeled B105: hardcoded_password_string. What is the most appropriate remediation? A. Rename the variable containing the string. B. Move the string to a different file. C. Remove the credential from source code and load it from a secret manager or environment variable at runtime. D. Encrypt the string using Base64. C. Remove the credential from source code and load it from a secret manager or environment variable at runtime. RATIONALE: Hardcoded credentials in source code must be treated as compromised. The correct remediation is removal from the codebase and runtime injection via a secure mechanism. Renaming, relocating, or encoding the string does not eliminate the exposure. Question 4
Question 7 A developer writes logger.info("EVENT: login_attempt | ACTION: user=%s" % username) in a security-sensitive application. What is the preferred logging practice? A. Using string concatenation with +. B. Using lazy %s formatting with arguments passed separately: logger.info("EVENT: login_attempt | ACTION: user=%s", username). C. Using an f-string. D. Writing the message to print() instead. B. Using lazy %s formatting with arguments passed separately: logger.info("EVENT: login_attempt | ACTION: user=%s", username). RATIONALE: Passing arguments separately to the logging call allows the logging framework to defer string formatting until the message is actually emitted, improving performance and ensuring consistent handling. Eager formatting with % or f-strings constructs the string even if the log level is disabled. Question 8 A try/except block is written to handle two distinct runtime errors. The requirement specifies one ERROR level log and one WARNING level log. Which configuration satisfies this requirement? A. Two ERROR logs in separate except blocks. B. One ERROR log and one WARNING log in separate except blocks, each catching a specific exception type. C. A single CRITICAL log for both exceptions. D. No logging; letting exceptions propagate. B. One ERROR log and one WARNING log in separate except blocks, each catching a specific exception type. RATIONALE: The requirement explicitly calls for differentiated severity levels across two exception handlers. Catching specific exception types preserves diagnostic precision and ensures that each error condition is logged at the appropriate severity. Question 9 What is the primary security concern with using a bare except: clause in a Flask route that handles database operations? A. It improves error visibility. B. It catches all exceptions, including system-exiting ones, and can silently suppress critical
failures or security-relevant errors. C. It prevents the application from logging errors. D. It causes the application to crash immediately. B. It catches all exceptions, including system-exiting ones, and can silently suppress critical failures or security-relevant errors. RATIONALE: A bare except: clause catches BaseException, including KeyboardInterrupt and SystemExit. This can mask serious faults, prevent graceful shutdown, and hide evidence of attacks or data corruption. Question 10 A developer uses assert user.is_authenticated to enforce an authentication check in production code. Why is this practice insecure? A. assert statements cannot check object attributes. B. Python's - O optimization flag removes assert statements from bytecode, silently disabling the security check. C. assert statements always raise SystemExit. D. assert statements cannot be used with boolean expressions. B. Python's - O optimization flag removes assert statements from bytecode, silently disabling the security check. RATIONALE: When Python is run with the - O (optimize) flag, assert statements are stripped from the compiled bytecode. Using assertions for security-critical validation can therefore result in those checks being entirely absent in optimized environments. Question 11 A developer wants to ensure that a security validation is enforced even under optimized Python execution. Which approach is appropriate? A. Use an assert statement with a descriptive message. B. Use an explicit if statement that raises an exception when the condition is not met. C. Use a comment indicating the required check. D. Use a print() statement for warning. B. Use an explicit if statement that raises an exception when the condition is not met. RATIONALE: Explicit conditional logic with exception raising is preserved under all optimization levels. This provides a reliable enforcement mechanism for security-critical validations, unlike assert statements.
Question 15 A developer needs to ensure that a function raises a ValueError when given invalid input. Which Pytest construct is most appropriate? A. with pytest.raises(ValueError): B. assert function(input) == None C. try: function(input) except: pass D. assert isinstance(input, ValueError) A. with pytest.raises(ValueError): RATIONALE: pytest.raises() is a context manager that asserts an exception of the specified type is raised within the block. It is the idiomatic Pytest mechanism for testing exception behavior. Question 16 A Bandit scan reports B301: pickle on a code segment that uses pickle.loads() on data received from an HTTP request. What is the primary risk? A. The data may be too large to process. B. Deserialization of untrusted data can execute arbitrary code. C. The pickle module is deprecated. D. The data may contain Unicode characters. B. Deserialization of untrusted data can execute arbitrary code. RATIONALE: The pickle module can execute arbitrary Python code during deserialization. Passing untrusted data to pickle.loads() allows an attacker to achieve remote code execution on the server. Question 17 A developer replaces pickle.loads() with json.loads() for parsing untrusted data. Why is this safer? A. JSON is faster than pickle. B. JSON parsing does not execute arbitrary code; it only produces standard data types. C. JSON is encrypted by default. D. JSON supports more data types than pickle. B. JSON parsing does not execute arbitrary code; it only produces standard data types. RATIONALE: json.loads() parses JSON into dictionaries, lists, strings, numbers, booleans, and
None. It does not support object instantiation or code execution, making it safe for untrusted input. Question 18 A developer is configuring logging for a Flask application. The requirement states that the log file must capture time, level, event, and action. Which log message format best satisfies this requirement? A. "User logged in" B. "EVENT: login | ACTION: authenticated user=%s" C. "200 OK" D. "Error occurred" B. "EVENT: login | ACTION: authenticated user=%s" RATIONALE: The format explicitly includes an EVENT: label and an ACTION: label, providing structured, searchable context. Combined with the timestamp and level from the logging configuration, this satisfies the four required elements. Question 19 A developer writes a Flask route that catches Exception as e and returns str(e) directly to the client. What security principle is violated? A. Least privilege. B. Information hiding and secure error handling. C. Separation of duties. D. Non-repudiation. B. Information hiding and secure error handling. RATIONALE: Returning raw exception messages to clients can expose internal paths, database schema, and implementation details. Error responses should be generic, with detailed information logged server-side only. Question 20 A unit test for a Flask application uses assert response.status_code == 403 after a standard user attempts to access an administrative endpoint. What security control is being validated? A. Authentication. B. Authorization. C. Rate limiting. D. Encryption.
C. compile() D. input() B. int() with input validation. RATIONALE: int() safely parses integer strings and raises ValueError for invalid input. Combined with validation, it eliminates the arbitrary code execution risk introduced by eval(). Question 24 A developer is instrumenting a Flask application with logging. Where should logging.basicConfig() ideally be called? A. Inside every route function. B. Once at the module level, near the top of the application entry point. C. Inside the database connection function. D. Inside a unit test. B. Once at the module level, near the top of the application entry point. RATIONALE: Configuring logging once at the application entry point ensures consistent formatting and destination across all modules. Reconfiguring inside routes or tests can lead to inconsistent or lost log records. Question 25 A unit test uses assert result == expected where result and expected are floating-point numbers. What is the recommended Pytest practice? A. Use exact equality with ==. B. Use pytest.approx() to account for floating-point precision. C. Convert both values to strings. D. Use assert result is expected. B. Use pytest.approx() to account for floating-point precision. RATIONALE: Floating-point arithmetic can introduce tiny rounding differences. pytest.approx() compares values within a configurable tolerance, preventing brittle tests that fail due to insignificant precision variations. Question 26 A developer reviews a code snippet that uses subprocess.call(command, shell=True) with a command built from user input. Which Bandit finding is most likely triggered? A. B105: hardcoded_password_string. B. B602: subprocess_popen_with_shell_equals_true.
C. B301: pickle. D. B303: md5. B. B602: subprocess_popen_with_shell_equals_true. RATIONALE: Bandit B602 flags the use of subprocess functions with shell=True, which invokes the system shell and enables command injection when the command string includes untrusted input. Question 27 What is the recommended remediation for a command injection vulnerability in Python? A. Escaping semicolons in user input. B. Using shell=False and passing arguments as a list. C. Converting the command to uppercase. D. Running the command with elevated privileges. B. Using shell=False and passing arguments as a list. RATIONALE: With shell=False, arguments are passed directly to the executable without shell interpretation. This prevents metacharacters in user input from being executed as commands. Question 28 A developer wants to ensure that a Flask application does not run with debug mode enabled in production. Which configuration setting must be False? A. TESTING B. DEBUG C. SECRET_KEY D. SESSION_COOKIE_SECURE B. DEBUG RATIONALE: Flask's debug mode exposes the Werkzeug interactive debugger, which can allow arbitrary code execution if accessed. DEBUG must be set to False in production. Question 29 A Pytest test verifies that a log file contains an entry with the level WARNING when a deprecated feature is used. Which assertion is most appropriate? A. assert "WARNING" in caplog.text B. assert "DEBUG" in caplog.text C. assert len(caplog.records) == 0 D. assert caplog.records[0].levelname == "ERROR"
C. Cross-site scripting. D. Buffer overflow. B. Log injection. RATIONALE: The attacker injected a newline character to create a forged log entry. This is log injection (log forging), which can be used to mislead investigators or conceal malicious activity. Question 33 Which Python logging level is most appropriate for recording a failed login attempt that does not indicate a system fault but is security-relevant? A. DEBUG B. INFO C. WARNING D. CRITICAL C. WARNING. RATIONALE: A failed login attempt is a security-relevant event that warrants attention but does not necessarily indicate a system failure. WARNING is the appropriate level for potentially harmful situations that should be reviewed. Question 34 A developer is reviewing a Bandit finding for B303: md5. What is the security concern? A. MD5 produces hashes that are too short. B. MD5 is cryptographically broken and unsuitable for security-sensitive applications such as password hashing or digital signatures. C. MD5 cannot be used in Python. D. MD5 automatically decrypts data. B. MD5 is cryptographically broken and unsuitable for security-sensitive applications such as password hashing or digital signatures. RATIONALE: MD5 is vulnerable to collision attacks and is not considered cryptographically secure. It should not be used for password hashing, integrity verification, or digital signatures. Question 35 A unit test for a security function uses a hardcoded expected value. Which practice improves the test's long-term maintainability and security relevance? A. Using a magic number without explanation. B. Using a clearly named constant or fixture with documented rationale.
C. Removing the assertion entirely. D. Using assert True. B. Using a clearly named constant or fixture with documented rationale. RATIONALE: Named constants and documented fixtures make the test's intent explicit and maintainable. This reduces the risk of tests becoming outdated or misunderstood as the codebase evolves. Question 36 A developer wants to verify that an application does not expose stack traces in HTTP responses. Which Pytest assertion is most appropriate? A. assert "Traceback" not in response.text B. assert "Traceback" in response.text C. assert response.status_code == 200 D. assert len(response.text) > 0 A. assert "Traceback" not in response.text RATIONALE: The assertion confirms that the response body does not contain a stack trace, which would reveal internal implementation details to an attacker. Question 37 A developer is reviewing a code snippet that catches Exception as e and logs logger.error("Error: " + str(e)). What improvement should be made? A. Use logger.error("Error occurred: %s", str(e)) for lazy formatting. B. Use print(e) instead. C. Remove the logging entirely. D. Use logger.critical() instead. A. Use logger.error("Error occurred: %s", str(e)) for lazy formatting. RATIONALE: Passing the exception string as an argument defers formatting until the log record is emitted, which is the recommended logging pattern. It also avoids premature string construction. Question 38 A developer is writing a Pytest test that checks whether a function handles a KeyError gracefully. Which construct is most appropriate? A. with pytest.raises(KeyError): B. assert function({}) == None
A Pytest test uses assert response.status_code == 302 after a login request. What does this status code typically indicate in a Flask application? A. The request was successful and returns the requested resource. B. The request resulted in a redirect, often to a post-login dashboard. C. The request was malformed. D. The server encountered an internal error. B. The request resulted in a redirect, often to a post-login dashboard. RATIONALE: HTTP 302 Found indicates a temporary redirect. In a Flask login flow, a successful authentication commonly redirects the client to a dashboard or home page, making 302 the expected status. Question 42 A developer wants to verify that a security fix does not introduce new vulnerabilities. Which practice is most appropriate? A. Running the full test suite and a static analysis scan after applying the fix. B. Deploying the fix without testing. C. Relying on the developer's intuition. D. Disabling security tests to avoid false positives. A. Running the full test suite and a static analysis scan after applying the fix. RATIONALE: Regression testing and static analysis help confirm that the fix is effective and that no new vulnerabilities have been introduced. This is a core practice of a secure software development lifecycle. Question 43 A developer is reviewing a Flake8 report and sees W292: no newline at end of file. What is the primary implication of this finding? A. It is a critical security vulnerability. B. It is a style and consistency issue that can cause problems with some tools and version control systems. C. It indicates a SQL injection flaw. D. It indicates a hardcoded secret. B. It is a style and consistency issue that can cause problems with some tools and version control systems. RATIONALE: W292 is a code style issue, not a direct security vulnerability. However,
consistent file formatting supports tooling reliability and code review clarity, which indirectly contribute to maintainability and security. Question 44 A developer is writing a unit test that mocks a database call to simulate a connection failure. What is the purpose of this test? A. To verify that the application crashes on database failure. B. To verify that the application handles the failure gracefully and logs the error appropriately. C. To measure database performance. D. To test the database schema. B. To verify that the application handles the failure gracefully and logs the error appropriately. RATIONALE: Mocking a database failure allows the test to focus on the application's error- handling logic without requiring an actual database outage. The test should confirm graceful degradation and appropriate logging. Question 45 A developer is reviewing a code snippet that uses logging.basicConfig(filename='app.log', level=logging.INFO). What is the effect of the level parameter? A. It sets the minimum severity level for messages to be processed by the logger. B. It sets the maximum severity level. C. It encrypts the log file. D. It rotates the log file automatically. A. It sets the minimum severity level for messages to be processed by the logger. RATIONALE: The level parameter filters messages below the specified severity. With level=logging.INFO, DEBUG messages are ignored, while INFO, WARNING, ERROR, and CRITICAL messages are processed. Question 46 A developer wants to ensure that a function logs a WARNING when a deprecated configuration key is used. Which logging call is most appropriate? A. logger.error("Deprecated key: %s", key) B. logger.warning("Deprecated key used: %s", key) C. logger.debug("Deprecated key: %s", key) D. logger.critical("Deprecated key: %s", key)
C. compile() D. input() B. json.loads() RATIONALE: json.loads() safely parses JSON into standard Python data types without executing code. It is the appropriate tool for structured configuration data that conforms to JSON syntax. Question 50 A developer wants to verify that a Flask application returns a generic error message rather than a detailed exception when an internal error occurs. Which assertion is most appropriate? A. assert "Internal Server Error" in response.text B. assert "Traceback" not in response.text C. assert response.status_code == 200 D. assert len(response.text) == 0 B. assert "Traceback" not in response.text RATIONALE: The assertion confirms that the response does not contain a stack trace, providing evidence that the application handles internal errors without exposing implementation details. Question 51 A developer is configuring logging for a Flask application and wants to ensure that log messages include the module name where the event occurred. Which format specifier is appropriate? A. %(asctime)s B. %(levelname)s C. %(module)s D. %(message)s C. %(module)s RATIONALE: %(module)s inserts the name of the module in which the logging call was made. This aids in debugging and incident analysis by identifying the source of the log event. Question 52 A developer is writing a unit test that checks whether a function returns None when given an empty list. Which assertion is most appropriate? A. assert function([]) is None B. assert function([]) == 0
C. assert function([]) == False D. assert function([]) is not None A. assert function([]) is None RATIONALE: Using is None is the recommended Python idiom for checking for the None singleton. It is more explicit and reliable than equality comparison for this purpose. Question 53 A developer is reviewing a Bandit finding for B404: import_subprocess. What does this finding indicate? A. The subprocess module is imported but not used. B. The subprocess module is imported, which may be used to execute system commands and requires careful handling. C. The subprocess module contains a known vulnerability. D. The subprocess module is deprecated. B. The subprocess module is imported, which may be used to execute system commands and requires careful handling. RATIONALE: Bandit flags the import of subprocess because the module can be used to execute external commands. It is not inherently vulnerable, but its use requires attention to input validation and shell invocation. Question 54 A developer wants to ensure that a security-sensitive function raises an exception when an invalid state is detected, regardless of Python optimization. Which construct should be used? A. assert condition, "Invalid state" B. if not condition: raise ValueError("Invalid state") C. print("Invalid state") D. logging.warning("Invalid state") B. if not condition: raise ValueError("Invalid state") RATIONALE: Explicit conditional logic with a raised exception is preserved under all optimization levels. It provides a reliable enforcement mechanism for security-critical state validation. Question 55 A Pytest test uses assert "password" not in caplog.text after executing a login function. What security property does this test validate?