Cyber Security Quiz: Safe Data Handling In Scripts
10 questions · exam conditions
0:00
Safe Data Handling In ScriptsQuestion 1 of 10

A scheduled reporting script must decrypt customer records. Its author proposes encrypting the database password in a configuration file and embedding the decryption key directly in the script. The script and configuration file are deployed together to every reporting server.

Which alternative provides the strongest practical improvement in handling the password?

Obfuscate the embedded decryption key and rename variables so an attacker cannot easily identify the protected value.
Store the password in an owner-readable plaintext file because file permissions make encryption unnecessary in every threat model.
Split the decryption key between two constants in the script and reconstruct it only when the connection is opened.
Retrieve a narrowly scoped credential at runtime from a secret manager using the server's authenticated workload identity.
← Back to quizzes

Cyber Security Quiz

Cyber Security Quiz: Safe Data Handling In Scripts

Practice Safe Data Handling In Scripts in Cyber Security with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.

What this quiz covers

This quiz focuses on Safe Data Handling In Scripts, giving you a quick way to practice the rules, question types, and explanations that matter most for Cyber Security.

How to use this quiz

Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.

All questions

Question 1

A scheduled reporting script must decrypt customer records. Its author proposes encrypting the database password in a configuration file and embedding the decryption key directly in the script. The script and configuration file are deployed together to every reporting server.

Which alternative provides the strongest practical improvement in handling the password?

  1. Obfuscate the embedded decryption key and rename variables so an attacker cannot easily identify the protected value.
  2. Store the password in an owner-readable plaintext file because file permissions make encryption unnecessary in every threat model.
  3. Split the decryption key between two constants in the script and reconstruct it only when the connection is opened.
  4. Retrieve a narrowly scoped credential at runtime from a secret manager using the server's authenticated workload identity. (correct answer)
Explanation: When you see a question about protecting secrets used by automated processes, focus on where the secret lives and who can access it — not just whether it appears encrypted. The real threat isn't a casual observer; it's anyone who can read the script or its accompanying files. The original proposal buries the decryption key inside the deployed script, which means any attacker who can read one file gets everything they need to reconstruct the password. D solves this at the architectural level: a secret manager (like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault) holds the credential centrally, and the script never stores any long-lived secret locally. Instead, the server proves who it is using a workload identity (e.g., an IAM role or service account), fetches a narrowly scoped credential at runtime, and the credential can be short-lived, audited, and rotated without touching the script. No key exists in the codebase at all. A is security theater — obfuscation and variable renaming provide zero cryptographic protection. Any attacker who can run strings or spend five minutes reading the script will find the key. B is dangerous and flatly wrong; file permissions fail whenever an attacker gains the same OS user, reads a backup, or exploits a misconfiguration — plaintext storage is never equivalent to encryption across all threat models. C splits the key into two constants but keeps both constants in the same script, so an attacker reading the file still recovers the full key with trivial effort. Study tip: On security exams, answers that eliminate the secret from the codebase entirely almost always beat answers that just hide or split it — "no secret here" is stronger than "well-hidden secret here."

Question 2

A Python script sends an API token by building this shell command from configuration values: curl -H "Authorization: Bearer <token>" <url>. It executes the command through a shell and includes the completed command in exception messages. The URL may be supplied by a project administrator.

Which redesign best addresses both command construction risk and accidental token disclosure?

  1. Escape only the token, continue using the shell, and remove the command text from successful execution logs.
  2. Use an HTTP library without a shell, pass the token as a header value, and sanitize exceptions before logging. (correct answer)
  3. Validate only that the URL begins with https://, then retain the shell command and redact its token afterward.
  4. Base64-encode the token before inserting it into the shell command, then decode it at the receiving API.
