Docsity

WGU D385 ZHN1 Task 2 – Software Security and Testing: Secure Coding, API Security, Python, Exams of Nursing

Partial preview of the text

Download WGU D385 ZHN1 Task 2 – Software Security and Testing: Secure Coding, API Security, Python and more Exams Nursing in PDF only on Docsity!

WGU D385 ZHN1 Task 2 – Software Security and Testing: Secure Coding, API Security, Python Vulnerability Remediation & Pytest Solutions Questions, answers, rationales and marking schemes

1. Which secure coding practice best mitigates SQL injection vulnerabilities in Python applications? A. Using parameterized queries with prepared statements [Correct answer] A explanation: Correct. Parameterized queries separate SQL code from data, so user input cannot alter the query structure. B. Escaping all single quotes in user input B explanation: Incorrect. Escaping quotes can be bypassed with other techniques (e.g., numeric injection) and is not sufficient. C. Storing database credentials in the source code C explanation: Incorrect. This is a security anti-pattern that exposes credentials; it does not prevent SQL injection. D. Using stored procedures without parameterization D explanation: Incorrect. Stored procedures can still be vulnerable if they concatenate user input into dynamic SQL. Answer: Using parameterized queries with prepared statements Rationale: Parameterized queries ensure that user input is treated as data, not executable code, preventing SQL injection attacks. Marking scheme: Correct answer: A (1 point). No partial credit. 2. What is the primary purpose of input validation in secure coding? A. To ensure that only properly formatted data is processed, reducing attack surface [Correct answer] A explanation: Correct. Input validation verifies data against expected rules, blocking many injection and data corruption attacks. B. To encrypt all user input before storage B explanation: Incorrect. Encryption protects confidentiality but does not validate input; it is not the primary purpose. C. To log all user actions for auditing C explanation: Incorrect. Logging is for auditing and monitoring, not for validating input. D. To improve application performance by caching input D explanation: Incorrect. Caching is unrelated to input validation; validation is about security and data integrity. Answer: To ensure that only properly formatted data is processed, reducing attack surface Rationale: Input validation checks that data meets expected format, type, and range, thereby preventing malicious or malformed input from causing harm. Marking scheme: Correct answer: A (1 point). No partial credit. 3. Which HTTP header is used to mitigate cross-site scripting (XSS) attacks by restricting sources of executable scripts?

B. Trust the file extension to determine file type B explanation: Incorrect. Extensions can be spoofed; content validation is necessary. C. Store files in the web root with original names for easy access C explanation: Incorrect. This allows direct access and potential execution of malicious files. D. Use client-side validation only to check file size D explanation: Incorrect. Client-side validation can be bypassed; server-side validation is essential. Answer: Validate file type and size, and store files outside the web root with randomized names Rationale: Validating file type and size prevents malicious files, and storing outside web root with randomized names prevents direct access and path traversal. Marking scheme: Correct answer: A (1 point). No partial credit.

6. Which API security implementation ensures that a client is authorized to access a specific resource? A. OAuth 2.0 with scopes [Correct answer] A explanation: Correct. Scopes define the level of access granted to an access token, enabling authorization. B. API keys B explanation: Incorrect. API keys identify the client but do not provide fine-grained authorization or user context. C. Basic authentication C explanation: Incorrect. Basic auth only authenticates the client; it does not handle authorization scopes. D. JWT without validation D explanation: Incorrect. JWT must be validated; without validation, it's insecure. Even with validation, scopes are needed for authorization. Answer: OAuth 2.0 with scopes Rationale: OAuth 2.0 with scopes allows fine-grained access control by granting tokens with specific permissions (scopes) for resources. Marking scheme: Correct answer: A (1 point). No partial credit. 7. What is the purpose of rate limiting in API security? A. To prevent abuse and denial-of-service attacks by limiting the number of requests [Correct answer] A explanation: Correct. Rate limiting helps protect resources from being overwhelmed. B. To encrypt API traffic B explanation: Incorrect. Encryption is provided by TLS, not rate limiting. C. To log all API requests C explanation: Incorrect. Logging is separate; rate limiting does not inherently log requests.

