Docsity

WGU D385 ZHN1 Task 2 – Software Security and Testing | Secure Coding, API Security Implem, Exams of Database Programming

Toggle sidebar
bg1
WGU D385 ZHN1 Task 2 – Software Security and Testing
| Secure Coding, API Security Implementation, Python
Vulnerability Remediation & Pytest Solutions |
2026/2027 Updated
SECTION 1: Secure Coding Principles and Foundations
Question 1: Which security principle states that a user or process should be
granted only the minimum permissions necessary to perform its required
function?
A. Defense in depth
B. Least privilege
C. Separation of duties
D. Fail-safe defaults
Correct Answer: B. Least privilege
Rationale: Least privilege is the core principle that restricts access rights to
the minimum level required for a legitimate task. It limits the blast radius of a
compromised account or process. Defense in depth (A) refers to layered controls,
separation of duties (C) divides critical functions among multiple actors, and fail-
safe defaults (D) means access is denied unless explicitly granted—related, but not
the definition of least privilege.
Question 2: A Python application constructs a SQL query by concatenating user
input directly into the string. Which vulnerability class does this introduce?
A. Cross-site scripting (XSS)
B. SQL injection (SQLi)
C. Path traversal
D. Insecure deserialization
Correct Answer: B. SQL injection (SQLi)
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28

Partial preview of the text

Download WGU D385 ZHN1 Task 2 – Software Security and Testing | Secure Coding, API Security Implem and more Exams Database Programming in PDF only on Docsity!

WGU D385 ZHN1 Task 2 – Software Security and Testing

| Secure Coding, API Security Implementation, Python

Vulnerability Remediation & Pytest Solutions |

2026/2027 Updated

SECTION 1: Secure Coding Principles and Foundations Question 1: Which security principle states that a user or process should be granted only the minimum permissions necessary to perform its required function? A. Defense in depth B. Least privilege C. Separation of duties D. Fail-safe defaults Correct Answer: B. Least privilege Rationale: Least privilege is the core principle that restricts access rights to the minimum level required for a legitimate task. It limits the blast radius of a compromised account or process. Defense in depth (A) refers to layered controls, separation of duties (C) divides critical functions among multiple actors, and fail- safe defaults (D) means access is denied unless explicitly granted—related, but not the definition of least privilege. Question 2: A Python application constructs a SQL query by concatenating user input directly into the string. Which vulnerability class does this introduce? A. Cross-site scripting (XSS) B. SQL injection (SQLi) C. Path traversal D. Insecure deserialization Correct Answer: B. SQL injection (SQLi)

Rationale: String concatenation of untrusted input into SQL allows an attacker to alter query logic (e.g., ' OR '1'='1). The secure remediation is parameterized queries or an ORM that binds parameters safely. XSS (A) targets browser rendering, path traversal (C) manipulates filesystem paths, and insecure deserialization (D) exploits object reconstruction—none are the direct result of SQL string concatenation. Question 3: In secure design, what does the principle of "fail-safe defaults" mean? A. The system should fail open to preserve availability. B. Access should be denied by default unless explicitly allowed. C. All errors should be logged with full stack traces. D. Default passwords must be changed after installation. Correct Answer: B. Access should be denied by default unless explicitly allowed. Rationale: Fail-safe defaults means the default state is denial—access is granted only through explicit configuration. This prevents accidental exposure when a rule is missing. Failing open (A) is the opposite and dangerous. Full stack traces in logs (C) can leak sensitive information, and changing default passwords (D) is good hygiene but not the definition of fail-safe defaults. Question 4: Which of the following is the most secure way to handle a secret API key in a Python application? A. Hard-code the key in the source file for simplicity. B. Store the key in a .env file excluded from version control and load it via environment variables. C. Commit the key to a private repository to share with the team. D. Embed the key in the Docker image as an environment variable at build time.

