






















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!























1. A security engineer runs Bandit on a Python module and receives a B608 warning for a SQL query constructed with string concatenation. Which remediation most effectively eliminates the vulnerability while preserving functionality?
A. Replace concatenation with an f-string using input validation. B. Use parameterized queries with a database driver that supports placeholders. C. Escape all single quotes in the user input before concatenation. D. Apply a web application firewall (WAF) rule to block SQL injection patterns.
Answer: B. Use parameterized queries with a database driver that supports placeholders.
Rationale: Parameterized queries separate SQL logic from data, preventing injection regardless of input content. Escaping quotes or using f-strings with validation can be bypassed and do not address the root cause. A WAF is a defense-in-depth measure, not a remediation.
2. In Python, which logging configuration best supports post-incident forensic analysis while minimizing performance overhead in a high-throughput service?
A. Logging to a file with DEBUG level and immediate flush after each record. B. Using a RotatingFileHandler with a size limit and a WARNING level. C. Logging to syslog with a custom formatter that includes thread ID and timestamp. D. Asynchronous logging with a QueueHandler and a dedicated listener thread.
Answer: D. Asynchronous logging with a QueueHandler and a dedicated listener thread.
Rationale: Asynchronous logging decouples I/O from application threads, reducing latency while still capturing detailed records for forensics. Immediate flush in option A introduces significant overhead. Options B and C may lose granularity or lack asynchronous benefits.
3. Consider the following Python code snippet:
**```python assert user.is_authenticated, "User not authenticated"
**Which statement accurately describes a security implication of using this assertion for access control?** A. Assertions are optimized away when Python runs with -O, potentially bypassing the check. B. Assertions raise AssertionError, which is a subclass of Exception and can be caught. C. Assertions should be used for input validation because they provide clear error messages. D. Assertions are thread-safe and cannot be disabled at runtime. **Answer: A. Assertions are optimized away when Python runs with -O, potentially bypassing the check.** _Rationale: When Python is run with the -O flag, assert statements are removed, so security checks based on assertions can be silently skipped. Assertions are intended for debugging, not for enforcing security controls. The other options misstate assertion behavior._ **4. A developer writes a custom exception class that inherits from Exception but does not call super().__init__(). What is the most likely consequence when this exception is raised and logged?** A. The exception message will be empty when str() is called on the instance. B. The exception will not be caught by except Exception clauses. C. The traceback will not include the original exception context. D. The exception will be automatically converted to a SystemExit. **Answer: A. The exception message will be empty when str() is called on the instance.** _Rationale: Without calling super().__init__(), the base Exception class does not receive the message argument, so str(exception) returns an empty string. The exception is still catchable and traceback behavior is unaffected. It is not converted to SystemExit._ **7. A team uses a static analysis tool that reports a high number of false positives. What is the most effective approach to improve the signal-to-noise ratio without missing critical vulnerabilities?** A. Disable all rules that produce false positives. B. Tune rule thresholds and add suppressions with justifications for known false positives. C. Only run the tool on changed files in pull requests. D. Replace the tool with a dynamic analysis tool. **Answer: B. Tune rule thresholds and add suppressions with justifications for known false positives.** _Rationale: Tuning rules and documenting suppressions reduces noise while preserving detection of real issues. Disabling rules outright may miss vulnerabilities. Running only on changed files may miss context. Dynamic analysis complements but does not replace static analysis._ **8. In exception handling, which pattern best prevents resource leaks when working with files or network connections?** A. Using a try/except block and closing the resource in the except clause. B. Using a try/finally block to ensure the resource is closed. C. Relying on the garbage collector to close the resource. D. Using a global variable to track open resources and closing them at program exit. **Answer: B. Using a try/finally block to ensure the resource is closed.** _Rationale: The try/finally block guarantees cleanup regardless of whether an exception occurs. Closing only in except misses the no-exception path. Garbage collection is non-deterministic. Global tracking is error-prone._ **9. A security analyst reviews a Python application and finds that it uses the pickle module to deserialize data from untrusted sources. Which remediation is most appropriate?** A. Use a restricted unpickler that only allows safe classes. B. Replace pickle with a safe serialization format like JSON and validate the schema. C. Encrypt the pickled data before transmission. D. Add a digital signature to the pickled data and verify it before deserialization. **Answer: B. Replace pickle with a safe serialization format like JSON and validate the schema.** _Rationale: Pickle is inherently unsafe for untrusted data; using JSON with schema validation eliminates the risk. Restricted unpicklers are complex and error-prone. Encryption and signatures do not prevent malicious payloads if the key is compromised or the signature is not verified properly._ **10. Which of the following best describes the role of assertions in a secure software development lifecycle?** A. Assertions should be used to enforce security invariants in production code. B. Assertions are primarily for internal consistency checks during development and testing. C. Assertions should replace exception handling for critical errors. D. Assertions are the preferred method for input validation in public APIs. **Answer: B. Assertions are primarily for internal consistency checks during development and testing.** _Rationale: Assertions are designed for debugging and internal sanity checks, not for enforcing security in production because they can be disabled. They should not replace exception handling or input validation, which must always be active._ _have levels, but the drop here occurs at the logger. Options A and C misstate inheritance; D confuses lastResort, which only applies when no handlers exist._ **13. In a pytest suite, `assert response.json()['user']['id'] == expected` fails with a KeyError rather than an assertion failure. Which remediation best preserves test intent and diagnosability?** A. Wrap the call in `try/except KeyError: pytest.fail()` with no message. B. Replace with `assert response.json().get('user', {}).get('id') == expected` so a missing key yields a clean assertion diff. C. Add `pytestmark = pytest.mark.filterwarnings('ignore')` to suppress the error. D. Convert to `assert expected in response.json()` to avoid indexing. **Answer: B. Replace with `assert response.json().get('user', {}).get('id') == expected` so a missing key yields a clean assertion diff.** _Rationale: Using `.get` chains converts a missing-key crash into a boolean assertion whose diff shows actual vs expected, preserving intent and diagnostics. Option A discards the value diff, C is unrelated to exceptions, and D weakens the assertion so it no longer verifies the id value._ **14. A service catches `Exception` at the top of `main()` and logs `logger.exception('failure')`, then exits 0. Which security-relevant defect does this introduce in a CI/CD pipeline?** A. None - logging the exception satisfies observability requirements. B. It masks failures as success, allowing a broken or partially compromised build to pass gates and deploy. C. It causes the exception traceback to be written to stdout instead of stderr, breaking log parsers. D. It prevents the exception from being logged because `logger.exception` requires an active handler. **Answer: B. It masks failures as success, allowing a broken or partially compromised build to pass gates and deploy.** _Rationale: Swallowing exceptions and exiting 0 hides failures from CI gates, which can promote insecure or broken artifacts. Option A ignores the exit-code regression, C misstates `logger.exception` output routing, and D is false since handlers are normally configured._ **17. A remediation ticket requires converting a `try/except Exception: pass` block around a crypto verification call. Which refactor best aligns with secure remediation principles?** A. Catch `Exception`, log at DEBUG, and continue. B. Catch the specific crypto exception, log at ERROR with context, and fail closed by raising or returning an error to the caller. C. Remove the try/except entirely so the process crashes on any error. D. Catch `BaseException` to also handle `KeyboardInterrupt` and `SystemExit`. **Answer: B. Catch the specific crypto exception, log at ERROR with context, and fail closed by raising or returning an error to the caller.** _Rationale: Fail-closed behavior with specific exception handling preserves security guarantees while providing diagnostics. Option A silently continues on verification failure (fail-open), C removes control over error signaling, and D improperly catches system-level exceptions._ **18. Which statement about `logger.exception()` versus `logger.error()` inside an `except` block is most accurate for security incident forensics?** A. They are identical; both include the traceback. B. `logger.exception()` automatically includes the active exception traceback, while `logger.error()` includes it only if `exc_info=True` is passed. C. `logger.error()` includes the traceback; `logger.exception()` does not. D. Neither includes the traceback; `traceback.print_exc()` is required. **Answer: B. `logger.exception()` automatically includes the active exception traceback, while `logger.error()` includes it only if `exc_info=True` is passed.** _Rationale: `logger.exception` is shorthand for `logger.error(..., exc_info=True)`, capturing the traceback for forensic reconstruction. Options A, C, and D misstate this behavior and would degrade incident analysis._ **19. A SAST baseline is introduced mid-project. The team wants to prevent new high-severity findings without blocking on legacy debt. Which approach best matches modern secure-SDLC practice?** A. Suppress all high-severity findings with `# nosec` comments. B. Fail the build only on findings not present in the committed baseline, while tracking baseline burn-down separately. C. Disable the SAST tool in CI and run it only quarterly. D. Set the severity threshold to LOW so everything is visible and blocking. **Answer: B. Fail the build only on findings not present in the committed baseline, while tracking baseline burn-down separately.** _Rationale: Baseline gating prevents regression while allowing incremental remediation of legacy debt, a standard secure-SDLC pattern. Option A hides issues, C removes continuous feedback, and D blocks all progress with pre-existing noise._ **20. A custom exception hierarchy defines `class AuthError(Exception)` and `class TokenExpired(AuthError)`. A caller writes `except AuthError:` before `except TokenExpired:`. What is the runtime consequence?** A. Both handlers run in declaration order. B. The `TokenExpired` handler is unreachable because `AuthError` matches first, so expired-token logic never executes. C. Python raises a SyntaxError at import time for overlapping handlers. D. The more specific handler runs first regardless of order. **Answer: B. The `TokenExpired` handler is unreachable because `AuthError` matches first, so expired-token logic never executes.** _Rationale: Python evaluates `except` clauses top-down, so the broader `AuthError` catches `TokenExpired` first, making the later handler dead code. Options A, C, and D misstate exception matching semantics._ **22. In a structlog-based service, a developer configures structlog.configure with a ProcessorFormatter that wraps the stdlib logging root handler. Which configuration error most likely causes structured key-value pairs to appear as a single opaque string in downstream JSON logs?** A. Setting structlog.processors.KeyValueRenderer as the final processor instead of JSONRenderer, so the event dict is stringified before the stdlib formatter serializes it. B. Omitting structlog.stdlib.add_log_level from the processor chain, causing the formatter to fall back to repr() of the event dict. C. Using structlog.stdlib.ProcessorFormatter.wrap_for_formatter without setting the foreign_pre_chain, which forces the stdlib formatter to escape the dict. D. Configuring the root logger with a plain logging.Formatter instead of ProcessorFormatter, so structlog's event dict is rendered by str() rather than serialized as JSON. **Answer: D. Configuring the root logger with a plain logging.Formatter instead of ProcessorFormatter, so structlog's event dict is rendered by str() rather than serialized as JSON.** _Rationale: ProcessorFormatter is required to convert structlog's event dict into a serializable payload; if the root handler uses a plain logging.Formatter, the dict is coerced via str() and appears as an opaque Python dict literal. Option A is wrong because KeyValueRenderer still produces structured (though non-JSON) output and does not cause a single opaque string. Option B is incorrect because add_log_level affects the level field, not dict serialization. Option C misstates the role of foreign_pre_chain, which only affects records originating from stdlib loggers._ **23. A test suite uses pytest with `assert` statements under `-O` optimization. Which statement best characterizes the risk of relying on bare `assert` for security-critical input validation in production code?** A. Bare asserts are always executed in production, so the risk is limited to performance overhead rather than correctness. B. Under -O, the interpreter strips assert statements, so validation that depends on them silently disappears, potentially allowing invalid input to proceed. C. Bare asserts raise AssertionError, which is a subclass of Exception and will be caught by a broad `except Exception` handler, masking the failure. D. Bare asserts are compiled to bytecode that cannot be optimized away, but they are unsuitable because they cannot include custom messages. **Answer: B. Under -O, the interpreter strips assert statements, so validation that depends on them silently disappears, potentially allowing invalid input to proceed.** _Rationale: CPython removes assert statements when run with -O (and -OO), so any validation implemented solely with assert is not enforced in optimized builds, a classic security anti-pattern. Option A is the opposite of the truth. Option C is true about AssertionError's hierarchy but does not address the -O stripping risk. Option D is incorrect because asserts can include messages and are indeed optimized away._ **24. Which exception-handling pattern best avoids both swallowing security-relevant failures and leaking sensitive data in logs when calling an external authentication API?** A. `except Exception as e: logging.error(f"auth failed: {e}"); return False` B. `except Exception: pass` followed by a generic failure response to the caller C. `except (requests.Timeout, requests.ConnectionError) as e: logging.warning("auth transport error", exc_info=True); raise AuthUnavailable from e` D. `except BaseException as e: logging.critical(str(e)); sys.exit(1)` **Answer: C. `except (requests.Timeout, requests.ConnectionError) as e: logging.warning("auth transport error", exc_info=True); raise AuthUnavailable from e`** _Rationale: Catching specific transport exceptions, logging with structured context (without embedding secrets), and re-raising a domain-specific exception preserves the failure signal and avoids leaking credentials. Option A logs the raw exception string, which may include request details or tokens, and returns a boolean that hides the cause. Option B swallows all_ **25. A SAST tool flags a potential path traversal in `open(os.path.join(BASE, user_path))`. Which remediation most robustly prevents traversal while preserving legitimate nested paths?** A. Reject any user_path containing the substring '..' before joining. B. Normalize with os.path.normpath and verify the result starts with BASE + os.sep using os.path.commonpath or Path.is_relative_to. C. URL-encode user_path so that '..' becomes '%2E%2E' and cannot traverse. D. Run the process as a non-root user so traversal cannot escape the container. **Answer: B. Normalize with os.path.normpath and verify the result starts with BASE + os.sep using os.path.commonpath or Path.is_relative_to.** _Rationale: Canonicalizing the joined path and verifying containment via commonpath/is_relative_to defeats traversal regardless of encoding or symlink tricks. Option A is bypassable via encoded or alternate separators and does not handle absolute paths. Option C is irrelevant because the filesystem does not decode URL encoding. Option D reduces impact but does not prevent traversal within accessible directories._ **26. A developer adds `logging.basicConfig(level=logging.DEBUG)` inside a library module's __init__.py. What is the most significant architectural problem this introduces?** A. It forces DEBUG-level output for the entire application and may leak sensitive data, while also preventing the host application from configuring handlers. B. It has no effect because basicConfig is idempotent and only the first call in a process takes effect. C. It causes a circular import because basicConfig imports the root logger, which imports the library. D. It disables propagation to the root logger, so library logs never reach application handlers. **Answer: A. It forces DEBUG-level output for the entire application and may leak sensitive data, while also preventing the host application from configuring handlers.** _Rationale: Library code should never call basicConfig because it mutates global logging state, sets a verbose level, and may add a handler before the application configures logging, causing duplicate or leaked output. Option B is misleading: basicConfig is a no-op only if the root logger already has handlers, but the side effect of setting level still occurs in some Python versions and the call is still an anti-pattern. Option C is false; there is no such_ _circular import. Option D is incorrect because basicConfig does not disable propagation._ _Option C is false; the GIL is not disabled by dev mode, and audit hooks are separate. Option D is false; dev mode is not a sandbox._ **29. A remediation ticket requires eliminating a `eval()` call used to parse configuration. Which replacement best preserves the intended expressiveness while eliminating arbitrary code execution?** A. `ast.literal_eval` on the raw string, which parses only Python literals. B. `exec` inside a restricted namespace with `__builtins__` set to None. C. `pickle.loads` on the string after base64-decoding it. D. `compile(source, '', 'eval')` followed by `eval(code, {})`. **Answer: A. `ast.literal_eval` on the raw string, which parses only Python literals.** _Rationale: ast.literal_eval safely evaluates only literal structures (strings, numbers, tuples, lists, dicts, booleans, None) and raises ValueError on other nodes, eliminating code execution. Option B is a known-unsafe pattern because restricted namespaces are bypassable. Option C introduces deserialization RCE. Option D still calls eval and offers no safety._ **30. A security review finds that a service logs `logger.info(f"user login: {username} token={token}")`. Which remediation best aligns with OWASP logging guidance and Python logging best practices?** A. Switch to lazy %-style formatting and exclude the token, logging only a hashed or truncated correlation identifier. B. Keep the f-string but set the logger level to WARNING so the message is not emitted in production. C. Wrap the log call in `if logger.isEnabledFor(logging.INFO)` to avoid formatting cost. D. Move the token into a custom LogRecord attribute so it is available to handlers but not in the message string. **Answer: A. Switch to lazy %-style formatting and exclude the token, logging only a hashed or truncated correlation identifier.** _Rationale: OWASP recommends never logging credentials or session tokens; replacing them with a non-reversible identifier and using lazy %-style formatting avoids both leakage and unnecessary string construction. Option B relies on level configuration that may change and still leaves the secret in code. Option C addresses performance, not confidentiality. Option D still places the secret in the log record, where handlers may serialize it._