D. To authenticate users D explanation: Incorrect. Authentication is handled by mechanisms like OAuth or API keys, not rate limiting. Answer: To prevent abuse and denial-of-service attacks by limiting the number of requests Rationale: Rate limiting controls the number of requests a client can make in a given time frame, mitigating brute force and DoS attacks. Marking scheme: Correct answer: A (1 point). No partial credit.

8. Which Python vulnerability is mitigated by using the 'secrets' module instead of 'random' for generating tokens? A. Insecure randomness leading to predictable tokens [Correct answer] A explanation: Correct. 'secrets' uses a cryptographically secure random number generator, preventing prediction. B. SQL injection B explanation: Incorrect. SQL injection is prevented by parameterized queries, not by random number generation. C. Cross-site scripting C explanation: Incorrect. XSS is mitigated by output encoding and CSP, not by token generation. D. Path traversal D explanation: Incorrect. Path traversal is mitigated by validating file paths, not by random token generation. Answer: Insecure randomness leading to predictable tokens Rationale: The 'random' module is not cryptographically secure; 'secrets' generates cryptographically strong random numbers suitable for managing secrets. Marking scheme: Correct answer: A (1 point). No partial credit. 9. In pytest, which fixture scope would you use to ensure a fixture is created once per test session? A. session [Correct answer] A explanation: Correct. Session-scoped fixtures are created once per test session and shared across all tests. B. module B explanation: Incorrect. Module scope means the fixture is created once per module (test file). C. function C explanation: Incorrect. Function scope means the fixture is created for each test function. D. class D explanation: Incorrect. Class scope means the fixture is created once per test class. Answer: session

B. Use a fast hash like MD5 or SHA-1 without salt. B explanation: Incorrect. Fast hashes are vulnerable to brute-force and rainbow tables. C. Hash passwords with a strong, slow algorithm like bcrypt, scrypt, or Argon2, using a unique salt per password. [Correct answer] C explanation: Correct. Slow hashing with salt is the recommended practice. D. Encrypt passwords with a symmetric key stored in the source code. D explanation: Incorrect. Key management is poor, and encryption is reversible; hashing is preferred. Answer: Hash passwords with a strong, slow algorithm like bcrypt, scrypt, or Argon2, using a unique salt per password. Rationale: Password hashing with a slow algorithm and per-user salt protects against rainbow table and brute-force attacks. Storing plaintext or using fast hashes is insecure. Marking scheme: 1 point for correct option; 0 otherwise. Explanation required for full credit.

13. Which of the following is a secure method to prevent cross-site request forgery (CSRF) in a web application? A. Rely solely on HTTP referer header checks. A explanation: Incorrect. Referer can be spoofed or omitted, not reliable alone. B. Use only GET requests for state-changing operations. B explanation: Incorrect. GET requests are more easily forged and not suitable for state changes. C. Include a unique, unpredictable token in state-changing requests and validate it server-side. [Correct answer] C explanation: Correct. CSRF tokens are a robust defense. D. Disable all cookies to avoid CSRF. D explanation: Incorrect. Disabling cookies breaks functionality and doesn't address the core issue. Answer: Include a unique, unpredictable token in state-changing requests and validate it server-side. Rationale: CSRF tokens ensure that requests originate from the legitimate user session. Without validation, attackers can forge requests. Marking scheme: 1 point for correct option; 0 otherwise. Explanation required for full credit. 14. In the context of API security, what is the primary purpose of using OAuth 2.0? A. To securely store user passwords in a central database. A explanation: Incorrect. OAuth does not store passwords. B. To enable third-party applications to obtain limited access to an HTTP service, either on behalf of a resource owner or by allowing the third-party application to obtain access on its own behalf. [Correct answer] B explanation: Correct. This is the definition of OAuth 2.0.

C. To encrypt all API traffic using TLS. C explanation: Incorrect. TLS is separate; OAuth is about authorization. D. To provide a replacement for HTTP basic authentication. D explanation: Incorrect. OAuth can be used with various authentication methods but is not a direct replacement. Answer: To enable third-party applications to obtain limited access to an HTTP service, either on behalf of a resource owner or by allowing the third-party application to obtain access on its own behalf. Rationale: OAuth 2.0 is an authorization framework that allows delegated access without sharing credentials. It is not an authentication protocol per se, though often used with OpenID Connect. Marking scheme: 1 point for correct option; 0 otherwise. Explanation required for full credit.

