Docsity

WGU D385 TASK 1 PERFORMANCE ASSESSMENT GUIDE SOFTWARE SECURITY & TESTING PYTHON LOGGING A,, Exams of Nursing

Toggle sidebar
bg1
Page 1
WGU D385 TASK 1 PERFORMANCE ASSESSMENT GUIDE
SOFTWARE SECURITY & TESTING PYTHON LOGGING A,
Exams of Computer Security - Questions and Answers Already
Graded A+ Premium Exam Tested And Verified
GRADED A+
ABSTRACT
This exam assesses mastery of secure software development, software testing
principles, and Python-specific logging and error handling. It emphasizes practical
application of OWASP Top 10 (2021), OWASP ASVS 4.x, NIST SP 800-218 SSDF,
and CWE/SANS Top 25 within the context of a performance assessment task.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16

Partial preview of the text

Download WGU D385 TASK 1 PERFORMANCE ASSESSMENT GUIDE SOFTWARE SECURITY & TESTING PYTHON LOGGING A, and more Exams Nursing in PDF only on Docsity!

WGU D385 TASK 1 PERFORMANCE ASSESSMENT GUIDE

SOFTWARE SECURITY & TESTING PYTHON LOGGING A,

Exams of Computer Security - Questions and Answers Already

Graded A+ Premium Exam Tested And Verified

GRADED A+

ABSTRACT

This exam assesses mastery of secure software development, software testing

principles, and Python-specific logging and error handling. It emphasizes practical

application of OWASP Top 10 (2021), OWASP ASVS 4.x, NIST SP 800-218 SSDF,

and CWE/SANS Top 25 within the context of a performance assessment task.

1. Which Python logging practice best prevents log injection per OWASP?

A. Use a custom Formatter that escapes newline characters in user input. B. Log user input directly without sanitization for audit fidelity. C. Rely on the logging module's default behavior to handle special characters. D. Encode all log messages in base64 before writing to file.

Answer: A. Use a custom Formatter that escapes newline characters in user

input.

OWASP recommends sanitizing user input before logging to prevent log injection, such as by escaping newline characters. Direct logging (B) is vulnerable; default behavior (C) does not sanitize; base64 (D) obscures but does not prevent injection.

2. In Python unittest, which assertion method checks that an exception is

raised?

A. assertRaises B. assertRaisesRegex C. assertException D. assertRaisesException

Answer: A. assertRaises

assertRaises is the standard unittest method to verify an exception is raised. assertRaisesRegex also checks the message but is more specific; the others are not real methods.

3. A developer uses Python's logging module with a FileHandler. Which risk

arises if log files are world-readable?

A. Log injection attacks become easier. B. Sensitive information may be exposed to unauthorized users. C. Log rotation will fail. D. The logging module will raise a PermissionError.

Answer: B. Sensitive information may be exposed to unauthorized users.

World-readable log files can leak sensitive data such as passwords or PII. Log injection (A) is unrelated to file permissions; rotation (C) and PermissionError (D) are not directly caused by world-readable permissions.

7. What is the primary purpose of static application security testing (SAST) in

Python?

A. To analyze source code for vulnerabilities without executing it. B. To monitor runtime behavior for anomalies. C. To test the application's response to malformed inputs. D. To verify the application's performance under load.

Answer: A. To analyze source code for vulnerabilities without executing it.

SAST analyzes source code statically to find security flaws. Runtime monitoring (B) is dynamic analysis; input testing (C) is fuzzing or dynamic testing; performance testing (D) is unrelated.

8. In Python, which exception handling practice is most secure when dealing

with sensitive operations?

A. Catch all exceptions and log the full stack trace including sensitive data. B. Catch specific exceptions and log a generic error message without details. C. Use a bare except clause to ensure no exceptions propagate. D. Suppress all exceptions to avoid denial of service.

Answer: B. Catch specific exceptions and log a generic error message without

details.

Catching specific exceptions and logging generic messages prevents information leakage. Logging full traces (A) may expose sensitive data; bare except (C) can hide bugs; suppressing (D) is insecure.

9. Which NIST SSDF practice emphasizes verifying software integrity through

automated testing?

A. PO.1: Define security requirements B. PS.1: Protect all forms of code C. PW.7: Review and/or analyze human-readable code D. PW.8: Test executable code

Answer: D. PW.8: Test executable code

PW.8 focuses on testing executable code to verify security. PO.1 is about requirements; PS.1 is about protecting code; PW.7 is code review.

10. A Python application uses the assert statement for input validation. Why

is this insecure in production?