C. Strict-Transport-Security D. X-Frame-Options Correct Answer: B. Content-Security-Policy Rationale: Content-Security-Policy (CSP) restricts the origins from which scripts, styles, and other resources may load, dramatically reducing XSS impact. Access-Control-Allow-Origin (A) controls cross-origin resource sharing, Strict- Transport-Security (C) forces HTTPS, and X-Frame-Options (D) mitigates clickjacking by controlling framing—not script execution. Question 7: A developer uses pickle.loads() on data received from an untrusted network source. Why is this dangerous? A. Pickle is slower than JSON and may cause a denial of service. B. Pickle can execute arbitrary code during deserialization. C. Pickle does not support Unicode characters. D. Pickle automatically encrypts data, hiding malicious payloads. Correct Answer: B. Pickle can execute arbitrary code during deserialization. Rationale: Python's pickle module can invoke arbitrary callables during unpickling, enabling remote code execution (CWE-502). The secure remediation is to use a safe format such as JSON for untrusted data and never unpickle untrusted input. Performance (A) and Unicode (C) are irrelevant to the security risk; pickle does not encrypt data (D). Question 8: Which of the following best describes "defense in depth"? A. Using a single, very strong firewall at the network perimeter. B. Layering multiple independent security controls so that failure of one does not compromise the system. C. Encrypting the entire database with one master key. D. Relying on input validation as the only control against injection.

Correct Answer: B. Layering multiple independent security controls so that failure of one does not compromise the system. Rationale: Defense in depth assumes that any single control can fail, so multiple overlapping controls (validation, encoding, least privilege, monitoring, encryption) are used. A single perimeter firewall (A) is not layered, whole- database encryption (C) is a single control, and relying solely on input validation (D) violates the principle. Question 9: What is the secure alternative to using shell=True with user-controlled input in Python's subprocess module? A. Use os.system() instead. B. Pass arguments as a list and avoid shell=True. C. URL-encode the input before passing it to the shell. D. Prefix the command with sudo. Correct Answer: B. Pass arguments as a list and avoid shell=True. Rationale: Using shell=True invokes the system shell, which interprets metacharacters and enables command injection (CWE-78). Passing a list of arguments with shell=False (the default) avoids shell interpretation. os.system() (A) is even more shell-dependent, URL-encoding (C) does not neutralize shell metacharacters, and sudo (D) increases privilege rather than fixing injection. Question 10: Which type of testing evaluates a running application by sending crafted requests and observing responses, without access to source code? A. Static Application Security Testing (SAST) B. Dynamic Application Security Testing (DAST) C. Software Composition Analysis (SCA) D. Unit testing Correct Answer: B. Dynamic Application Security Testing (DAST)

validation (A) is a different control, compression (C) is unrelated to security, and encryption (D) protects confidentiality, not rendering safety. Question 13: A web application returns detailed stack traces to users when an error occurs. Which security principle does this violate? A. Least privilege B. Fail-safe defaults C. Information hiding / avoiding information leakage D. Separation of duties Correct Answer: C. Information hiding / avoiding information leakage Rationale: Stack traces can reveal file paths, library versions, database schema, and internal logic—useful reconnaissance for attackers. Production systems should return generic error messages while logging details server-side. Least privilege (A), fail-safe defaults (B), and separation of duties (D) address access control, not error-message disclosure. Question 14: Which of the following is a secure way to store user passwords in Python? A. Store the plaintext password encrypted with AES. B. Store a salted hash using a slow algorithm such as bcrypt, scrypt, or Argon2. C. Store an MD5 hash of the password. D. Store the password in a cookie for session management. Correct Answer: B. Store a salted hash using a slow algorithm such as bcrypt, scrypt, or Argon2. Rationale: Passwords should be hashed with a salt and a deliberately slow, memory-hard algorithm to resist brute-force and rainbow-table attacks. Reversible encryption (A) means a breach exposes all passwords. MD5 (C) is fast and

cryptographically broken for password storage. Cookies (D) are client-side and unsafe for storing secrets. Question 15: In the context of API security, what is Broken Object Level Authorization (BOLA)? A. A failure to validate that the authenticated user is allowed to access the specific object referenced by an identifier. B. A failure to encrypt API responses. C. A failure to rate-limit API requests. D. A failure to log API errors. Correct Answer: A. A failure to validate that the authenticated user is allowed to access the specific object referenced by an identifier. Rationale: BOLA (also called IDOR—Insecure Direct Object Reference) occurs when an API exposes an object identifier and does not verify that the requester owns or has permission for that object. It is the top API security risk. Encryption (B), rate limiting (C), and logging (D) are separate concerns. Question 16: What does the os.path.basename() function help prevent when handling uploaded filenames? A. SQL injection B. Path traversal C. Cross-site scripting D. Insecure deserialization Correct Answer: B. Path traversal Rationale: os.path.basename() strips directory components from a filename, preventing an attacker from using sequences such as ../../etc/passwd to escape the intended upload directory (CWE-22). It does not address SQL injection (A), XSS (C), or deserialization (D).

