











































































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 Practice Exam 2026
Typology: Exams
1 / 83
This page cannot be seen from the preview
Don't miss anything!












































































Section 1: Python Secure Coding Fundamentals Q1. Which of the following Python functions should never be used with untrusted user input because it can execute arbitrary code? A) len() B) eval() C) str.upper() D) int() Answer: B Rationale: eval() evaluates any string as Python code, allowing arbitrary code execution. Untrusted input can lead to severe security vulnerabilities. The other functions are safe with proper type handling. Q2. When using the subprocess module, which argument setting is most secure to avoid shell injection? A) shell=True B) shell=False (default) C) shell=None D) shell=os.shell Answer: B Rationale: shell=False (default) prevents the shell from interpreting metacharacters, reducing injection risk. shell=True should be avoided with user-supplied input. Q3. What is the primary security benefit of using secrets.token_hex() over random.hex() for generating a password reset token? A) It returns longer strings B) It uses cryptographically strong randomness C) It is faster D) It encodes the output as bytes Answer: B Rationale: The secrets module is designed for cryptographically secure random numbers, suitable for tokens, passwords, and security-sensitive data. random is predictable and not secure. Q4. Which of the following is a safe way to deserialize untrusted data in Python? A) pickle.loads(data)
B) json.loads(data) with schema validation C) yaml.load(data, Loader=yaml.Loader) D) marshal.loads(data) Answer: B Rationale: JSON with schema validation is generally safe if the input is validated. pickle, marshal, and unsafe YAML loaders can execute arbitrary code during deserialization. Q5. To prevent leaking sensitive information in error messages to end users in a production web application, you should: A) Print the full traceback B) Use assert statements for validation C) Log full details server-side and return generic errors D) Disable all error handling Answer: C Rationale: Detailed errors should go to logs for debugging, while users receive generic messages to prevent information disclosure (e.g., stack traces revealing code structure). Q6. Which of the following imports indicates a safe use of eval()? A) eval("import('os').system('rm - rf /')") B) eval("2 + 2") with hardcoded constant C) eval(user_input) D) eval("globals().update({'secret': 123})") Answer: B Rationale: Using eval() on a hardcoded constant string (no user input) is safe, though unnecessary. Any evaluation of user input or dynamic strings enables code injection. Q7. What is the main security risk of using pickle to load data from an untrusted source? A) Pickle is slow B) Pickle can execute arbitrary code during unpickling C) Pickle only works with built-in types D) Pickle is deprecated Answer: B Rationale: Pickle's protocol allows objects to define reduce that can execute arbitrary code. Unpickling untrusted data is equivalent to eval(). Q8. Which built-in function can be safely used to parse a string containing a mathematical expression from user input if you restrict allowed names and operators?
C) os.listdir(user_provided_dir) D) Path(user_provided_dir).exists() Answer: B Rationale: Using shell=True with string concatenation allows the user to insert shell metacharacters (e.g., ; rm - rf /). Argument list form with shell=False is safe. Q12. To protect a SQLite database from SQL injection when using user input as a table name, what is the correct approach? A) Use f-strings to insert the table name B) Use parameterized queries? for the table name C) Validate and whitelist the table name against allowed values D) Escape single quotes manually Answer: C Rationale: SQL parameters cannot be used for identifiers (table/column names). Whitelisting is the only safe method. Direct concatenation or escaping is insufficient. Q13. Which of the following helps prevent XXE (XML External Entity) attacks when parsing XML in Python? A) Use xml.etree.ElementTree without precautions B) Use lxml with resolve_entities=False C) Use minidom.parse() D) Disable DTD processing and external entity resolution Answer: D Rationale: Disabling DTD processing and external entity resolution prevents XXE. Many parsers (including lxml and defusedxml) offer safe configurations. The option D is the general secure practice. Q14. A Python script reads a file whose name is provided by the user. What is the primary risk if no validation is performed? A) Denial of service B) Path traversal attack C) Buffer overflow D) Integer overflow Answer: B Rationale: An attacker can supply ../../etc/passwd to read arbitrary files. Always validate or sanitize paths (e.g., resolve to a safe directory).
Q15. You are using the re module to match user-supplied patterns. What attack is possible if the pattern is complex? A) SQL injection B) ReDoS (Regular Expression Denial of Service) C) Cross-site scripting D) Format string attack Answer: B Rationale: Poorly crafted or nested regexes can cause catastrophic backtracking, consuming CPU and crashing the service. Limit pattern complexity or use timeouts. Q16. Which Python function safely converts a string to an integer without raising an exception for malformed input? A) int(user_input) B) try: int(user_input) except ValueError: default C) ast.literal_eval(user_input) D) float(user_input).is_integer() Answer: B Rationale: Try/except with int() is the standard safe conversion. int() itself raises ValueError; catching it allows a fallback. Q17. To prevent HTTP header injection (CRLF injection) in a Python web app, you should: A) Use f-strings to build headers B) Strip or encode \r and \n characters from user input before including in headers C) Use Base64 encoding for all header values D) Never include user input in headers Answer: B Rationale: CRLF characters can split headers and enable response splitting attacks. Sanitize or reject inputs containing \r or \n. Better yet, avoid raw user input in headers. Q18. Which of the following is NOT a valid mitigation for LDAP injection? A) Escape special LDAP characters B) Use parameterized LDAP queries C) Validate input against a whitelist of allowed values D) Use eval() to parse user input Answer: D Rationale: eval() is dangerous and irrelevant to LDAP. Proper LDAP injection prevention involves escaping or using safe APIs (like ldap3 with proper formatting).
Answer: B Rationale: A unique random salt per password ensures that identical passwords produce different hashes, rendering precomputed rainbow tables ineffective. Q23. The Python secrets module should be used for which of the following? A) Generating random numbers for simulations B) Creating cryptographically secure session IDs C) Shuffling a deck of cards for a game D) Selecting random elements for a statistical sample Answer: B Rationale: The secrets module is specifically for security-sensitive randomness (tokens, passwords, session IDs). For non-security use, random is sufficient. Q24. Which of the following functions from hmac provides a constant-time comparison to avoid timing attacks? A) hmac.new(key, msg, digestmod).digest() B) hmac.compare_digest(a, b) C) hmac.digest(key, msg, digest) D) hmac.HMAC(key, msg, digestmod).hexdigest() Answer: B Rationale: compare_digest() is designed to take the same time regardless of how many bytes match, preventing timing side-channel attacks. Q25. In a Python web framework like Flask, what is the recommended way to store user session data securely? A) Store plaintext user ID in a cookie B) Use Flask’s signed session with a strong secret key C) Store session data in a global variable D) Use pickle to serialize the session Answer: B Rationale: Flask's signed sessions use its secret key to sign the cookie, preventing tampering. Never store sensitive data in plaintext or without integrity protection. Q26. What is the main danger of implementing a “remember me” cookie by storing the user’s password hash directly in the cookie? A) The cookie will expire too quickly B) The cookie can be stolen and used to impersonate the user forever C) The cookie size is too large D) The cookie is automatically encrypted
Answer: B Rationale: A stolen cookie containing a password hash gives the attacker permanent access. Use a separate, revocable token that can be invalidated server-side. Q27. Which of the following is a secure way to generate a random password reset token in Python 3.12+? A) random.choice(string.ascii_letters, k=32) B) os.urandom(32).hex() C) secrets.token_urlsafe(32) D) Both B and C Answer: D Rationale: Both os.urandom() and secrets module functions provide cryptographically strong randomness. secrets.token_urlsafe is more convenient for URLs. Q28. Rate limiting in a login endpoint helps prevent which attack? A) SQL injection B) Cross-site scripting C) Brute-force password guessing D) Session fixation Answer: C Rationale: Limiting login attempts per IP or user prevents automated brute-force attacks. It does not directly prevent injection or XSS. Q29. A Python application uses basic HTTP authentication. Which is a major weakness? A) It requires a session cookie B) Credentials are sent in plaintext (unless over HTTPS) C) It cannot be used with browsers D) It requires JavaScript Answer: B Rationale: Basic authentication sends username and password base64-encoded, which is easily decoded. Always use HTTPS with Basic Auth, but better alternatives exist. Q30. What is the purpose of hashing a password with multiple iterations (e.g., 100, rounds of PBKDF2)? A) To make the hash longer B) To slow down each password attempt, hindering brute-force attacks C) To allow password recovery D) To encrypt the password
B) random.randint(0, n) C) os.urandom(n) D) secrets.choice(seq) Answer: B Rationale: The built-in random module uses Mersenne Twister, which is predictable and insecure for cryptography. Q35. You need to compute a hash of a large file. Which method is most memory-efficient? A) hashlib.sha256(open('file', 'rb').read()).hexdigest() B) hashlib.file_digest(open('file', 'rb'), 'sha256') (Python 3.11+) C) Reading the entire file into memory and updating once D) Using base64 encoding first Answer: B Rationale: hashlib.file_digest() (or manually updating in chunks) reads the file incrementally, avoiding loading the whole file into memory. Q36. Which hashing algorithm is considered cryptographically broken and should never be used for security purposes? A) SHA- 256 B) SHA- 3 C) MD D) BLAKE Answer: C Rationale: MD5 is vulnerable to collision attacks. It should not be used for digital signatures, certificates, or password hashing. Q37. To verify a digital signature created with RSA, you need which key? A) The signer’s private key B) The signer’s public key C) A symmetric key D) No key Answer: B Rationale: Public key cryptography: the public key verifies signatures; the private key signs. Q38. What is the primary purpose of an HMAC (Hash-based Message Authentication Code)? A) Encrypting messages B) Providing both integrity and authenticity of a message using a shared secret
C) Generating random numbers D) Compressing data Answer: B Rationale: HMAC uses a secret key to produce a hash that verifies both that the message was not altered and that it came from a party possessing the key. Q39. Which of the following is true about “authenticated encryption” (e.g., AES-GCM)? A) It only encrypts, no integrity check B) It combines encryption with an integrity/authenticity check in one pass C) It is slower than unauthenticated modes D) It requires two separate keys Answer: B Rationale: Authenticated encryption modes (GCM, CCM, ChaCha20-Poly1305) provide confidentiality, integrity, and authenticity simultaneously. Q40. When using RSA encryption, which padding scheme is considered secure against chosen-ciphertext attacks? A) PKCS#1 v1.5 padding B) OAEP (Optimal Asymmetric Encryption Padding) C) No padding D) Zero padding Answer: B Rationale: OAEP is the standard secure padding for RSA encryption. PKCS#1 v1.5 has known weaknesses and is deprecated. Section 5: Network Security Q41. Which Python library is commonly used to create secure TLS/SSL connections? A) socket B) ssl C) http.client D) asyncio Answer: B Rationale: The ssl module wraps sockets with TLS. Modern usage often involves ssl.create_default_context() for secure defaults.
Q46. To protect a Python socket server from SYN flood attacks, what should you implement? A) Increase socket buffer size B) Use a SYN cookie mechanism (kernel-level) and set somaxconn appropriately C) Use settimeout on all connections D) Disable TCP keepalive Answer: B Rationale: SYN flood mitigation is mostly a kernel/network task, but you can limit the backlog (listen(backlog)) and use SYN cookies (kernel). Application-level timeouts help but not primary. Q47. Which of the following is a secure way to handle client IP addresses in a proxy environment? A) Trust the first IP in X-Forwarded-For unconditionally B) Use request.remote_addr only C) Use the last trusted proxy’s X-Forwarded-For entry after validating a whitelist of proxies D) Always use the client’s claimed IP from X-Real-IP Answer: C Rationale: X-Forwarded-For can be spoofed unless proxies are trusted. Only use the rightmost trusted entry. Q48. Which Python package is recommended for secure FTP (FTPS) or SFTP? A) ftplib B) paramiko for SFTP C) socket D) telnetlib Answer: B Rationale: paramiko implements SSHv2 and SFTP, which is secure. ftplib with TLS can be used but is error-prone. Never use plain FTP. Q49. When using subprocess to run a network utility like ping, what is the safest method? A) os.system("ping " + host) B) subprocess.call("ping " + host, shell=True) C) subprocess.run(["ping", host], shell=False) D) eval("ping " + host) Answer: C Rationale: List form with shell=False avoids shell interpretation. Input validation on host is still recommended.
Q50. What is the main purpose of the SSLSocket method getpeercert()? A) Get the client’s IP address B) Retrieve the peer’s X.509 certificate for validation C) Get the TLS cipher suite D) Get the peer’s port number Answer: B Rationale: getpeercert() returns the certificate of the remote peer, allowing you to verify its fields (subject, issuer, etc.) after the TLS handshake. Section 6: Web Security (OWASP Top 10 Focus) Q51. Which of the following Python web code snippets is vulnerable to SQL injection? A) cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) B) cursor.execute("SELECT * FROM users WHERE name = %s", (name,)) C) cursor.execute(f"SELECT * FROM users WHERE name = '{name}'") D) cursor.execute("SELECT * FROM users WHERE name = :name", {"name": name}) Answer: C Rationale: f-string concatenation directly embeds user input. Parameterized queries (options A, B, D) are safe. Q52. Which HTTP response header can be used to enforce that your web application is only loaded over HTTPS? A) X-XSS-Protection B) Strict-Transport-Security (HSTS) C) Content-Security-Policy D) X-Frame-Options Answer: B Rationale: HSTS instructs the browser to always use HTTPS for future requests to the domain. It prevents SSL stripping. Q53. A Flask application uses session['user_id'] = request.form['user_id'] without validation. What attack is possible? A) SQL injection B) Session fixation C) Cross-site request forgery D) Path traversal
Answer: B Rationale: Frameworks like Flask/Werkzeug provide MultiDict that returns the first value, but you must still handle ambiguity. Proper validation is still required. Q58. A developer uses pickle to serialize the user’s session data. What is the biggest security concern? A) Performance overhead B) Session data might be too large C) An attacker can forge a malicious session that executes code when deserialized D) Pickle cannot store Unicode Answer: C Rationale: If an attacker can control the cookie content (e.g., via signing key leak), pickle can lead to RCE. Never store pickle in cookies; use JSON with signing. Q59. Which of the following is a safe method to set a secure cookie in Flask? A) response.set_cookie('key', 'value', secure=False, httponly=False) B) response.set_cookie('key', 'value', secure=True, httponly=True, samesite='Lax') C) response.set_cookie('key', 'value', domain='.example.com') D) response.set_cookie('key', 'value', max_age=3600, secure=False) Answer: B Rationale: secure=True ensures cookie sent only over HTTPS, httponly=True prevents JavaScript access (XSS mitigation), and samesite='Lax' helps CSRF. Q60. Path traversal (directory traversal) can be prevented by: A) Using os.path.join() and then normalizing the path with os.path.abspath() and verifying it stays inside the base directory B) Replacing ../ with empty string C) Using user input directly in open() D) URL encoding the path Answer: A Rationale: Normalization and prefix checking is the robust solution. Simple replacement can be bypassed (....// etc.). Section 7: File and OS Security Q61. Which of the following makes a Python program vulnerable to a race condition when checking and then using a file? A) with open(file, 'r') as f: data = f.read()
B) Using os.access(file, os.R_OK) and then open(file, 'r') C) pathlib.Path(file).read_text() D) Using tempfile.NamedTemporaryFile Answer: B Rationale: Time-of-check to time-of-use (TOCTOU) vulnerability: after access() returns true, the file could be changed or replaced before open(). Use atomic operations. Q62. Which is the most secure way to create a temporary file in Python? A) open('/tmp/mytemp.txt', 'w') B) tempfile.mktemp() C) tempfile.NamedTemporaryFile(delete=True) D) os.tmpnam() Answer: C Rationale: NamedTemporaryFile creates a secure, unpredictable filename and opens it, avoiding race conditions. mktemp and tmpnam are unsafe and deprecated. Q63. What is the security risk of using os.system() with a string that includes user input? A) The command might be too long B) Command injection via shell metacharacters C) The system may not have enough memory D) It only works on Windows Answer: B Rationale: os.system() invokes the shell, making it vulnerable to command injection if input contains ;, |, $(), etc. Q64. Which Python function is safe for setting file permissions, assuming the file path is trusted? A) os.chmod(path, 0o777) B) os.chmod(path, 0o600) C) os.chmod(path, 0o666) D) os.chmod(path, 0o755) Answer: B Rationale: 0o600 gives read/write only to owner, protecting sensitive files from other users. Avoid world-readable/writable permissions. Q65. To securely delete a file’s contents from disk (overwriting), you should: A) Use os.remove(file) B) Open the file, overwrite with random data multiple times, then os.remove()
A) Cross-site scripting B) Path traversal to overwrite critical files C) SQL injection D) XXE Answer: B Rationale: The filename tries to navigate out of the upload directory to overwrite an SSH key file. Always sanitize and normalize file paths. Q70. Which Python setting can help prevent core dumps from revealing sensitive memory contents after a crash? A) sys.setrecursionlimit(1000) B) resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) C) os.set_inheritable(0, False) D) sys.setswitchinterval(0.01) Answer: B Rationale: Setting RLIMIT_CORE to (0,0) disables core dumps. Core dumps may contain passwords or cryptographic keys. Section 8: Error Handling & Logging Q71. Which of the following logging practices is insecure? A) Logging user IDs for audit trails B) Logging full stack traces to a file accessible only by administrators C) Logging passwords or API keys in debug mode D) Logging request paths without query parameters Answer: C Rationale: Passwords and API keys must never be logged, even in debug mode. They could be exposed in log files or monitoring systems. Q72. To avoid information disclosure in error responses, a Flask application in production should: A) Set app.debug = True B) Set app.config['PROPAGATE_EXCEPTIONS'] = False and use custom error handlers C) Use app.run(debug=True) D) Print exceptions to the console only
Answer: B Rationale: Production must not propagate exceptions to the client. Custom error handlers return generic messages while logging details. Q73. What is the purpose of using a structured logging format (e.g., JSON) for security? A) It looks nicer B) It allows easier automated analysis and SIEM integration C) It encrypts log entries automatically D) It prevents log injection Answer: B Rationale: Structured logs facilitate machine parsing, alerting, and correlation across systems. It does not directly prevent injection but helps detection. Q74. Which of the following is a log injection attack? A) An attacker injects newline characters into a log message to fake log entries B) An attacker deletes log files C) An attacker sends large logs to cause DoS D) An attacker reads log files Answer: A Rationale: Log injection occurs when an attacker introduces CR/LF or control characters to forge log entries. Use replace('\n', '\n') or structured logging. Q75. In Python’s logging module, which configuration would expose sensitive data? A) logging.basicConfig(level=logging.INFO) B) logging.basicConfig(level=logging.DEBUG) when debugging includes user inputs C) logging.getLogger().setLevel(logging.WARNING) D) Rotating log files Answer: B Rationale: Debug level often outputs request details, parameters, and even passwords. Never use DEBUG in production. Q76. Which Python exception handling pattern is unsafe because it hides critical failures? A) try: ... except Exception as e: log.exception(e); raise B) try: ... except: pass C) try: ... except ValueError: handle() D) try: ... finally: cleanup() Answer: B Rationale: Bare except: or except: pass swallows all exceptions,