A. Assertions are always executed, causing performance overhead. B. Assertions can be disabled with the -O flag, skipping validation. C. Assertions raise AssertionError which is not catchable. D. Assertions cannot check complex conditions.

Answer: B. Assertions can be disabled with the -O flag, skipping validation.

Python's -O flag disables assertions, so validation would be skipped in optimized mode. Assertions are not for production validation. Performance (A) is not the main issue; AssertionError is catchable (C); assertions can check complex conditions (D).

11. Which Python logging configuration most effectively prevents log injection

(CWE-117) in untrusted input?

A. Using a RotatingFileHandler with a maxBytes limit. B. Setting the formatter to include the raw message with no sanitization. C. Applying a custom Filter that escapes CR/LF characters in log records. D. Logging at DEBUG level to avoid writing to persistent storage.

Answer: C. Applying a custom Filter that escapes CR/LF characters in log

records.

Log injection occurs when untrusted input containing newline or control characters is written to logs, allowing forged entries. A custom logging.Filter that escapes CR/LF (and other control chars) before formatting mitigates CWE-117. RotatingFileHandler and log level do not sanitize content, and raw formatting preserves the injection vector.

14. A CI pipeline runs Bandit and reports B608 (SQL injection via string

formatting). Which remediation best satisfies SSDF PW.5?

A. Suppressing B608 with # nosec and documenting the risk. B. Replacing string-formatted SQL with parameterized queries. C. Increasing Bandit confidence threshold to HIGH. D. Moving the query into a separate module.

Answer: B. Replacing string-formatted SQL with parameterized queries.

B608 flags SQL built via string formatting; the root-cause fix is parameterized queries, which separate code from data and eliminate injection. Suppression, threshold tuning, and relocation only hide the weakness and violate SSDF secure coding practices.

15. In Python logging, which handler configuration prevents sensitive data

leakage while preserving auditability?

A. Logging full request bodies at INFO to the console. B. Using a Filter to redact PII fields before emission. C. Setting logger.disabled = True in production. D. Routing all logs to a world-readable file.

Answer: B. Using a Filter to redact PII fields before emission.

A logging.Filter can redact or mask PII/secret fields before records reach handlers, preserving audit trails without exposing sensitive data. Logging full bodies leaks data, disabling logging destroys auditability, and world-readable files violate confidentiality.

16. Which test design technique best achieves branch coverage for a function

with compound boolean guards?

A. Equivalence partitioning on numeric inputs only. B. Boundary value analysis at the endpoints. C. Condition/decision (MC/DC) test case derivation. D. Random fuzzing until no failures occur.

Answer: C. Condition/decision (MC/DC) test case derivation.

Modified condition/decision coverage ensures each atomic condition independently affects the decision outcome, which is necessary to exercise all branches of compound guards. Equivalence partitioning and boundary analysis target input domains, not boolean structure; random fuzzing gives no coverage guarantee.

17. A developer uses logging.basicConfig(level=logging.DEBUG) in production.

What is the primary security concern?

A. Increased log volume may fill disk, causing denial of service. B. DEBUG records may expose secrets and internal state to attackers. C. basicConfig disables exception tracebacks entirely. D. DEBUG level bypasses all formatters and filters.

Answer: B. DEBUG records may expose secrets and internal state to

attackers.

DEBUG-level logging frequently emits sensitive internals (tokens, PII, stack details) that aid attackers and violate least disclosure. Disk exhaustion is a secondary availability risk, not the primary security concern; basicConfig does not disable tracebacks or bypass filters.

20. When designing tests for a password reset function, which approach best

aligns with OWASP ASVS verification?

A. Testing only the happy path with valid tokens. B. Testing token entropy, expiry, single-use, and rate limiting. C. Verifying the UI displays a success message. D. Checking that the function returns HTTP 200.

Answer: B. Testing token entropy, expiry, single-use, and rate limiting.

ASVS requires verification of reset token strength, expiration, one-time use, and anti-automation controls, which are the security-critical properties. Happy-path, UI-message, and status-code checks do not verify the security controls and would miss exploitable weaknesses.

21. Which Python logging configuration most effectively prevents log injection

when user input is logged?

A. Using a custom Formatter that escapes newline and control characters in the message. B. Setting the logging level to DEBUG to capture all input for later analysis. C. Relying on the default logging module behavior, which automatically sanitizes input. D. Storing logs in a database instead of a file to avoid injection attacks.

Answer: A. Using a custom Formatter that escapes newline and control

characters in the message.

Log injection occurs when untrusted input containing newlines or control characters is written to logs, allowing attackers to forge log entries. A custom Formatter that escapes such characters mitigates this. The default logging module does not sanitize input, and DEBUG level or database storage does not prevent injection.