Explanation: When a question asks you to evaluate a "redesign" that fixes multiple security flaws at once, your job is to identify all the vulnerabilities first, then find the option that closes every one — not just the most obvious. Here, the code has two distinct problems: it constructs a shell command from externally-influenced input (creating command injection risk), and it leaks the API token in exception messages (accidental credential disclosure). A strong fix must address both independently. Option B is the right choice because it eliminates the root cause of each problem separately. Using an HTTP library like requests removes the shell entirely — there's no command string to inject into, regardless of what the URL contains. Passing the token as a header value in the library call keeps it out of any string that gets logged or raised as an exception. Sanitizing exceptions before logging ensures that even if a library surfaces internal details, the token never escapes into logs. This is defense-in-depth: each layer protects independently. Option A fails because escaping only the token still leaves the shell in place. A malicious URL from an administrator could still inject shell metacharacters. Removing the command from successful logs doesn't protect against exception messages, which is exactly where the leak occurs. Option C is similarly incomplete — validating the URL prefix doesn't prevent injection through characters later in the URL, and "redacting afterward" is error-prone and unreliable. Option D is a red herring. Base64 is encoding, not encryption. It provides zero security and doesn't address command injection at all. The study tip here: when a scenario lists two vulnerabilities, automatically eliminate any answer that only patches one of them. Real security design closes attack surfaces at the source, not with after-the-fact sanitization.

Question 3

A privileged script writes a file containing recovery codes to /var/app/export.txt. Before writing, it checks that the path does not exist. It then opens the path, writes the codes, and changes the file mode to owner-only. An unprivileged local user can create entries in /var/app.

Which change best prevents the user from redirecting sensitive output during the interval between the check and the write?

  1. Repeat the existence check immediately before changing the completed file to owner-only permissions.
  2. Write to the existing path, overwrite the file a second time, and then set owner-only permissions before closing.
  3. Generate a checksum of the recovery codes before writing and compare it with the completed destination file.
  4. Open the destination atomically with exclusive creation, reject symbolic links, and request restrictive permissions at creation. (correct answer)
Explanation: When you see a question involving a "check-then-act" sequence on a file path, you're looking at a TOCTOU (Time-of-Check to Time-of-Use) race condition. The window between checking whether a path exists and actually opening it gives an attacker time to swap in a symbolic link, redirecting writes to an arbitrary target — like overwriting /etc/passwd or exfiltrating data. The solution in D eliminates this window entirely by making the check and the open a single atomic operation. Using flags like O_CREAT | O_EXCL on POSIX systems instructs the kernel to create the file only if it doesn't exist, and fail immediately if it does — with no exploitable gap between those two events. Rejecting symbolic links (O_NOFOLLOW) prevents a pre-placed symlink from redirecting the write, and specifying restrictive permissions at creation (e.g., mode 0600) ensures the file is never briefly world-readable. A is wrong because repeating the existence check still doesn't close the TOCTOU window — it just adds another check-then-act pair, each with its own race. B is wrong because overwriting twice only addresses data integrity concerns; the file has already been opened on an attacker-controlled path, so the damage is done before any second write occurs. C is wrong because a checksum detects corruption after the fact — it does nothing to prevent a symlink redirect from happening in the first place. As a study tip: whenever a question describes a sequence of "check, then open, then act," immediately think atomic operations. The fix is almost always to collapse check and open into one uninterruptible system call.

Question 4

A database export utility can receive its password through a command-line option, an environment variable, or standard input. The script runs on a multi-user Linux server under a dedicated service account. Process arguments are visible to other local users, and child processes inherit the script's environment by default.

Which approach best reduces unnecessary exposure of the database password while preserving unattended execution?

  1. Place the password in an environment variable, launch the utility, and unset the variable after the utility exits.
  2. Supply the password through standard input using a direct process invocation, and prevent the script from echoing or logging it. (correct answer)
  3. Pass the password as a command-line option after restricting the script file to the dedicated service account.
  4. Encode the password with Base64, place the encoded value in an environment variable, and decode it inside the utility.
Explanation: When evaluating how to pass secrets to processes, your core framework should be: at what scope is this secret visible, and for how long? Three attack surfaces matter here — the process table (visible to all users via ps), the environment (inherited by child processes and sometimes logged), and stdin (private to the process). Passing the password through standard input via direct process invocation (B) is the strongest approach because stdin is not exposed in the process table and is not automatically inherited or logged by the OS. By invoking the utility directly (rather than through a shell that might record the input), and suppressing echoing, the password exists only in the memory of the receiving process. This minimizes both duration and scope of exposure. A is flawed because environment variables are inherited by all child processes spawned by the utility, and on many systems they're accessible through /proc/<pid>/environ by other users or monitoring tools. Unsetting the variable after the utility exits is too late — the damage window is the entire runtime. C is the most direct trap: restricting the script file doesn't protect the command-line arguments. On a multi-user Linux system, any user can run ps aux and see another process's arguments in plaintext. File permissions control who can read the script, not who can observe the running process. D is security theater. Base64 is encoding, not encryption — it provides zero confidentiality. Anyone who can see the environment variable can trivially decode it. For exam strategy: whenever a question mentions a multi-user system and command-line arguments, immediately flag option C-style answers as traps — process table visibility is a classic distractor.