Question 19: What is the primary security concern with using eval() on user- supplied input in Python? A. It may cause a memory leak. B. It can execute arbitrary Python code. C. It only works with integers. D. It automatically escapes HTML. Correct Answer: B. It can execute arbitrary Python code. Rationale: eval() parses and executes a Python expression, so untrusted input can run arbitrary code, read files, or make network calls. Safe alternatives include ast.literal_eval() for literals or explicit parsing. Memory leaks (A), integer-only restrictions (C), and HTML escaping (D) are incorrect. Question 20: Which HTTP status code is most appropriate when an authenticated user attempts to access a resource they are not authorized to view? A. 400 Bad Request B. 401 Unauthorized C. 403 Forbidden D. 404 Not Found Correct Answer: C. 403 Forbidden Rationale: 403 indicates the server understood the request but refuses to authorize it—the user is authenticated but lacks permission. 401 (B) means authentication is missing or invalid. 400 (A) indicates malformed input, and 404 (D) is used when the resource does not exist (though sometimes deliberately used to hide existence). SECTION 2: Web Security and OWASP Top 10 (Questions 21–45) Question 21: Which OWASP Top 10 category primarily covers SQL injection, command injection, and LDAP injection?

A. Broken Access Control B. Injection C. Security Misconfiguration D. Cryptographic Failures Correct Answer: B. Injection Rationale: Injection occurs when untrusted data is sent to an interpreter as part of a command or query. SQLi, command injection, and LDAP injection are canonical examples. Broken access control (A) concerns permissions, misconfiguration (C) concerns insecure settings, and cryptographic failures (D) concern weak or missing encryption. Question 22: A web application reflects user input directly into the HTML response without escaping. Which vulnerability is most likely? A. Stored XSS B. Reflected XSS C. CSRF D. SQL injection Correct Answer: B. Reflected XSS Rationale: Reflected XSS occurs when user input is immediately returned in the response without proper output encoding, allowing a crafted link to execute script in the victim's browser. Stored XSS (A) persists the payload server-side. CSRF (C) forces state-changing requests, and SQLi (D) targets the database. Question 23: Which control is the most direct mitigation for cross-site request forgery (CSRF)? A. Parameterized queries B. Anti-CSRF tokens validated server-side

C. It prevents the use of HTTPS. D. It automatically enables SQL injection. Correct Answer: B. Attackers can easily guess or find the default credentials and gain unauthorized access. Rationale: Default credentials are published in documentation and widely known; failing to change them is a security misconfiguration that enables trivial unauthorized access. Performance (A), HTTPS (C), and SQLi (D) are unrelated. Question 26: Which of the following is a secure way to prevent XSS in a Python web template? A. Disable auto-escaping to improve performance. B. Use context-aware auto-escaping provided by the template engine. C. Store all user input in a database without validation. D. Rely on client-side JavaScript validation only. Correct Answer: B. Use context-aware auto-escaping provided by the template engine. Rationale: Modern template engines (Jinja2, Django templates) auto-escape by default for HTML contexts. Disabling it (A) reintroduces XSS. Storing unvalidated input (C) and relying on client-side validation (D) do not prevent server-side rendering vulnerabilities. Question 27: What does the X-Content-Type-Options: nosniff header prevent? A. SQL injection B. MIME type sniffing that can lead to script execution C. Cross-site request forgery D. Directory traversal Correct Answer: B. MIME type sniffing that can lead to script execution

Rationale: nosniff instructs browsers not to guess a response's MIME type, preventing attacks where a file is misinterpreted as executable script. It does not directly address SQLi (A), CSRF (C), or path traversal (D). Question 28: A login form returns different error messages for "invalid username" versus "invalid password." What vulnerability does this introduce? A. SQL injection B. User enumeration C. Cross-site scripting D. Insecure deserialization Correct Answer: B. User enumeration Rationale: Distinct error messages allow attackers to determine which usernames exist, enabling targeted brute-force or credential-stuffing attacks. The secure practice is a generic message such as "Invalid username or password." SQLi (A), XSS (C), and deserialization (D) are different vulnerability classes. Question 29: Which OWASP Top 10 category is most associated with using outdated libraries with known CVEs? A. Vulnerable and Outdated Components B. Injection C. Broken Access Control D. Identification and Authentication Failures Correct Answer: A. Vulnerable and Outdated Components Rationale: This category covers risks from using components (libraries, frameworks, dependencies) with known vulnerabilities or unsupported versions. Remediation includes software composition analysis, timely patching, and dependency pinning. Injection (B), access control (C), and authentication (D) are separate categories.

