








































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Python Institute Certified Entry-Level Security Specialist with Python Latest Version: 6.0 100 Questions with Correct Answers & Explanations | Graded A+ Study Guide
Typology: Exams
1 / 48
This page cannot be seen from the preview
Don't miss anything!









































Section 1: General Python Security (30 Questions)
1. Which of the following is the most secure way to handle sensitive data (e.g., passwords) in memory in Python? A) Store in a regular string and delete it using del B) Store in a list of characters and overwrite each element with zero C) Use the secrets module and a bytearray that is explicitly overwritten D) Store in a string and rely on garbage collection Correct Answer: C Explanation: Strings in Python are immutable and cannot be overwritten; they remain in memory until garbage collected. bytearray is mutable, and using secrets module provides cryptographically strong randomness. Overwriting with zeros reduces the risk of memory dumping attacks. 2. What is the primary security risk of using Python's pickle module for deserializing untrusted data? A) It is too slow B) It can execute arbitrary code during unpickling C) It does not support complex data types D) It requires a network connection Correct Answer: B Explanation: The pickle module allows classes to define reduce methods that can execute arbitrary code. Unpickling untrusted data leads to remote code execution. Prefer json or yaml.safe_load for untrusted data. 3. Which Python function poses a severe code injection risk when used with user- supplied input? A) print() B) len() C) eval() D) str()
Correct Answer: C Explanation: eval() evaluates any string as Python code. If user input is passed directly, an attacker can execute arbitrary commands (e.g., import('os').system('rm - rf /')). Avoid eval(), exec(), and compile() on untrusted input.
4. How should you generate a cryptographically secure random token for password reset in Python? A) random.randint(0, 1000000) B) os.urandom(32) C) str(random.getrandbits(128)) D) hashlib.md5(str(time.time()).encode()).hexdigest() Correct Answer: B Explanation: os.urandom() uses operating system entropy sources and is suitable for cryptography. The random module is a pseudo-random generator not designed for security. hashlib.md5 with timestamp is predictable and weak. 5. What is the recommended way to prevent shell injection when using subprocess? A) Set shell=True and use string concatenation B) Use shell=True and properly escape arguments C) Set shell=False and pass arguments as a list D) Use os.system() instead Correct Answer: C Explanation: shell=False (default) disables the shell, so argument lists are passed directly to the executable, avoiding shell metacharacter interpretation. Example: subprocess.run(['ls', '-l', user_provided_path]). 6. Which of the following is a safe way to parse YAML input from an untrusted source? A) yaml.load(data) B) yaml.load(data, Loader=yaml.Loader) C) yaml.safe_load(data) D) yaml.full_load(data) Correct Answer: C Explanation: yaml.safe_load() restricts the loader to simple Python types (dict, list, str, int,
10. Which of the following is a vulnerability introduced by using a mutable default argument in a Python function? A) Memory leak B) Information disclosure via shared state across calls C) Buffer overflow D) SQL injection Correct Answer: B Explanation: Mutable default arguments (e.g., def f(x=[])) are created once at function definition and reused. Subsequent calls modify the same object, potentially leaking data between users or causing unintended behavior. 11. In a Python web application, where should error details (tracebacks) be logged? A) Displayed in the HTTP response to help debugging B) Sent to the browser console only C) Written to server logs, never exposed to clients D) Stored in a cookie Correct Answer: C Explanation: Detailed error messages (stack traces, database queries) can reveal system internals to attackers. They must be logged server-side while generic “Internal Server Error” responses are shown to users. 12. Which Python feature can lead to a denial-of-service (ReDoS) attack if user-supplied regular expressions are used? A) re.compile() with re.IGNORECASE B) Catastrophic backtracking in complex regex patterns C) Using raw strings for patterns D) The re.match() function Correct Answer: B Explanation: Poorly crafted regex patterns (e.g., (a+)+b) can cause exponential backtracking on specific inputs, consuming CPU. Never apply user-controlled regexes to untrusted input without limits.
13. What is the security implication of Python’s assert statement? A) It always runs even in optimized mode (-O) B) It can be disabled globally, so it must not be used for security checks C) It prevents SQL injection automatically D) It encrypts the assertion message Correct Answer: B Explanation: When Python is started with - O or - OO, assert statements are removed. Relying on assert for input validation, authentication, or authorization creates a severe vulnerability. 14. Which of the following libraries is the safest for hashing passwords in Python? A) hashlib.md B) hashlib.sha C) bcrypt or argon D) base Correct Answer: C Explanation: bcrypt and argon2 are designed for password hashing: they are slow, use salting, and are resistant to brute-force and GPU attacks. md5 and sha1 are fast and unsuitable. 15. What is the risk of using tempfile.mktemp() in Python? A) It creates files with world-writable permissions B) The generated filename is predictable, leading to race condition attacks C) It only works on Windows D) It does not delete files automatically Correct Answer: B Explanation: tempfile.mktemp() has been deprecated because it returns a predictable filename, allowing an attacker to create a symlink or file before the program uses it (TOCTOU). Use tempfile.mkstemp() or TemporaryFile(). 16. Which of the following is a secure default for Django’s SECURE_HSTS_SECONDS? A) 0 B) 31536000 (one year) after initial deployment
Correct Answer: B Explanation: debug is True if Python was not run with the - O (optimize) flag. It is used for conditional debug code. Security checks should not rely on it.
20. Which of the following is a safe way to read a file whose name comes from user input? A) Directly open the user-supplied filename B) Filter the filename to allow only alphanumerics and a single dot, then chroot to a safe directory C) Prepend a base directory and resolve symlinks, then verify the resolved path stays within the base D) Use os.path.join(base, user_input) without further checks Correct Answer: C Explanation: Path traversal attacks (e.g., ../../../etc/passwd) can be prevented by normalizing the path (os.path.realpath) and checking that it starts with the intended base directory. Direct concatenation is insufficient. 21. Which module in Python is designed to help securely manage passwords and other sensitive data? A) getpass B) hashlib C) cryptography D) All of the above Correct Answer: D Explanation: getpass securely prompts for a password without echoing; hashlib provides hashing algorithms; cryptography is a comprehensive library for encryption and key management. Together they support secure handling. 22. How can you limit the amount of memory a Python process can use to prevent denial of service? A) Use sys.setrecursionlimit() B) Use resource.setrlimit() (Unix) or job objects (Windows) C) Use gc.collect() periodically D) Use sys.setswitchinterval()
Correct Answer: B Explanation: resource.setrlimit(RLIMIT_AS, ...) sets the address space limit. This mitigates memory exhaustion attacks. Python alone cannot enforce hard limits without OS assistance.
23. What is the main security risk of using Python’s xml modules (e.g., xml.etree.ElementTree ) with untrusted XML? A) Cross-site scripting B) XML External Entity (XXE) attacks C) Infinite recursion due to deep nesting D) All of the above Correct Answer: D Explanation: By default, Python’s XML libraries may resolve external entities (XXE), and can be vulnerable to billion laughs (exponential entity expansion) or deep recursion attacks. Use defusedxml or disable DTD/entities. 24. When creating a Django application, which setting should be set to False in production to avoid exposing debug information? A) ALLOWED_HOSTS B) SECRET_KEY C) DEBUG D) DATABASES Correct Answer: C Explanation: When DEBUG = True, Django displays detailed error pages with tracebacks and settings. In production, DEBUG must be False to prevent information leakage. 25. What is the purpose of the PYTHONHASHSEED environment variable? A) It seeds the random number generator for secrets B) It enables or disables hash randomization for dictionary iteration, affecting security against HashDoS attacks C) It stores the secret key for Flask D) It changes the hashing algorithm used by hashlib Correct Answer: B Explanation: Setting PYTHONHASHSEED to a fixed value disables hash randomization,
time, preventing timing attacks that try to deduce secret values by measuring comparison duration. The == operator short-circuits on the first differing byte.
29. In a Python application that uses SQLite, how can you prevent SQL injection? A) Escape quotes using replace("'", "''") B) Use parameterized queries with placeholders (? or :name) C) Validate input length only D) Use string concatenation with repr() Correct Answer: B Explanation: Parameterized queries separate SQL logic from data. Example: cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)). SQLite’s? placeholder prevents injection even from malicious input. 30. What is the danger of using exec() or eval() with user-supplied code even if you try to restrict the global namespace? A) It is always slower than alternative methods B) It cannot access built-ins like import C) Sophisticated attackers can escape restricted execution environments via object introspection (().class.bases[0].subclasses()) D) It raises a SecurityError by default Correct Answer: C Explanation: Python’s restricted execution protections are notoriously weak. Attackers can navigate from any accessible object to the base object class and then to dangerous subclasses (e.g., os.system). Never run untrusted code. **Section 2: Input Validation & Injection (20 Questions)
queries, which eliminate SQL injection. Stored procedures can still be vulnerable if dynamic SQL is built inside them. Escaping is error-prone.
32. What is the best way to validate that a user input is an email address? A) Check that it contains @ and. B) Use a regular expression that follows RFC 5322 exactly C) Use the email_validator library or simply send a confirmation email D) Reject any input longer than 50 characters Correct Answer: C Explanation: Email validation is complex; robust libraries handle edge cases. The only definitive method is to send a confirmation link. Overly complex regex may cause ReDoS, and simple checks are insufficient. 33. When handling file uploads in Python (Flask/Django), which is a security best practice? A) Save the file with the original filename provided by the user B) Generate a new random filename and store the file outside the web root C) Serve the file directly from the uploads folder without any checks D) Allow any file extension including .php or .exe Correct Answer: B Explanation: Attackers can use malicious filenames (directory traversal, double extensions) or upload executable files. Generate a random name, store it outside static web root, and validate file content (magic bytes) not just extension. 34. Which command injection payload will execute arbitrary commands in Python if the code uses os.system("ping " + user_input)? A) 8.8.8.8 & cat /etc/passwd B) 127.0.0.1; ls C) $(whoami) D) All of the above Correct Answer: D Explanation: Shell metacharacters like &, ;, |, $(), ` allow command chaining. When user_input is concatenated without sanitization, any of these can execute additional commands.
38. Which of the following LDAP injection prevention techniques is correct in Python? A) Escape special characters * ( ) \ NUL using backslashes B) Use parameterized LDAP queries via python-ldap with escape_filter_chars C) Concatenate user input directly into the filter string D) Both A and B Correct Answer: D Explanation: Parameterized LDAP queries are best, but if strings must be inserted, use ldap.filter.escape_filter_chars() to escape dangerous characters. Direct concatenation allows injection (e.g., (uid=)(|(uid=))). 39. What is a safe way to allow users to enter HTML markup (e.g., in a comment system) without XSS? A) Strip all tags using a regex B) Use a whitelist-based sanitizer like bleach or nh3 (ammonia) C) Disable JavaScript in the browser via CSP only D) Store raw HTML but escape output with html.escape Correct Answer: B Explanation: Escaping output would display as text. To allow safe formatting, use a library that parses HTML and removes dangerous tags/attributes (e.g., A) 255 characters B) No limit – usernames can be arbitrarily long C) 50 characters, with a whitelist of allowed characters D) 1024 characters Correct Answer: C Explanation: Limiting length (e.g., 20–50 chars) prevents memory exhaustion and also avoids issues with hashing, database indexing, and display. More importantly, whitelisting prevents injection.
42. Which Python function can be used to safely evaluate mathematical expressions from user input? A) eval() B) ast.literal_eval() C) compile() with mode='eval' D) exec() Correct Answer: B Explanation: ast.literal_eval() evaluates only literals (strings, numbers, tuples, lists, dicts, booleans, None). It does not call functions or operators beyond basic literals, so it is safe for config files, but still not for arithmetic expressions. For maths, a proper parser (e.g., asteval) is needed. 43. In a Python CLI tool, how can you safely pass a user-supplied filename to grep via subprocess? A) subprocess.run(f"grep pattern {filename}", shell=True) B) subprocess.run(["grep", "pattern", filename], shell=False) C) os.system(f"grep pattern '{filename}'") D) subprocess.run(f"grep pattern {shlex.quote(filename)}", shell=True) Correct Answer: B Explanation: Using list form without shell=True is safest. If you must use a shell, shlex.quote() escapes the argument. Option B correctly avoids shell injection entirely. 44. What type of attack is prevented by using html.escape() on output? A) SQL injection
Correct Answer: B Explanation: If the child process produces more output than the OS pipe buffer (typically 64KB) and the parent never reads it, both processes can deadlock. Use subprocess.run() with capture_output=True (which reads fully) or handle pipes asynchronously.
48. Which of the following characters should be blacklisted (or escaped) when building a shell command with shell=True? A) ;, &, |, $, ``` ``,(,),<,>,\n,\rB) Only'and"` C) Only spaces D) Only newlines Correct Answer: A Explanation: All shell metacharacters have special meaning. Blacklisting is fragile because it’s easy to miss one. The secure approach is to avoid shell=True entirely. If unavoidable, use shlex.quote(). 49. What is a “canary word” in the context of input validation? A) A secret value included in logs to detect injection attempts B) A unique string placed in expected input to detect when a developer forgets to validate C) A function that catches exceptions D) A type of cryptographic hash Correct Answer: B Explanation: When writing unit tests, a canary word (e.g., "CANARY") is inserted into untrusted input. If it appears in output without proper encoding, the test fails, indicating missing validation/escaping. 50. Which of the following is a safe way to create a dynamic SQL query with a variable table name? A) Use string formatting: f"SELECT * FROM {table_name}" B) Validate the table name against a whitelist of allowed values C) Use parameterized queries – but table names cannot be parameterized, so sanitize via whitelist D) Both B and C (C is clarification: table names cannot be placeholders, so whitelist is the solution)
Correct Answer: D Explanation: Parameter placeholders only work for column values, not identifiers (table/column names). The secure pattern is to verify that the table name is one of a predefined set (whitelist). Section 3: Authentication & Session Management (20 Questions)
51. Which of the following password storage methods is least secure? A) scrypt B) bcrypt C) MD5 without salt D) Argon Correct Answer: C Explanation: MD5 is a fast hash, vulnerable to rainbow tables and brute force. Salting alone is not enough; a slow, memory-hard algorithm (bcrypt, Argon2, scrypt) is required. 52. In Flask, what configuration is needed to ensure session cookies are signed (not encrypted) to prevent tampering? A) app.config['SECRET_KEY'] = a_random_secret B) app.config['SESSION_COOKIE_SECURE'] = True C) app.config['SESSION_COOKIE_HTTPONLY'] = True D) None, Flask signs by default using itsdangerous with the secret key Correct Answer: A Explanation: Flask signs session cookies with a secret key (SECRET_KEY) to prevent client-side tampering. Without a strong secret, an attacker could forge session data. Encryption is not used by default (sessions are client-side, signed). 53. Which of the following is a secure way to reset a forgotten password? A) Send the current password via email B) Generate a time-limited, single-use token sent to the user’s registered email, then allow setting a new password C) Answer a secret question (e.g., mother’s maiden name) D) Show the old password in plaintext after clicking “Forgot password”
tokens. SECURE_SSL_REDIRECT redirects HTTP → HTTPS. All are recommended for HTTPS sites.
57. What is a session fixation attack? A) Stealing the session cookie via network sniffing B) Forcing a user to use a known session ID before they authenticate C) Fixing a broken session handling function D) Encrypting the session cookie twice Correct Answer: B Explanation: In session fixation, an attacker provides a victim with a specific session ID (e.g., via a link). Once the victim logs in, the attacker uses the same ID to hijack the session. Mitigation: regenerate session ID after authentication. 58. Which Python library should you use to implement multi-factor authentication (TOTP)? A) pyotp B) totp (built-in) C) hashlib D) jwt Correct Answer: A Explanation: pyotp is a popular library for TOTP and HOTP (RFC 6238). It integrates with Google Authenticator. Python does not have a built-in TOTP module. 59. Why should you never roll your own cryptographic session implementation? A) It is too slow B) It is likely to have subtle vulnerabilities (e.g., padding oracle, side-channel leaks, improper IV handling) C) It is not allowed by the Python license D) It cannot be tested Correct Answer: B Explanation: Cryptography is extremely hard to get right. Custom session tokens may be predictable, use weak randomness, or expose timing attacks. Use well-vetted frameworks (Flask-Login, Django’s session).
60. How can you prevent brute-force login attacks in a Python web app? A) Implement account lockout after a few failed attempts B) Use CAPTCHA after several failures C) Add progressive delays (e.g., 1s, 5s, 30s) D) All of the above Correct Answer: D Explanation: Multiple layers are effective: lockout protects against many attempts, CAPTCHA stops automated scripts, delays slow down attacks. Remember to log failures and alert on suspicious patterns. 61. In OAuth 2.0, which grant type should a Python CLI application use? A) Authorization Code with PKCE B) Implicit grant (deprecated) C) Client credentials (only for machine-to-machine) D) Resource owner password (legacy) Correct Answer: A Explanation: For public clients (CLI, single-page apps), Authorization Code with PKCE (Proof Key for Code Exchange) is the modern, secure standard. It prevents code interception attacks. 62. Which of the following is a property of a secure session ID? A) It is sequential and easy to guess B) It is generated using a cryptographic random number generator and has sufficient entropy C) It contains the user’s password D) It remains unchanged after login Correct Answer: B Explanation: Secure session IDs must be unpredictable (high entropy), not contain user data, and preferably regenerated upon privilege elevation. Use secrets.token_urlsafe(). 63. What is the purpose of the SameSite cookie attribute? A) Ensure the cookie is sent only to the same site (preventing CSRF)