Question 5

A developer accidentally commits a production API key to a private source repository. The developer deletes the key from the current file and creates a follow-up commit. The repository is available to multiple contractors and is mirrored by the build system.

What is the most important immediate response to make the exposed credential unusable?

  1. Change the repository to private access and rely on the follow-up commit to conceal the previous version.
  2. Purge the key from reachable history first, because removal guarantees that existing copies can no longer authenticate.
  3. Revoke or rotate the key, then investigate exposure and remove it from repository history and build-system copies. (correct answer)
  4. Encrypt the source file in a new commit and retain the same key so deployed scripts continue operating.
Explanation: When a credential is exposed, your first instinct might be to hide it — but hiding is not the same as neutralizing. The core concept being tested here is incident response priority for credential exposure: the distinction between concealing access to a secret versus invalidating that secret entirely. The right move, captured in C, is to immediately revoke or rotate the key. Once a credential is revoked at the service provider level, every copy of it — in contractor laptops, build-system caches, git mirrors, or browser history — becomes worthless. Revoking is instant and universal. After killing the key, you then clean repository history and audit for further exposure, which limits future risk and satisfies compliance obligations. A fails because making a repository private doesn't undo what contractors or the build mirror have already seen or cached. The key still works — it's just slightly harder to find. Obscurity is not security. B contains a dangerous misconception: purging history does not make an existing copy of the key stop authenticating. If a contractor copied the key yesterday, scrubbing the repo tomorrow doesn't revoke their copy. History cleanup matters, but it's a secondary step, not the primary fix. D is a trap for anyone who prioritizes "keeping things working" over security. Encrypting the file while retaining the same compromised key solves nothing — the key is still valid and still exposed in prior history. Study tip: On credential-exposure questions, always ask "does this action stop the key from working?" If the answer is no, it's a secondary step, not the immediate response.

Question 6

A long-running service script retrieves a short-lived signing secret once per hour. It stores the secret in a global immutable string, copies it into several debug objects, and retains previous values in an in-memory cache for troubleshooting. Core dumps are enabled on the host.

Which modification most appropriately reduces the secret's exposure in process memory?

  1. Keep only the current secret for the required operation, avoid diagnostic copies, and restrict core dumps while acknowledging that erasure may be best effort. (correct answer)
  2. Retain all previous secrets but encrypt each cache entry with a key stored in another global variable in the same process.
  3. Convert each secret to Base64 before placing it in debug objects and clear only the original immutable string reference.
  4. Move the cache to a global environment variable so memory-management tools can remove old string objects automatically.
Explanation: When evaluating secrets in process memory, you should think about minimization and exposure surface — how many copies exist, for how long, and what attack vectors (like crash dumps) could expose them. The goal isn't perfect erasure (which managed runtimes often can't guarantee), but reducing the number of places a secret lives and limiting opportunities for exfiltration. Option A is correct because it attacks the problem from multiple angles simultaneously: keeping only the current secret eliminates the historical cache exposure, avoiding diagnostic copies reduces the total number of in-memory references, and restricting core dumps closes the crash-dump exfiltration path. Importantly, it honestly acknowledges that memory erasure in most runtimes is best-effort — strings may be interned or garbage-collected unpredictably — which reflects mature, realistic security thinking rather than false confidence. Option B is a classic security theater trap. Encrypting cached secrets with a key stored in the same process memory provides essentially zero protection — an attacker who can read process memory reads both the ciphertext and the key. You've added complexity without adding security. Option C mistakes encoding for protection. Base64 is not encryption; it's trivially reversible and widely recognized. Clearing only the original reference while leaving Base64 copies in debug objects actually widens exposure rather than reducing it. Option D misunderstands how environment variables work. They are stored in process memory just like other variables and are often more accessible (e.g., via /proc/self/environ on Linux), not less. Moving secrets there makes things worse, not better. Your takeaway: on memory-security questions, always ask "does this reduce the number of copies and attack surfaces, or just shuffle them around?"