22. In unittest, what is the primary security risk of using assertEqual for

sensitive data comparisons?

A. It may leak sensitive data in failure messages, exposing secrets in logs. B. It performs a shallow comparison that can be bypassed by crafted objects. C. It uses a non-constant-time comparison, enabling timing side-channel attacks. D. It automatically logs both values to the root logger at DEBUG level.

Answer: A. It may leak sensitive data in failure messages, exposing secrets in

logs.

assertEqual includes the compared values in its failure message, which can expose sensitive data such as passwords or tokens in test logs. While non-constant-time comparison is a concern for cryptographic operations, the primary risk in unit tests is data leakage. The other options are incorrect: assertEqual does not use shallow comparison, nor does it automatically log to the root logger.

23. Which OWASP Top 10 2021 category is most directly mitigated by

comprehensive logging of authentication failures?

A. A01:2021 - Broken Access Control B. A02:2021 - Cryptographic Failures C. A09:2021 - Security Logging and Monitoring Failures D. A05:2021 - Security Misconfiguration

Answer: C. A09:2021 - Security Logging and Monitoring Failures

A09:2021 specifically addresses security logging and monitoring failures, including insufficient logging of authentication failures. While broken access control and misconfiguration can involve logging, the category explicitly focused on logging is A09. Cryptographic failures are unrelated to logging authentication events.

27. Which NIST SSDF practice most directly addresses the need for logging

security-relevant events?

A. PW.4: Reuse well-secured software B. PS.1: Protect all forms of code from unauthorized access C. RV.1: Identify and confirm vulnerabilities on an ongoing basis D. PW.8: Configure compilation, interpreter, and build tools to improve security

Answer: C. RV.1: Identify and confirm vulnerabilities on an ongoing basis

NIST SSDF RV.1 focuses on identifying and confirming vulnerabilities, which includes monitoring and logging security events to detect issues. The other practices relate to reuse, code protection, and build configuration, not directly to logging security events.

28. In secure coding, what is the primary purpose of input validation?

A. To ensure data conforms to expected format and reject malicious input. B. To sanitize output before rendering to prevent XSS. C. To encrypt sensitive data before storage. D. To log all user actions for auditing.

Answer: A. To ensure data conforms to expected format and reject malicious

input.

Input validation ensures that data meets expected format and constraints, rejecting potentially malicious input. Output sanitization, encryption, and logging are separate concerns. Input validation is a fundamental secure coding practice to prevent injection attacks.

29. Which Python logging practice best supports non-repudiation in security

auditing?

A. Logging to a local file with rotation B. Including timestamps and user identifiers in log records C. Using the DEBUG level for all events D. Storing logs in an easily modifiable database

Answer: B. Including timestamps and user identifiers in log records

Non-repudiation requires that actions can be attributed to a specific user and time. Including timestamps and user identifiers in log records supports this. Local files and modifiable databases are susceptible to tampering, and DEBUG level does not ensure non-repudiation.

30. In unit testing, what is the primary security concern with using mock

objects for authentication?

A. Mocks may not accurately simulate real authentication, leading to false confidence. B. Mocks always introduce SQL injection vulnerabilities. C. Mocks automatically log sensitive credentials. D. Mocks bypass all input validation, causing buffer overflows.

Answer: A. Mocks may not accurately simulate real authentication, leading

to false confidence.

Mocks are simplified replacements that may not replicate the security behavior of real authentication systems, potentially giving a false sense of security. They do not inherently introduce SQL injection, log credentials, or cause buffer overflows (which are not typical in Python).

31. A Python service logs a user-supplied parameter with %-formatting.

Which risk does this introduce?

A. Log injection via forged newlines enabling log forging B. Format-string vulnerability enabling arbitrary memory writes C. SQL injection through the logging handler's database backend D. Denial of service via excessive log rotation

Answer: A. Log injection via forged newlines enabling log forging

Using %-formatting with untrusted input allows attackers to inject newlines and forged log entries (CWE-117), corrupting audit trails. Python's %-formatting is memory-safe, so format-string memory corruption (B) does not apply; SQL injection (C) and log rotation DoS (D) are unrelated to this logging practice.

34. A developer uses assert statements for input validation in production

Python code. Why is this insecure?

A. Assertions are removed when Python runs with -O, disabling validation B. Assertions raise AssertionError, which is not an exception C. Assertions cannot check complex conditions D. Assertions are slower than if-statements and cause DoS

Answer: A. Assertions are removed when Python runs with -O, disabling

validation

Python's -O (optimize) flag strips assert statements, so validation logic disappears in production, enabling bypass (CWE-617). Assertions do raise AssertionError (B is false); they can check any condition (C false); performance (D) is not the security issue.

