
































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!

































EXAM INFORMATION
Subject: Software Security & Testing Questions: 50 | Format: Multiple choice Duration: 3 hours Passing score: 97%
ABOUT THIS EXAM
This exam covers static analysis, Python logging, assertions, exception handling, and remediation strategies for secure software development. It emphasizes practical application of tools and techniques to identify and mitigate vulnerabilities, with a focus on Python-specific implementations and industry best practices.
WHAT THIS COVERS
Detailed Explanations
Q A static analysis tool reports a potential SQL injection vulnerability in a Python function that constructs a query using string formatting. Which remediation strategy best addresses the root cause while maintaining functionality?
A (^) Replace string formatting with parameterized queries using the database driver's placeholder syntax.
CORRECT
B (^) Sanitize all user inputs by escaping single quotes and semicolons before concatenation.
C (^) Implement a web application firewall (WAF) rule to block SQL injection patterns.
D (^) Use an ORM exclusively for all database interactions without reviewing generated SQL.
EXPLANATION Parameterized queries separate SQL logic from data, preventing injection by design. Escaping is error-prone and bypassable; WAFs are defense-in-depth but not a fix; ORMs can still be misused and may not cover all cases.
Detailed Explanations
Q Which assertion strategy is most appropriate for validating preconditions in a Python function that is part of a security-critical authentication module?
A (^) Use assert statements to check that username and password are non-empty, as they are cheap and can be disabled with -O.
B (^) Raise ValueError with a descriptive message for invalid inputs, and document the expected types.
CORRECT
C (^) Rely on type hints and mypy static checking to enforce input validity at runtime.
D (^) Use assert statements with custom messages, and ensure the production environment runs with assertions enabled.
EXPLANATION Assertions can be disabled in optimized mode, making them unreliable for security checks. Raising explicit exceptions ensures validation always occurs. Type hints are not runtime enforced; relying on assertions is risky.
Detailed Explanations
Q A developer catches a broad Exception in Python and logs it with logging.error(e). What is the primary security concern with this approach?
A (^) It may log sensitive information from the exception message, such as credentials or PII.
CORRECT
B (^) It fails to capture the stack trace, hindering debugging.
C (^) It suppresses the exception, allowing the program to continue in an inconsistent state.
D (^) It logs at ERROR level, which may be filtered out in production.
EXPLANATION Exception messages can contain sensitive data; logging them may expose secrets. Option B is also true but less security-critical; C is about suppression; D is a logging level issue, not primary security concern.
Detailed Explanations
Q When using Python's logging module, which handler and formatter combination best supports forensic analysis after a security incident?
A (^) StreamHandler with a simple message format to console for real-time monitoring.
B (^) RotatingFileHandler with a detailed format including timestamp, log level, module, and process ID.
CORRECT
C (^) SysLogHandler sending logs to a remote syslog server with default formatting.
D (^) MemoryHandler buffering logs and flushing only on critical errors.
EXPLANATION RotatingFileHandler preserves logs with rotation, and detailed formatting aids forensics. Console logging is ephemeral; syslog may lack detail; MemoryHandler may lose logs on crash.
Detailed Explanations
Q Which exception handling anti-pattern is most likely to introduce a security vulnerability in a Python web application?
A (^) Catching specific exceptions like ValueError and returning a generic error message.
B (^) Using a bare except: clause that swallows all exceptions and continues execution.
CORRECT
C (^) Logging exceptions with logging.exception() and re-raising them.
D (^) Using finally blocks to release resources such as database connections.
EXPLANATION Bare excepts can hide critical errors, leading to inconsistent state and potential security bypasses. The other options are good practices or less risky.
Detailed Explanations
Q In Python, which logging level is most appropriate for recording security-relevant events such as failed login attempts, and why?
A (^) DEBUG, because it provides detailed information for troubleshooting.
B (^) INFO, because it indicates normal but significant events.
C (^) WARNING, because it indicates a potential issue that should be investigated.
CORRECT
D (^) ERROR, because it indicates a failure that requires immediate attention.
EXPLANATION Failed logins are potential security issues, so WARNING is appropriate. DEBUG is too verbose, INFO is for normal events, ERROR is for actual errors, not just attempts.
Detailed Explanations
Q Which of the following best describes the principle of remediation in the context of software security testing?
A (^) Remediation involves only patching the identified vulnerability without addressing root causes.
B (^) Remediation is the process of mitigating or eliminating vulnerabilities, including root cause analysis and preventive measures.
CORRECT
C (^) Remediation is solely the responsibility of the security team, not developers.
D (^) Remediation focuses on adding runtime protections like WAFs rather than code fixes.
EXPLANATION Remediation includes fixing the vulnerability and preventing recurrence. Option A is incomplete; C is incorrect as developers play a key role; D is a partial measure, not full remediation.
Detailed Explanations
Q A developer writes: try: risky(); except (ValueError, TypeError): logger.exception('failed'); raise SystemExit(1). During review, a senior engineer objects. Which critique is most accurate?
A (^) logger.exception should be logger.error because no exception is active in the handler.
B (^) SystemExit should be replaced with sys.exit(1) for portability across platforms.
C (^) Re-raising SystemExit masks the original exception's traceback and prevents upstream recovery.
CORRECT
D (^) Catching both ValueError and TypeError violates the single-responsibility principle.
EXPLANATION SystemExit is not a subclass of Exception and terminates the interpreter, discarding the chained traceback and preventing callers from handling the original error; use bare 'raise' or a custom exception. logger.exception is correct inside an except block (A), sys.exit raises SystemExit identically (B), and grouping exception types is idiomatic (D).
Detailed Explanations
Q A team configures Python logging with dictConfig using a RotatingFileHandler and a StreamHandler sharing one logger. During a burst of warnings, duplicate lines appear in the file but not on the console. Which configuration error most likely explains this?
A (^) The logger's propagate flag is True and a parent logger also has a RotatingFileHandler attached.
CORRECT
B The StreamHandler level is set to WARNING while the RotatingFileHandler level is DEBUG.
C (^) The formatter uses %(message)s without a timestamp, causing apparent duplicates.
D The RotatingFileHandler maxBytes is smaller than the burst size, triggering rotation mid-write.
EXPLANATION Duplicate records typically arise when a record propagates to an ancestor logger that also has a handler writing to the same destination; setting propagate=False or attaching handlers only at the root fixes it. Level mismatches (B) change filtering, not duplication, formatting (C) cannot duplicate lines, and rotation (D) does not duplicate records.
Detailed Explanations
Q A SAST tool reports a taint flow from request.args['q'] to cursor.execute(query). The developer adds html.escape(q) before the query. Which statement best characterizes the residual risk?
A (^) The flow is fully mitigated because escaping neutralizes all metacharacters.
B (^) The flow remains exploitable because HTML escaping does not address SQL context.
CORRECT
C (^) The flow is mitigated only if the database uses a UTF-8 collation.
D (^) The flow is mitigated because taint analyzers recognize html.escape as a sanitizer.
EXPLANATION Sanitizers are context-specific: HTML escaping is irrelevant in a SQL grammar, so injection persists and the taint flow should remain flagged. Option A overstates escaping, C confuses collation with sanitization, and D is false - most analyzers do not treat html.escape as a SQL sanitizer.
Detailed Explanations
Q During a code review, an engineer replaces 'except Exception as e: pass' with 'except Exception as e: logger.warning("op failed")'. What is the most significant remaining defect?
A (^) logger.warning is inappropriate; only logger.error should be used in except blocks.
B (^) The exception is swallowed without re-raising or preserving the traceback, hiding the failure.
CORRECT
C (^) The message string should be an f-string to include the exception details.
D (^) Catching Exception violates PEP 8 and should be replaced with a bare except.
EXPLANATION Logging without re-raising (or without logger.exception/stack_info) discards the exception context and lets execution continue in an unknown state - the core anti-pattern. logger.warning is acceptable (A), f-strings in log calls are discouraged but not the main defect (C), and bare except is worse than except Exception (D).
Detailed Explanations
Q A module defines class AuditError(Exception) with init(self, code, msg) that calls super().init(msg) and sets self.code. A caller does 'raise AuditError(42, "bad") from KeyError("k")'. Which statement about the resulting exception is correct?
A (^) str(exc) returns 'bad' and exc.cause is the KeyError instance.
CORRECT
B (^) str(exc) returns '(42, "bad")' because init overrides the message.
C (^) exc.context is None because 'from' clears the implicit context.
D (^) The KeyError is discarded because AuditError is not a subclass of it.
EXPLANATION super().init(msg) sets the args so str(exc) yields 'bad', and 'raise ... from ...' explicitly sets cause to the KeyError. Option B misstates args handling, C confuses context (still set) with cause, and D ignores chaining semantics.
Detailed Explanations
Q A reviewer sees: 'assert isinstance(user, Admin)'. The code then calls user.delete_all(). Which statement best explains why this pattern is a security weakness?
A (^) isinstance is too slow for security checks and should use type() instead.
B (^) Asserts can be disabled with -O, so the authorization check may vanish in production.
CORRECT
C (^) Admin is a subclass of User, so isinstance returns False and blocks access.
D (^) The assert raises AssertionError, which is not a subclass of Exception.
EXPLANATION Using assert for authorization is unsafe because the -O flag strips asserts, silently removing the check; explicit if/raise is required. Speed (A), subclass direction (C), and AssertionError's hierarchy (D, it is a subclass of Exception) are all incorrect.