15. Which of the following is a common vulnerability in Python applications that use the pickle module for deserialization? A. Arbitrary code execution. [Correct answer] A explanation: Correct. Pickle can execute code via reduce. B. SQL injection. B explanation: Incorrect. SQL injection is related to database queries, not pickle. C. Cross-site scripting (XSS). C explanation: Incorrect. XSS is a web output issue, not directly related to pickle. D. Denial of service via memory exhaustion. D explanation: Incorrect. While possible, code execution is the primary critical risk. Answer: Arbitrary code execution. Rationale: The pickle module can execute arbitrary code during deserialization, making it unsafe for untrusted data. Alternatives like JSON are safer. Marking scheme: 1 point for correct option; 0 otherwise. Explanation required for full credit. 16. What is the purpose of the pytest.mark.parametrize decorator? A. To skip a test conditionally. A explanation: Incorrect. That is done with pytest.mark.skipif. B. To run a test function multiple times with different sets of arguments. [Correct answer] B explanation: Correct. This is exactly what parametrize does. C. To group tests into classes. C explanation: Incorrect. Grouping is done with classes. D. To define fixtures for tests. D explanation: Incorrect. Fixtures are defined with @pytest.fixture. Answer: To run a test function multiple times with different sets of arguments.

B. Grant users only the minimum permissions necessary to perform their tasks. [Correct answer] B explanation: Correct. This is the definition. C. Allow all API endpoints to be accessed without authentication. C explanation: Incorrect. This is insecure. D. Use the same API key for all services. D explanation: Incorrect. This increases risk if compromised. Answer: Grant users only the minimum permissions necessary to perform their tasks. Rationale: Least privilege reduces the attack surface and limits damage from accidental or malicious actions. Marking scheme: 1 point for correct option; 0 otherwise. Explanation required for full credit.

20. Which of the following is a recommended practice for handling exceptions in secure Python code? A. Display full stack traces to end users for debugging. A explanation: Incorrect. Stack traces can reveal sensitive information. B. Avoid revealing sensitive information in error messages returned to users. [Correct answer] B explanation: Correct. This prevents information leakage. C. Ignore all exceptions to prevent crashes. C explanation: Incorrect. Ignoring exceptions can hide security issues. D. Use a single generic exception handler that catches all exceptions without logging. D explanation: Incorrect. Logging is important for security monitoring. Answer: Avoid revealing sensitive information in error messages returned to users. Rationale: Detailed error messages can leak system internals, stack traces, or data. Secure code logs details server-side and returns generic messages. Marking scheme: 1 point for correct option; 0 otherwise. Explanation required for full credit. 21. Which of the following is the most secure way to store a secret key in a Python application deployed to a cloud environment? A. Hard-code the key in the application source code. A explanation: Hard-coding secrets exposes them to anyone with access to the codebase and prevents rotation. It is a severe security risk. B. Use a dedicated secrets management service (e.g., AWS Secrets Manager, HashiCorp Vault) and retrieve the key at runtime. [Correct answer] B explanation: Correct. Secrets management services provide secure storage, fine-grained access control, auditing, and rotation, which are essential for production security. C. Store the key in a plaintext configuration file within the application directory. C explanation: Plaintext configuration files are easily accessible to attackers and may be accidentally committed to version control. They offer no protection.

D. Embed the key in a compiled Python bytecode file (.pyc). D explanation: Bytecode can be decompiled, and the key remains static and extractable. It does not provide secure storage or rotation. Answer: Use a dedicated secrets management service (e.g., AWS Secrets Manager, HashiCorp Vault) and retrieve the key at runtime. Rationale: Secrets should never be hard-coded or stored in version control. A secrets management service provides secure storage, access control, and auditability, and allows rotation without code changes. Marking scheme: 1 point for selecting the correct option (B).