35. Which OWASP Top 10 2021 category is most directly mitigated by

parameterized logging and output encoding?

A. A03:2021 - Injection B. A01:2021 - Broken Access Control C. A02:2021 - Cryptographic Failures D. A05:2021 - Security Misconfiguration

Answer: A. A03:2021 - Injection

Injection flaws (including log injection and OS command injection) are mitigated by separating data from code, such as parameterized queries and proper output encoding. Parameterized logging prevents log forging, a form of injection. The other categories address access control, cryptography, and configuration, not injection.

36. A unit test for a password validator uses a hardcoded valid password.

Which testing principle does this violate?

A. Tests should not contain real credentials or sensitive data B. Tests must use mocking for all external dependencies C. Tests should assert only boolean outcomes D. Tests must be run in isolation from the network

Answer: A. Tests should not contain real credentials or sensitive data

Hardcoding real passwords in test code risks credential leakage and violates secure coding practices (CWE-798). Tests should use dummy or generated values. Mocking (B), boolean assertions (C), and network isolation (D) are not the primary issue here.

37. Which Python logging configuration prevents log injection by untrusted

input?

A. Using a custom Formatter that escapes newlines and control characters B. Setting the logging level to DEBUG C. Logging to a file instead of stdout D. Using the root logger for all messages

Answer: A. Using a custom Formatter that escapes newlines and control

characters

Escaping newlines and control characters in log messages prevents attackers from forging log entries (CWE-117). Changing level (B), destination (C), or logger hierarchy (D) does not address injection.

38. In test-driven development, what is the primary purpose of writing a failing

test first?

A. To ensure the test can detect the absence of the feature B. To measure code coverage before implementation C. To document the API for future maintainers D. To validate performance requirements early

Answer: A. To ensure the test can detect the absence of the feature

Writing a failing test first confirms the test is valid and will catch regressions; it ensures the test actually exercises the new functionality. Coverage (B), documentation (C), and performance (D) are secondary benefits, not the primary purpose.

41. A developer writes logger.debug(f"User input: {user_supplied}"). What

vulnerability does this introduce?

A. Log injection via CRLF characters enabling log forging B. Format string injection through unescaped braces C. Sensitive data exposure if user_supplied contains secrets D. Denial of service from excessive log volume

Answer: A. Log injection via CRLF characters enabling log forging

Unsanitized user input in log messages allows attackers to inject CRLF sequences (e.g., '\n') to forge log entries, a CWE-117 log injection vulnerability. While f-strings are not format-string vulnerable (unlike str.format with user-controlled format), the primary risk here is log injection. Sensitive data exposure is a separate concern (CWE-532) not caused by f-string interpolation per se.

42. Which unittest assertion correctly verifies that `validate_input("

43. A code review flags eval(request.form['expr']). Which remediation best

aligns with OWASP ASVS input validation requirements?

A. Wrap eval in a try/except block to catch syntax errors B. Replace eval with ast.literal_eval for safe literal parsing C. Sanitize input using a regex allowlist before eval D. Log the eval input for auditing before execution

Answer: B. Replace eval with ast.literal_eval for safe literal parsing

ast.literal_eval safely evaluates only Python literals, eliminating arbitrary code execution (CWE-95). Regex allowlisting (C) is insufficient for complex expressions and error-prone. try/except (A) does not prevent code execution. Logging (D) is detective, not preventive.

44. Which logging configuration prevents sensitive data leakage while

preserving auditability in production?

A. Set root logger level to DEBUG and log all request bodies B. Use a custom Filter that redacts PII fields before emission C. Disable all logging in production to avoid exposure D. Write logs to a world-readable file for transparency

Answer: B. Use a custom Filter that redacts PII fields before emission

A logging Filter can redact or mask sensitive fields (e.g., passwords, tokens) before they reach handlers, satisfying CWE-532 mitigation while retaining audit trails. DEBUG logging (A) increases exposure. Disabling logging (C) removes auditability. World-readable logs (D) worsen confidentiality.

45. In a test suite, setUp creates a database connection and tearDown closes

it. What is the primary risk if setUp raises an exception?

A. tearDown is still executed to clean up resources B. The test is skipped and tearDown is not called C. tearDown is not executed, potentially leaking resources D. The exception is suppressed and the test passes

Answer: C. tearDown is not executed, potentially leaking resources

If setUp fails, unittest does not call tearDown, so any resources acquired before the failure point may leak. This is a known unittest behavior; best practice is to use addCleanup or context managers. Options A and B are incorrect; D is false-the test errors.