Question 7

An API synchronization script currently logs the full request URL, response headers, account email address, bearer token, and a generated request identifier. Operations personnel need enough information to correlate failures across systems, but they do not need customer data or credentials.

Which logging change most appropriately supports troubleshooting while minimizing sensitive-data exposure?

  1. Log only the request identifier, operation name, status code, and a sanitized error category defined by an allowlist. (correct answer)
  2. Log the email address and a truncated bearer token so operators can distinguish requests from different accounts.
  3. Hash every existing log field without a salt so operators can correlate identical values across multiple systems.
  4. Retain the full records in the log but encrypt each individual line with a key stored beside the script.
Explanation: When a question asks you to balance operational troubleshooting with data minimization, think in terms of the principle of least privilege applied to logging: capture only what operators need, not what happens to be available. Sensitive fields like credentials and PII should be excluded entirely, not merely obscured through weak techniques. Option A is the right approach because it logs only the fields operators actually require — a request identifier (for cross-system correlation), an operation name (to identify what failed), a status code (to characterize the failure), and an allowlisted error category (to guide remediation). No credentials, no PII, no extraneous data. This satisfies the operations team's needs while eliminating sensitive-data exposure at the source. Option B fails because retaining the email address introduces PII into logs unnecessarily, and a truncated bearer token is still a partial credential — even a fragment can assist an attacker who intercepts log files, and it provides no legitimate benefit over a request identifier. Option C is deceptively technical but deeply flawed. Hashing without a salt means identical values always produce identical hashes, making them vulnerable to rainbow-table lookups. An attacker could recover email addresses or tokens by precomputing hashes of known values. This is security theater, not real protection. Option D stores the encryption key beside the script, which is essentially equivalent to no encryption at all. Anyone with access to the logs also has access to the key — it provides no meaningful protection and still retains all sensitive data. Study tip: When you see logging questions on security exams, ask yourself: "Does the solution remove sensitive data, or just hide it poorly?" Encryption with co-located keys and unsalted hashes are classic distractors that look secure but aren't.

Question 8

A continuous-integration pipeline injects a deployment token into a script as a protected secret. The platform masks exact occurrences of the token in console output. For diagnostics, the script enables command tracing and prints the token's decoded claims and the first eight characters of the token.

Which assessment of this design is most accurate?

  1. The design is safe because protected-secret masking applies automatically to any substring or transformed representation of the token.
  2. The design is safe if pipeline logs expire quickly, because short retention eliminates disclosure during the retention period.
  3. The design remains risky because tracing and derived output may bypass exact-value masking; unnecessary secret output should be removed. (correct answer)
  4. The design becomes safe if the token is printed only on failed jobs, because successful jobs are the primary source of leakage.
Explanation: When you see a question about secrets management in CI/CD pipelines, focus on what the masking system actually protects against — not what you wish it protected against. Most platforms mask secrets by scanning output for the exact secret string. The moment you transform, split, or trace that secret, you produce output the masker has never seen and cannot recognize. That's precisely why C is correct. Enabling command tracing (e.g., set -x in bash) causes the shell to echo every command before execution — including the raw token in argument lists. Printing decoded claims exposes the token's payload, and printing the first eight characters creates a substring the masker won't match. All of these are derived or partial representations the exact-value masker is blind to. The safest fix is simply not outputting secret material at all. A is wrong because it assumes masking is context-aware and transformation-aware — it isn't. Masking only catches the literal registered secret value. Any encoding, decoding, or truncation defeats it entirely. B is wrong because "logs expire quickly" doesn't eliminate disclosure during that window. An attacker, a misconfigured log forwarder, or an automated scraper can capture secrets the moment they appear. Short retention reduces dwell time, but it is not a security control — it's a consolation. D is wrong because failed jobs are not uniquely dangerous; successful jobs run the same tracing code and produce the same output. The leak exists regardless of job outcome. Study tip: In security questions, watch for answers that describe a partial or administrative mitigation being framed as a complete fix — that pattern almost always signals a distractor.