22. When implementing JWT-based authentication in a Python API, which of the following practices is critical to prevent token forgery? A. Accept tokens with the 'none' algorithm to simplify development. A explanation: The 'none' algorithm means no signature, so anyone can forge tokens. It must never be accepted in production. B. Store the JWT secret in the client-side JavaScript code. B explanation: Client-side code is visible to users, exposing the secret and allowing token forgery. Secrets must remain server-side. C. Verify the token signature using the correct algorithm and secret/public key. [Correct answer] C explanation: Correct. Signature verification ensures the token was issued by a trusted party and has not been tampered with. D. Disable signature verification for performance reasons. D explanation: Disabling signature verification removes the ability to detect tampered or forged tokens, completely undermining JWT security. Answer: Verify the token signature using the correct algorithm and secret/public key. Rationale: JWT signatures ensure integrity and authenticity. Failing to verify the signature or accepting 'none' algorithm allows attackers to forge tokens. Always validate the signature with the expected algorithm. Marking scheme: 1 point for selecting the correct option (C). 23. Which of the following Python code snippets is vulnerable to command injection? A. os.system('ping ' + host) [Correct answer] A explanation: Correct (vulnerable). The host variable is concatenated directly into the shell command, so an attacker can inject commands (e.g., '; rm -rf /'). B. subprocess.run(['ping', host], shell=False) B explanation: This is safe because it passes arguments as a list and disables the shell, preventing command injection. C. subprocess.run(['ping', host], check=True) C explanation: This is safe because shell=False is the default; arguments are passed as a list, avoiding shell interpretation.

Rationale: The skipif marker allows conditional skipping of tests. It is useful for skipping tests based on platform, Python version, or availability of dependencies. Marking scheme: 1 point for selecting the correct option (C).

26. Which of the following is a secure method to prevent SQL injection in a Python application using SQLite? A. Use parameterized queries with placeholders (e.g., cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))). [Correct answer] A explanation: Correct. Parameterized queries ensure that user input is treated as data, not executable SQL, effectively preventing injection. B. Use string concatenation to build the query (e.g., cursor.execute('SELECT * FROM users WHERE id = ' + user_id)). B explanation: String concatenation allows attackers to inject SQL code by manipulating the input, leading to SQL injection vulnerabilities. C. Use f-strings to interpolate user input directly into the query. C explanation: F-strings insert values directly into the query string, which can be exploited for SQL injection. D. Escape single quotes in user input before concatenating into the query. D explanation: Manual escaping is error-prone and insufficient; attackers can use other techniques (e.g., comments, union) to bypass it. Parameterization is the robust solution. Answer: Use parameterized queries with placeholders (e.g., cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))). Rationale: Parameterized queries separate SQL code from data, preventing attackers from altering the query structure. String concatenation or f-strings are unsafe. Marking scheme: 1 point for selecting the correct option (A). 27. Which of the following is a security risk associated with using the eval() function on user input in Python? A. It can cause a memory leak. A explanation: While eval() might use memory, the primary security risk is code execution, not memory leaks. B. It can execute arbitrary code, leading to remote code execution. [Correct answer] B explanation: Correct. eval() evaluates any Python expression, so an attacker can inject code such as import('os').system('rm -rf /'). C. It automatically sanitizes user input. C explanation: eval() does not sanitize input; it executes it. This is the opposite of security. D. It only allows mathematical expressions. D explanation: eval() can execute any Python expression, not just mathematical ones. This misconception can lead to dangerous use. Answer: It can execute arbitrary code, leading to remote code execution.

Rationale: eval() interprets strings as Python expressions, so malicious input can execute arbitrary code. It should never be used on untrusted input. Use ast.literal_eval() for safe evaluation of literals. Marking scheme: 1 point for selecting the correct option (B).