A. Using parameterized SQL queries. B. Leaving directory listing enabled on a production web server. C. Enabling HTTPS with HSTS. D. Applying the principle of least privilege to database accounts. Correct Answer: B. Leaving directory listing enabled on a production web server. Rationale: Directory listing exposes files that should not be browsable, aiding reconnaissance and data exposure. Parameterized queries (A), HSTS (C), and least privilege (D) are secure practices, not misconfigurations. Question 33: What is the primary defense against log injection attacks? A. Encrypting log files. B. Sanitizing outbound log messages by encoding or removing control characters. C. Storing logs in a database. D. Using a single log level for all events. Correct Answer: B. Sanitizing outbound log messages by encoding or removing control characters. Rationale: Log injection occurs when attackers insert newline or control characters to forge log entries or exploit log parsers. Encoding or stripping these characters in outbound messages prevents injection. Encryption (A) protects confidentiality, database storage (C) is unrelated, and a single log level (D) reduces visibility. Question 34: Which HTTP method is considered "safe" and should not change server state? A. POST B. GET

C. PUT

D. DELETE

Correct Answer: B. GET Rationale: GET is defined as a safe, idempotent method for retrieving resources; it should not cause side effects. POST (A), PUT (C), and DELETE (D) are state-changing methods. Using GET for state changes can enable CSRF and caching issues. Question 35: What is the risk of using a wildcard (*) in the Access-Control-Allow- Origin CORS header on an API that handles sensitive data? A. It enables SQL injection. B. It allows any origin to read responses, potentially exposing sensitive data. C. It disables HTTPS. D. It causes the API to return 500 errors. Correct Answer: B. It allows any origin to read responses, potentially exposing sensitive data. Rationale: A wildcard CORS policy permits any website to make cross-origin requests and read responses, undermining the same-origin policy. Sensitive APIs should use an allowlist of trusted origins and avoid credentials with wildcard origins. SQLi (A), HTTPS (C), and server errors (D) are unrelated. Question 36: In the context of OWASP Top 10, what is "Security Logging and Monitoring Failures"? A. The failure to encrypt log files. B. Insufficient logging, detection, monitoring, and active response to breaches. C. The failure to use a centralized log server. D. The failure to delete logs after 30 days.

Rationale: SameSite=Strict prevents the browser from sending the cookie on cross-site requests, significantly reducing CSRF risk. It does not address SQLi (A), path traversal (C), or deserialization (D). Question 39: Which type of XSS persists the malicious payload on the server and affects every user who views the compromised page? A. Reflected XSS B. DOM-based XSS C. Stored XSS D. Blind XSS Correct Answer: C. Stored XSS Rationale: Stored XSS saves the payload (e.g., in a comment or profile field) and serves it to subsequent visitors. Reflected XSS (A) is immediately reflected without persistence, DOM-based XSS (B) executes in the client-side DOM, and blind XSS (D) fires in a different context (e.g., admin panel). Question 40: What is the security purpose of Subresource Integrity (SRI) in a web page? A. To encrypt third-party scripts. B. To verify that a fetched resource matches an expected cryptographic hash. C. To block all cross-origin requests. D. To compress JavaScript files. Correct Answer: B. To verify that a fetched resource matches an expected cryptographic hash. Rationale: SRI allows a page to specify a hash for an external script or stylesheet; the browser refuses to execute it if the hash does not match, protecting against tampered CDN content. It does not encrypt (A), block all cross- origin requests (C), or compress (D).

Question 41: A web application uses sequential, predictable session identifiers. Which attack is most facilitated? A. SQL injection B. Session prediction/hijacking C. Cross-site scripting D. Denial of service Correct Answer: B. Session prediction/hijacking Rationale: Predictable session IDs allow an attacker to guess another user's session token and hijack their session. Session IDs must be generated with a CSPRNG (e.g., secrets.token_urlsafe()). SQLi (A), XSS (C), and DoS (D) are separate attack types. Question 42: Which of the following is a secure practice for handling errors in a production web application? A. Display the full stack trace to the user. B. Log detailed errors server-side and return a generic message to the user. C. Suppress all errors silently. D. Include the database connection string in the error page. Correct Answer: B. Log detailed errors server-side and return a generic message to the user. Rationale: This balances troubleshooting with information hiding. Full stack traces (A) and connection strings (D) leak sensitive details, while silent suppression (C) removes auditability and can mask attacks. Question 43: What is the primary security benefit of using HTTPS with TLS for an API?