Question 9

A script calls a payment API using a URL that contains an access token in its query string. When the request fails, the HTTP library raises an exception containing the full URL. The script returns the exception text to the user and sends the same text to centralized logs.

Which change most effectively reduces disclosure without eliminating useful failure information?

  1. Move the token to an authorization header and log a sanitized error code, request identifier, and non-sensitive endpoint name. (correct answer)
  2. Keep the token in the URL but replace its middle characters in the user-facing message, while still forwarding the complete exception text to centralized logs for full diagnostics.
  3. Catch only authentication failures and suppress the URL in those cases, but preserve full exception text including the URL for all network and server errors to aid diagnosis.
  4. Hash the complete exception before storing it in centralized logs, and return the original exception text to any authenticated user who requests it.
Explanation: When evaluating API security questions like this, think along two axes: where does the sensitive data travel, and what information do responders actually need. A token embedded in a URL is particularly dangerous because URLs appear in server logs, browser histories, referrer headers, and exception messages by default — any of which can become an unintended disclosure channel. Answer A addresses the problem at its root by moving the token to an authorization header, which keeps it out of URLs entirely and therefore out of exception text. Then, rather than suppressing error context, it logs a sanitized error code, a request identifier, and the endpoint name — preserving everything a responder needs to diagnose failures without exposing credentials. This is the principle of defense in depth: fix the architecture first, then control what each audience sees. The distractors each patch one layer while leaving another broken. B partially masks the token in user-facing messages, which is a good instinct, but it still forwards the complete exception — including the raw token — to centralized logs, leaving credentials fully exposed to anyone with log access. C creates an inconsistent policy: suppressing the URL only for authentication errors means network and server failures still leak the token, which is exactly when external infrastructure (CDNs, proxies) might also be logging those URLs. D hashing the exception before log storage makes the log entry useless for diagnosis, and returning the original exception text — including the token — to authenticated users expands exposure rather than reducing it. Your takeaway: when a secret appears in a URL, the right fix is architectural (move it to a header), not cosmetic (mask it). Cosmetic patches reduce visibility without reducing risk.

Question 10

A script decrypts a confidential report, writes the plaintext to /tmp/report.txt, uploads it, and deletes the file in a normal cleanup step. The host is shared, /tmp is writable by all users, and the script might be terminated unexpectedly.

Which redesign best addresses both unauthorized file access and plaintext remaining after abnormal termination?

  1. Choose a random filename under /tmp, write the report normally, and register an exit handler that deletes the file.
  2. Create the file atomically with owner-only permissions, unlink it immediately while open, and upload through its open descriptor. (correct answer)
  3. Write the report to a predictable filename, set owner-only permissions afterward, and overwrite it before normal deletion.
  4. Compress the report before placing it in /tmp, restrict the parent script's permissions, and delete it after upload.
Explanation: When evaluating secure temporary file handling, you need to think about two distinct attack windows: the moment the file exists on disk and the moment the process terminates unexpectedly. A robust solution must eliminate both risks simultaneously. Option B closes both windows elegantly. Creating the file with owner-only permissions (O_CREAT with mode 0600) ensures no other user can read it from the start. The critical insight is unlinking the file immediately after opening it — this removes the directory entry so no other process can ever find or open it by name, yet your process retains a valid file descriptor and can still read, write, and upload through it. When the process terminates — whether normally or by a crash — the kernel automatically closes all open descriptors, and since the link count dropped to zero at unlink time, the inode and its data are reclaimed immediately. No cleanup handler needed; the OS handles it. Option A fails on two fronts: a random filename still exists in the filesystem between creation and deletion, remaining visible and potentially readable during that window. An exit handler also won't fire during a SIGKILL or kernel panic, leaving plaintext behind after abnormal termination. Option C is worse than doing nothing — setting permissions after writing means there's a race window where any user can read the file. This is a classic TOCTOU (Time-of-Check to Time-of-Use) vulnerability. Option D provides no meaningful confidentiality. Compression is not encryption; anyone with read access to /tmp can simply decompress it. For exam questions like this, watch for solutions that sound defensive but leave a race window open — true security closes the gap atomically, before any other process gets a chance.