28. In API security, what is the purpose of the OAuth 2.0 'scope' parameter? A. To define the expiration time of the access token. A explanation: Token expiration is controlled by parameters like 'expires_in', not by scopes. B. To encrypt the access token. B explanation: Scopes do not encrypt tokens; they define permissions. Token encryption is separate (e.g., JWE). C. To authenticate the client application. C explanation: Client authentication is handled by client credentials (ID and secret), not by scopes. D. To specify the level of access that the client is requesting. [Correct answer] D explanation: Correct. Scopes are used to request specific permissions, and the issued token is limited to those scopes. Answer: To specify the level of access that the client is requesting. Rationale: Scopes allow clients to request specific permissions, and the authorization server can limit the access token's capabilities. This enforces least privilege. Marking scheme: 1 point for selecting the correct option (D). 29. Which pytest feature allows you to run a test multiple times with different expected outcomes using a single test function? A. @pytest.mark.parametrize [Correct answer] A explanation: Correct. parametrize allows passing multiple sets of arguments and expected results to a test function. B. @pytest.fixture B explanation: fixture is used to provide test data or setup, but it does not inherently run the test multiple times with different values. C. @pytest.mark.skip C explanation: skip is used to skip tests, not to run them multiple times. D. @pytest.mark.xfail D explanation: xfail marks a test as expected to fail, but it does not parametrize inputs. Answer: @pytest.mark.parametrize Rationale: The parametrize decorator enables running the same test function with different input/output pairs, reducing code duplication and improving test coverage. Marking scheme: 1 point for selecting the correct option (A). 30. Which of the following is a secure way to handle user authentication in a Python web

32. Which Python standard library module provides a cryptographically secure way to generate random numbers suitable for security-sensitive applications? A. random A explanation: The random module implements pseudo-random number generators and is not suitable for security-sensitive applications because its output is predictable if the seed is known. B. secrets [Correct answer] B explanation: Correct. The secrets module is specifically designed for cryptographic security and should be used for generating tokens, passwords, and other security-sensitive data. C. uuid C explanation: The uuid module generates universally unique identifiers, but not all UUID versions are cryptographically secure; UUIDv1 and UUIDv4 may be predictable depending on the implementation and are not a substitute for a CSPRNG. D. hashlib D explanation: hashlib provides hashing algorithms, not random number generation. While it can be used to derive values from random inputs, it does not itself generate random numbers. Answer: secrets Rationale: The secrets module is designed for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets. It uses the most secure source of randomness available on the operating system. Marking scheme: 1 point for selecting option B. 33. In pytest, which built-in fixture is used to capture and inspect output written to stdout/stderr during a test? A. tmpdir A explanation: tmpdir provides a temporary directory unique to the test invocation, not output capture. B. monkeypatch B explanation: monkeypatch allows you to temporarily modify attributes, dictionaries, environment variables, etc., but does not capture output. C. capsys [Correct answer] C explanation: Correct. capsys captures writes to sys.stdout and sys.stderr and provides methods like readouterr() to access the captured output. D. caplog D explanation: caplog captures logging output, not stdout/stderr, and is used to inspect log records. Answer: capsys Rationale: The capsys fixture is a built-in pytest fixture that provides a way to capture text written to sys.stdout and sys.stderr during test execution. It allows you to read the captured output and optionally disable further capturing.

Marking scheme: 1 point for selecting option C.

34. When implementing token-based authentication for a Python API, which of the following practices best mitigates token replay attacks? A. Storing tokens in browser localStorage. A explanation: Storing tokens in localStorage makes them accessible to JavaScript, increasing the risk of XSS-based token theft. It does not mitigate replay attacks. B. Using long-lived tokens to reduce the need for frequent re-authentication. B explanation: Long-lived tokens increase the window for replay attacks if stolen. This is not a mitigation. C. Encoding user roles in the token payload without a signature. C explanation: Unsigned tokens can be tampered with, and encoding roles without a signature does not address replay. D. Using short-lived tokens with refresh tokens and validating token expiration on the server. [Correct answer] D explanation: Correct. Short-lived tokens limit the usefulness of a stolen token, and server-side expiration checks ensure expired tokens are rejected. Refresh tokens enable secure acquisition of new access tokens. Answer: Using short-lived tokens with refresh tokens and validating token expiration on the server. Rationale: Token replay attacks occur when an attacker captures a valid token and reuses it. Using short-lived access tokens reduces the window of opportunity, and server-side validation of expiration ensures that expired tokens are rejected. Refresh tokens allow obtaining new access tokens without re-authentication, and they should be protected and rotated. Marking scheme: 1 point for selecting option D. 35. Which of the following is a secure coding practice to prevent path traversal vulnerabilities in a Python file download endpoint? A. Validate the requested file path against a whitelist of allowed files or use a safe path join that resolves to a directory within an allowed base directory. [Correct answer] A explanation: Correct. Whitelisting or canonical path validation ensures that user input cannot escape the intended directory. B. Sanitize the filename by removing all dots and slashes. B explanation: While removing path separators may help, it can break legitimate filenames and is not a robust solution; attackers can use encoded characters or alternative separators. C. Rely on the web server's configuration to block path traversal. C explanation: While server configuration can help, application-level validation is necessary as defense in depth. Sole reliance on the server is insufficient. D. Use the user-supplied filename directly but restrict file extensions to .txt. D explanation: Restricting extensions does not prevent traversal to other directories containing .txt files; the path itself must be controlled.

