












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!













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. It contains 50 multiple-choice questions, each with four distractors and a fully worked rationale that explains why the keyed answer is correct. Questions are organized into clearly labelled sections that mirror the major content areas of the course. Targeted learning outcomes include: Apply static analysis tools to detect security vulnerabilities in source code.; Implement effective logging and assertion strategies for debugging and security monitoring.; Design robust exception handling and remediation plans for common software weaknesses.. Every item has been reviewed for clinical accuracy, current guidelines, and clarity so that students can study with confidence and self-correct as they work through the bank. Use it as a high-yield review immediately before the exam, or as a structured practice tool during the unit - the rationales double as concise teaching notes. The recommended writing time is 3 hours, with a passing score of 70%. Aligned with Aligned with ABET and ACM/IEEE curricular standards for software engineering and cybersecurity. standards and reflects the question style commonly seen on accredited program examinations. Students consistently achieving above the cut score on this bank have historically gone on to earn A+ on the corresponding course exam. Read every stem carefully - distractors are written to look plausible, and
Section 1: General (Questions 1-50)
1 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.
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.
Answer: A Rationale: 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.
2 In Python's logging module, which configuration ensures that log records are written to a file only when an exception occurs, while still capturing full stack traces?
A) Set the logging level to ERROR and use a FileHandler with a formatter that includes %(exc_info)s.
B) Use a try-except block that calls logging.exception() within the except clause, with a FileHandler configured.
C) Configure a SMTPHandler to email logs on exceptions and a FileHandler for all levels.
D) Use logging.basicConfig(filename='app.log', level=logging.CRITICAL) and call logging.critical() in except blocks.
Answer: B Rationale: logging.exception() automatically logs an ERROR-level message with exception information. Option A would log all errors, not just exceptions; C sends emails; D only logs critical messages and misses stack traces unless explicitly passed.
3 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.
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.
Answer: B Rationale: 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.
4 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.
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.
B) Using a bare except: clause that swallows all exceptions and continues execution.
C) Logging exceptions with logging.exception() and re-raising them. D) Using finally blocks to release resources such as database connections.
Answer: B Rationale: Bare excepts can hide critical errors, leading to inconsistent state and potential security bypasses. The other options are good practices or less risky.
8 A static analysis tool flags a potential path traversal vulnerability in a Python file download function. Which code change effectively remediates this?
A) Use os.path.basename() on the user-supplied filename before constructing the path.
B) Validate the filename against a whitelist of allowed filenames. C) Use os.path.realpath() to resolve the absolute path and ensure it starts with the intended base directory.
D) Encode the filename using URL encoding before use.
Answer: C Rationale: realpath() canonicalizes the path, preventing traversal outside the base directory. basename() may not handle all cases; whitelisting is good but less general; URL encoding does not prevent traversal.
9 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. D) ERROR, because it indicates a failure that requires immediate attention.
Answer: C Rationale: 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.
10 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.
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.
Answer: B Rationale: 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.
11 A security engineer runs Bandit on a Python module and receives a B (hardcoded_sql_expressions) finding for a query built with an f-string that interpolates a variable validated by a strict regex allowlist. Which remediation best preserves functionality while eliminating the finding?
A) Add '# nosec' with a comment documenting the allowlist validation. B) Convert the f-string to a parameterized query using the DB-API placeholder style.
C) Replace the f-string with str.format() and pass the variable as a format argument.
D) Wrap the query execution in a try/except and log the SQLException on failure.
Answer: B Rationale: Bandit's B608 flags string-formatted SQL regardless of upstream validation; the canonical fix is parameterization, which separates code from data and satisfies the analyzer. Suppressing with '# nosec' (A) hides the issue without fixing it, str.format (C) is still string interpolation flagged by B608, and try/except (D) addresses error handling, not injection.
12 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.
D) Catching both ValueError and TypeError violates the single-responsibility principle.
Answer: C Rationale: SystemExit is not a subclass of Exception and terminates the interpreter, discarding the chained traceback and preventing callers from handling the original
15 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.
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.
Answer: B Rationale: 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.
16 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.
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.
Answer: B Rationale: 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).
17 A CI pipeline fails because pylint emits W0703 (broad-except) on a handler that intentionally catches all exceptions to log and re-raise. Which action best aligns with secure-coding best practice?
A) Add '# pylint: disable=broad-except' on the line and document the rationale. B) Change to 'except BaseException' to avoid the warning. C) Remove the handler and rely on the default excepthook for logging. D) Refactor to catch (Exception,) as a tuple to satisfy the checker.
Answer: A Rationale: Targeted suppression with a documented justification is the accepted way to handle intentional broad catches at process boundaries. BaseException (B) is broader and worse, removing the handler (C) loses context, and (Exception,) (D) is functionally identical and still triggers W0703.
18 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. 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.
Answer: A Rationale: 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.
19 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.
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.
Answer: B Rationale: 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.
20 A team must remediate a SAST finding on a subprocess call built from user input. Which remediation most directly eliminates the injection class while preserving functionality?
A) Pass shell=False and provide the command as a list of arguments.
Answer: A Rationale: A logger filters records against its effective level before propagation; if the effective level is ERROR, DEBUG records never reach the root handler. Handlers and formatters do not perform severity filtering by default, and NullHandler only suppresses 'no handler' warnings. DEBUG is not globally disabled by handler presence.
23 Which assertion is appropriate for validating an internal invariant whose violation indicates a programming error, and how should it behave under python -O?
A) Use assert; it is stripped under -O, so it must not guard security-critical or user-input validation.
B) Use assert; it remains active under -O and is the preferred runtime input validator.
C) Use a custom exception; assert is always stripped in all CPython modes. D) Use assert with a message; -O converts failures to warnings instead of raising.
Answer: A Rationale: assert is intended for internal invariants and is removed when optimizations disable it (python -O), so it must never enforce security or input validation. It is not converted to warnings, and it is not stripped in normal execution. Custom exceptions are used for recoverable or externally triggered errors, not for invariants expected to hold.
24 A function raises ValueError for malformed input and OSError for I/O failures. A caller wraps it in try/except (ValueError, OSError) as e: log and re-raise. Which refactor best preserves diagnostic fidelity while enabling targeted recovery?
A) Catch Exception broadly and re-raise a new RuntimeError to unify error types. B) Separate except clauses: handle ValueError with user feedback and OSError with retry/backoff, logging each with exc_info=True.
C) Remove the try block and let exceptions propagate to the top-level handler only.
D) Catch BaseException to ensure no failure escapes, then log and continue.
Answer: B Rationale: Distinct exception types signal different recovery strategies, so separate handlers with exc_info=True preserve the traceback and enable targeted logic. Catching Exception or BaseException erases type information and can swallow KeyboardInterrupt/SystemExit. Removing handling entirely forfeits the opportunity for user feedback and retry.
25 A pipeline fails security gates on a medium-severity finding in a dependency. The team argues it is not exploitable in their usage. Which remediation decision best aligns with modern supply-chain risk management?
A) Ignore it because exploitability is the only criterion for remediation. B) Pin the vulnerable version and add a suppression with no expiry. C) Triage with reachability and exploitability context, apply a compensating control or upgrade, and record a time-boxed, documented exception if deferring.
D) Fork the dependency and patch silently without notifying upstream.
Answer: C Rationale: Modern practice combines reachability/exploitability triage with compensating controls and time-boxed, documented exceptions to manage risk transparently. Permanent suppressions or ignoring based solely on claimed non-exploitability bypass governance. Silent forks create maintenance and disclosure burdens without addressing upstream risk.
26 A test asserts that a function raises KeyError for a missing key. The implementation was changed to raise a custom ConfigError(KeyError). Which assertion most robustly encodes the intended contract?
A) with self.assertRaises(KeyError): B) with self.assertRaises(ConfigError): C) with self.assertRaises(Exception): D) with self.assertRaisesRegex(KeyError, 'missing'):
Answer: B Rationale: Asserting the specific ConfigError type captures the refined contract and will fail if the type regresses to a bare KeyError. Asserting KeyError passes for the subclass, masking the intended specificity, while Exception is too broad. assertRaisesRegex on KeyError still under-specifies the type.
27 A codebase logs sensitive tokens at INFO. Which change most effectively prevents leakage while preserving operational visibility?
A) Raise the logger level to WARNING globally. B) Add a logging.Filter that redacts or drops records containing token patterns before they reach handlers.
C) Switch to print() for non-sensitive messages and keep logging for tokens. D) Disable propagation to the root logger.
Answer: B Rationale: A Filter can inspect and sanitize or drop records regardless of level,
C) The handler catches it only if ValidationError is listed first in the except tuple. D) The handler catches it only if AppError is also raised in the same try block.
Answer: A Rationale: Python's except matches subclasses, so catching AppError also catches ValidationError and NotFoundError. Exact-type matching is not required, and ordering within a single except clause is irrelevant here. The presence of other raises in the block does not affect matching.
31 A team runs Bandit on a Python module and it flags subprocess.Popen(cmd, shell=True) in a function where cmd is assembled from a config file. Which remediation most directly eliminates the injection class while preserving the ability to pass arguments?
A) Wrap the call in try/except and log the exception B) Replace shell=True with shell=False and pass an argument list (e.g., shlex.split or explicit list)
C) Add # nosec to suppress the finding D) URL-encode the config values before interpolation
Answer: B Rationale: shell=True invokes the shell, so metacharacters in cmd become injectable; passing an argument list with shell=False (or shlex.split) prevents shell interpretation. try/except, # nosec, and URL-encoding do not remove the shell parsing vulnerability.
32 A developer configures logging.basicConfig(level=logging.INFO) and then calls logging.debug('token=%s', token) in a hot path. Which statement about runtime behavior and security is most accurate?
A) The token is logged because basicConfig overrides the logger's effective level B) The message is not emitted because DEBUG < INFO, so the token is not written to the log
C) The message is emitted but the token is masked by the logging module D) The message is emitted at WARNING level due to level coercion
Answer: B Rationale: The root logger's effective level is INFO, so DEBUG records are filtered before emission; the token is not logged. The logging module does not mask secrets, does not coerce levels, and basicConfig does not force DEBUG emission.
33 A function is expected to raise ValueError for malformed input. Under python -O, which assertion strategy still enforces this contract in production?
A) assert isinstance(x, str), 'x must be str' B) assert x, 'x must be truthy' C) if not isinstance(x, str): raise ValueError('x must be str') D) assert x is not None and isinstance(x, str)
Answer: C Rationale: Under -O, assert statements are stripped, so only an explicit raise survives optimization. Options A, B, and D are all assert-based and vanish, breaking the contract in production.
34 A module catches except Exception as e: and then does raise e inside a nested function. Which statement best characterizes the resulting traceback compared to a bare raise?
A) Both preserve the original traceback identically B) raise e resets the traceback to the re-raise site, while bare raise preserves the original
C) Bare raise is invalid outside an except block D) raise e chains a new exception with __context__ automatically
Answer: B Rationale: In Python 3, raise e re-raises the same exception object but the traceback is replaced with the current frame, losing the original origin; bare raise preserves it. Option A is false; C is false (bare raise is valid inside except); D misstates chaining semantics.
35 A SAST tool reports a taint flow from request.args.get('q') to cursor.execute('SELECT * FROM t WHERE c = ' + q). Which fix is the strongest remediation according to secure coding standards?
A) Escape single quotes in q before concatenation B) Use a parameterized query with a placeholder and pass q as a bound parameter C) Cast q to int before concatenation D) Add a WAF rule blocking SQL keywords
Answer: B Rationale: Parameterized queries separate code from data and eliminate the taint flow regardless of input content. Escaping, casting, and WAF rules are partial mitigations that fail for non-integer or encoded payloads and do not address the root cause.
36 A pytest suite uses @pytest.mark.parametrize to test a sanitizer. Which property best distinguishes a unit test from a property-based test in this context?
39 A CI pipeline runs bandit -r src and pytest --cov=src. A developer adds # nosec to silence a high-severity finding. What is the most appropriate governance response?
A) Accept it because nosec is a standard suppression B) Require a documented justification and a compensating control, and track the suppression in the risk register
C) Delete the bandit step to avoid noise D) Increase the coverage threshold to compensate
Answer: B Rationale: Suppressions must be justified, reviewed, and tracked with compensating controls to maintain risk visibility. Accepting blindly, removing scanning, or substituting coverage thresholds does not address the underlying risk.
40 A team must decide whether to remediate a SAST finding or accept it. Which factor most strongly supports remediation over acceptance?
A) The finding is in a test file B) The vulnerable path is reachable from an untrusted input source and has a known exploit
C) The finding has a low CVSS score D) The code is scheduled for deprecation next year
Answer: B Rationale: Reachability from untrusted input combined with a known exploit indicates real, exploitable risk, favoring remediation. Test-only code, low severity, and near-term deprecation are weaker justifications for acceptance.
41 A CI pipeline runs Bandit with -ll (medium severity threshold) and reports zero issues, yet a taint-tracking scan of the same code finds SQL injection. Which is the most accurate explanation for this discrepancy?
A) Bandit performs only pattern matching on AST nodes and cannot propagate taint across function boundaries or track data flow from sources to sinks.
B) Bandit's -ll flag disables SQL-related plugins, so injection findings are suppressed by configuration rather than by capability.
C) Bandit requires the --sql plugin to be explicitly enabled in the config file; otherwise SQL sinks are skipped entirely.
D) Bandit only scans files modified in the last commit when run in CI, so unchanged vulnerable files are omitted from the report.
Answer: A
Rationale: Bandit is a rule-based AST pattern matcher; it lacks interprocedural data-flow/taint analysis, so it misses injection where the sink and source are in different functions. B and C invent nonexistent flags/plugins, and D misstates Bandit's file-scoping behavior.
42 A module configures logging.basicConfig(level=logging.DEBUG) inside its top-level code. When imported by an application that already called basicConfig with level=WARNING, what is the observed logging behavior?
A) The module's DEBUG messages are emitted because the second basicConfig call overrides the first handler's level.
B) The module raises a RuntimeError at import because basicConfig may only be called once per process.
C) The second basicConfig is a no-op since a root handler already exists, so DEBUG records are filtered by the existing WARNING-level handler.
D) Both configurations merge: the root logger keeps WARNING but the module's logger is automatically set to DEBUG.
Answer: C Rationale: basicConfig only configures the root logger if it has no handlers; subsequent calls are no-ops (unless force=True). Thus the existing WARNING-level handler filters out DEBUG records. A, B, and D incorrectly describe override, error, or merge semantics that basicConfig does not implement.
43 Which assertion usage best preserves the intended invariant check while remaining safe under python -O (optimized mode)?
A) Use assert x is not None, 'x required' because Python raises AssertionError regardless of optimization flags.
B) Replace security-critical assertions with explicit if not cond: raise ValueError(...) because -O strips assert statements from the bytecode.
C) Wrap assertions in a try/except AssertionError block, which prevents -O from removing them.
D) Set PYTHONOPTIMIZE=0 in the environment, which forces assertions to remain active in all subprocesses.
Answer: B Rationale: Under -O, the compiler omits assert statements entirely, so any invariant that must hold in production should be an explicit raise. A and C misstate the semantics of -O; D is unreliable because child processes may not inherit the environment and -O is a compile-time flag.
B) The test errors because assertRaises cannot accept non-AssertionError exceptions.
C) The test fails because the raised TypeError is not an instance of ValueError and propagates out of the context manager.
D) The test passes but logs a warning that the exception type differed from the expected one.
Answer: C Rationale: assertRaises(ValueError) only catches ValueError; a TypeError escapes the context manager and is reported as a test failure/error. A and D wrongly claim success, and B misstates assertRaises' accepted exception types.
47 A developer wraps a database call in except Exception: pass to 'keep the service running.' Which security-relevant consequence is the most serious?
A) It increases CPU usage because exceptions are re-raised internally before being discarded.
B) It masks failures, allowing the service to proceed with corrupted state and hiding indicators of compromise from monitoring.
C) It disables Python's garbage collector for the duration of the try block, causing memory leaks.
D) It converts all exceptions to SystemExit, terminating the process on the next request.
Answer: B Rationale: Blanket swallowing hides errors, corrupts state, and blinds logging/monitoring, which is a security and reliability anti-pattern. A, C, and D misattribute unrelated runtime effects to exception handling.
48 A SAST tool flags subprocess.Popen(cmd, shell=True) where cmd includes user input. Which remediation most directly eliminates the injection class while preserving functionality?
A) Escape single quotes in cmd before passing it to Popen. B) Replace shell=True with shell=False and pass arguments as a list, avoiding the shell interpreter.
C) Wrap the call in try/except and log the command for auditing. D) Set env={'PATH': '/usr/bin'} to restrict which binaries can be invoked.
Answer: B Rationale: Removing the shell and passing an argument list eliminates shell metacharacter interpretation, the root cause of command injection. A's escaping is fragile, C only logs, and D constrains PATH but does not stop argument injection
into the invoked binary.
49 Given a logger configured with a StreamHandler at INFO and the logger's own level set to DEBUG, what happens when logger.debug('x') is called?
A) The record is emitted because the logger's level (DEBUG) permits it and handlers do not filter by level.
B) The record is dropped by the handler's INFO level after passing the logger's DEBUG check.
C) The record is emitted only if logger.propagate is True. D) A ValueError is raised because handler and logger levels must match.
Answer: B Rationale: Logging applies two gates: the logger's effective level, then each handler's level. DEBUG passes the logger but is filtered by the INFO handler. A ignores handler-level filtering, C confuses propagation with level checks, and D invents a constraint.
50 A remediation plan must prioritize fixes. Which ordering best reflects a risk-based approach combining exploitability and impact?
A) Fix in alphabetical order of CWE ID to ensure deterministic, auditable remediation.
B) Fix all low-severity issues first to reduce noise, then tackle high-severity ones. C) Fix internet-facing, remotely exploitable flaws with high impact first, then internal or low-impact issues.
D) Fix issues in the order they appear in the SAST report to preserve developer context.
Answer: C Rationale: Risk-based prioritization weights exploitability (exposure, remote reachability) and impact, so critical internet-facing flaws come first. A, B, and D use arbitrary or counterproductive orderings that ignore risk.