Answer: Using the pytest.mark.skipif marker with a condition such as sys.version_info < (3, 8). Rationale: The pytest.mark.skipif marker allows you to skip a test if a given condition is true. You can use it to skip tests based on the Python version by checking sys.version_info. Marking scheme: 1 point for selecting option C.

38. When using the subprocess module in Python, which approach is most secure to prevent shell injection? A. Passing a single string with shell=True and sanitizing user input. A explanation: Even with sanitization, shell=True invokes a shell and can be risky; sanitization is error-prone. It's better to avoid the shell entirely. B. Passing a list of arguments to subprocess.run with shell=False. [Correct answer] B explanation: Correct. This avoids shell interpretation of metacharacters and is the recommended secure approach. C. Using os.system with a string command. C explanation: os.system runs the command through the shell and is vulnerable to injection. D. Using subprocess.call with shell=True and escaping quotes. D explanation: shell=True still invokes a shell; escaping quotes is insufficient to prevent injection. Answer: Passing a list of arguments to subprocess.run with shell=False. Rationale: Using a list of arguments with shell=False avoids invoking a shell, so shell metacharacters in arguments are not interpreted. This prevents shell injection vulnerabilities. Marking scheme: 1 point for selecting option B. 39. Which pytest fixture scope is most appropriate for a fixture that sets up a database connection that is expensive to create and should be shared across all tests in a module? A. function A explanation: function scope creates the fixture for each test function, which is expensive and not suitable for shared expensive setup. B. class B explanation: class scope creates the fixture once per class, which might be appropriate if tests are grouped in classes, but module is more common for module-level sharing. C. module [Correct answer] C explanation: Correct. module scope creates the fixture once per module, allowing all tests in that module to share the same connection, reducing overhead. D. session D explanation: session scope creates the fixture once per test session, which could lead to state leakage across modules and is not the most appropriate for module-level sharing. Answer: module Rationale: The module scope creates the fixture once per module, which is suitable for expensive setup like a database connection that can be shared across tests within the same module.

session scope would create it once per session, which might be too broad if tests in different modules need isolation. Marking scheme: 1 point for selecting option C.

40. In the context of API security, which HTTP status code should be returned when a client provides an invalid or expired access token? A. 401 Unauthorized [Correct answer] A explanation: Correct. 401 is used when authentication is required and has failed or has not been provided; an invalid or expired token falls under this. B. 403 Forbidden B explanation: 403 indicates that the server understood the request but refuses to authorize it, typically when the client is authenticated but lacks permission. It is not for invalid credentials. C. 400 Bad Request C explanation: 400 is for malformed request syntax or invalid parameters, not for authentication failures. D. 500 Internal Server Error D explanation: 500 indicates a server error, not a client authentication issue. Answer: 401 Unauthorized Rationale: HTTP 401 Unauthorized indicates that the request lacks valid authentication credentials for the target resource. An invalid or expired token means the client is not properly authenticated, so 401 is appropriate. The response should include a WWW-Authenticate header. Marking scheme: 1 point for selecting option A. 41. Which of the following best describes a secure approach to implementing API input validation to prevent injection attacks? A. Use a blacklist to block known malicious patterns such as '