Learning outcomes
- Model a defensive problem through input contracts, explicit rules, traceable outputs and regression tests.
- Use Python, CSV, JSON, SQLite and APIs without confusing data processing with authorisation to act.
- Control secrets, paths, permissions, SQL queries and subprocesses to reduce the attack surface introduced by automation.
- Interpret logs, duplicates, time windows and coverage gaps without attributing authorship or overstating certainty.
- Verify integrity against a SHA-256 manifest and document chain-of-custody limitations.
- Explain the risks of dependencies, CI/CD, SBOMs and attestations without reducing security to a tool.
- Resolve and reproduce the fictional case “The alert that arrived twice” with an offline Python analyser.
Programming to reduce uncertainty, not multiply alerts
Programming for cybersecurity is not the same as running commands quickly. Defensive automation must transform identifiable inputs into verifiable outputs and proportionate human decisions. Between those two ends lie data selection, validation, correlation rules, exception handling, documentation and access controls. If a task runs ten times a minute, it can also produce an incorrect conclusion ten times a minute. The first requirement is not speed, but formulating a specific question that the programme can answer within known limits.
A simple example shows the difference: “detect intrusions” is an imprecise expectation; “flag connections from disabled accounts occurring after the revocation date, using trusted events from the identity provider” is a testable specification. The first promises a universal capability that cannot be demonstrated. The second requires us to define what “disabled” means, how dates are compared, which sources are considered authorised and what to do when events are missing. That delimitation makes testing possible and, above all, prevents an alert from being presented as conclusive proof of authorship.
Automation should preserve human involvement wherever a decision is made to block a user, report conduct, affect a production system or interpret a legal obligation. A programme can classify a discrepancy and recommend further analysis; it cannot, by itself, infer that the person appearing in a record committed an offence or that the data received are authentic. In a legal and technology advice portal, understanding the boundary between technical operation and evidential inference is as important as writing the correct function.
Related sources: [15] NIST · [1] Python
From the problem to the data flow: inputs, transformations and outputs
Before choosing Python, SQL or a SOAR platform, it is worth mapping a workflow: event source, expected format, mandatory fields, schema version, business rules, output, recipient and audit method. Every boundary introduces risks. An API may return data out of order, a CSV file may change its delimiters, or a database may represent dates without a time zone. If the design omits these contingencies, the code may finish without errors and produce an apparently correct but incomplete report.
It is useful to work with an explicit data contract. For example, each event includes a non-empty identifier, a UTC date and time in ISO 8601 format, a source system, an action type and a correlation identifier. The input has a maximum size, an allowed origin and a policy for duplicates. The design specifies how rejected rows are recorded and whether the task stops when the error rate exceeds a threshold. Unlike a spreadsheet edited manually, these rules are visible and can be reviewed.
The output also needs a contract: alerts include the rule applied, its supporting evidence, a confidence category, the code version, the execution time and the limitations. A conclusion that is not linked to its input data will be difficult to review later. It is advisable to maintain a test dataset with an expected result; when the script is changed, that dataset helps detect regressions that might otherwise go unnoticed during visual inspection.
Related sources: [15] NIST · [12] OWASP
Python as a defensive automation language
Python is useful for working with heterogeneous formats, building reproducible utilities and processing files without necessarily depending on external services. Its standard library includes csv, json, datetime, pathlib, hashlib, sqlite3, logging, argparse and unittest. The value of learning these modules lies in understanding contracts and errors, not in memorising a list of packages. For a simple correlation task, an application of a few dozen reviewable lines may be sufficient; adding a large set of dependencies does not always improve the result.
A reading function should deal only with obtaining data and validating the schema; another function should apply a rule; a third should export a result. This separation makes it possible to test the logic without touching production resources. For example, a function that determines whether a timestamp precedes a revocation can receive two timezone-aware datetime objects. It does not need to connect to an identity system to verify a temporal criterion. Injecting external dependencies as interfaces or parameters makes it easier to simulate controlled failures.
Reproducibility requires identifying the Python version, dependencies, non-secret configuration and rules applied. A script run manually may produce different figures days later because a source was updated, not because the algorithm changed. For that reason, a technical report should link the execution to the retained data, not merely to the code file. As the tool evolves, its change history and regression tests should evolve with it; automating without governing versions produces results that are difficult to compare.
Related sources: [1] Python · [15] NIST
Types, structures and data models
A text string, an IP address, a date and a user identifier may look similar on screen, but they are not interchangeable. Treating a date as text can produce incorrect sorting when formats differ. Comparing an IP address as if it were a number, without taking IPv4, IPv6 and private networks into account, also causes errors. The data model must reflect the questions it is intended to answer: to assess a sequence of accesses, the exact time matters, whereas an inventory may need a calendar date rather than an instant.
In Python, dictionaries and lists make it possible to build flexible records, but flexibility requires validation. dataclasses and type annotations help document the expected fields; the annotations do not, by themselves, check values at runtime. For more complex systems, schema validators can be used, always with dependencies under control. It is important to distinguish missing values from explicitly empty values, zero from “not measured”, and a negative label from a fact ruled out by evidence.
Identifiers also need semantics. Two systems may both call different subjects usuario_17, while the same user may have personal, service and temporary accounts. Correlation must use defined keys and, where no reliable relationship exists, record that uncertainty. Linking events solely because they share an IP address or a similar name can attribute other people’s activities to an individual; the logical precision of the programme cannot compensate for an incorrect identity model.
Related sources: [1] Python · [9] Python
Input validation and trust boundaries
All input from users, files, external systems or logs should be treated as potentially incomplete, inconsistent or manipulated. Validation does not mean indiscriminately removing unusual characters; it means checking length, type, range, format, mandatory status and relationships between fields. A correlation identifier may allow letters, numbers and hyphens up to a specified length; a date must be interpretable and have a known time zone; a result may belong only to a documented set of values.
Robust defence validates at the system boundary and checks the information again when it is used in different contexts. A string that is valid as a file name is not necessarily safe as a shell command or SQL query. Each destination has its own rules. The principle should be “data as data”: avoid turning untrusted text into instructions, unrestricted paths, concatenated queries or evaluable expressions. Allow-lists are usually more defensible than trying to anticipate every prohibited sequence.
It must be documented what happens when a row fails validation. Silently discarding it may conceal precisely the anomaly that matters; accepting everything in order to “lose no information” may make the result unusable. One strategy is to separate valid from rejected records, retain a precise reason and count the volume of failures, while avoiding the logging of complete sensitive fields. If the source produces an abnormal proportion of errors, the tool should flag degraded data quality before presenting statistics as though they covered the entire observed population.
Related sources: [12] OWASP · [13] OWASP
CSV, JSON and normalisation without loss of meaning
CSV looks simple because it can be opened in any editor, but it does not provide a universal type schema or guarantee that delimiters, encodings and quotation marks will be interpreted in the same way by every tool. A field may contain line breaks or commas within quotation marks; a spreadsheet may transform long identifiers, dates or values that look like formulas. Reading with csv.DictReader should be accompanied by checks of headers, size limits and an explicit encoding. When sharing data with spreadsheets, the risk of formula interpretation must also be assessed.
JSON preserves the distinction between numbers, strings, lists, objects and null values more effectively, but it does not guarantee authenticity or that concepts have the same meaning. Two producers may use status=0 with opposite meanings. Normalisation should record equivalences and retain the raw data where necessary to reconstruct the source. Converting every result into OK or ERROR often erases useful signals: access denied, authentication failure, server error, timeout and unobserved event require different treatment.
For example, one system reports an HTTP 403 response while another records a successful network connection. There is no necessary contradiction. The network may have worked while application authorisation denied the operation. If a normaliser converts both events into a binary “success” variable, it may create a false anomaly or remove a legitimate one. The quality of automation depends as much on the semantics of the data as on the syntactic correctness of the code.
Related sources: [2] Python · [3] Python
Files, directories, permissions and safe operations
Working with files requires consideration of reading, writing, permissions, collisions, symbolic links and error recovery. pathlib makes it possible to express paths clearly and resolve components such as .., but a resolved path is not, by itself, an authorisation. If a user chooses the name of an output file, its destination must be restricted to an allowed directory; concurrent file-system changes and links pointing outside the expected area must also be considered. In critical operations, name validation should be combined with safe opening mechanisms, least privilege and operating-system controls.
To avoid partial results, a temporary file can first be written on the same volume and then atomically replace the destination, where the file system supports this. The solution must account for exceptions: insufficient space, interruptions, permissions or unavailable disks. Even so, “atomic” does not mean a complete transaction across multiple files or services. If a CSV, an index and a manifest are exported at the same time, it is advisable to define how to identify a complete set and what to do with interrupted batches.
Input paths must not enable traversal through arbitrary folders or include secrets in reports. Cleanup tasks deserve particular caution: automation that deletes “old” files may affect material retained under legal obligations, investigations or recovery requirements. Deletion should follow an approved policy and be verified before execution. Moving items to quarantine for review is often more prudent than performing an irreversible bulk deletion.
Related sources: [4] Python · [15] NIST
Secrets, credentials and environment separation
An API token, service password or signing key should not be written into source code, public examples or the laboratory CSV files. Environment variables and secret managers can help, but they do not, by themselves, eliminate risk: a process may expose its configuration in logs, memory dumps or diagnostic tools. It is necessary to consider who can read the secret, how long it lasts, what permissions it grants and how it is revoked. If the task is merely to consult vulnerabilities, an administrative token is disproportionate.
Python’s secrets library is intended to generate unpredictable values used in authentication; random is not suitable for that cryptographic purpose. Nor should a SHA-256 hash be confused with a secure password-storage mechanism: passwords require specific derivation functions and appropriate parameters. A file hash is used to compare bytes with a reference, not to encrypt information or establish human identity.
Development, testing and production environments must be separated operationally. A script that produces an educational report does not need to connect to real systems, and one that reads production logs does not need to be able to modify users or delete evidence. Key rotation, least-privilege permissions and emergency mechanisms must be documented. A secure automation may deliberately have no write capability: least privilege is an architectural decision, not a patch added at the end.
Related sources: [5] Python · [15] NIST
Subprocesses, the shell and execution of external tools
System utilities are often automated through subprocess. The most defensible approach is to invoke known executables with an explicit list of arguments, control exit codes, set a timeout and limit the data transmitted. Using shell=True introduces a dangerous boundary when a parameter comes from an untrusted source, because the interpreter may treat special characters as instructions. The official Python documentation explains this difference and the particularities of Windows.
Not every interpolation is malicious and not every shell execution is prohibited, but its use requires an identifiable reason and proportionate safeguards. For example, automating an approved diagnostic query is different from allowing a CSV column to decide which command to run. Environment variables, the working directory, standard output, error output and the possible inclusion of secrets in failure messages must also be considered. A correct result with credentials exposed in the log is not a secure execution.
It is advisable to distrust solutions that invoke processes without limits for every incoming event. High volume can exhaust memory, storage or file descriptors. Queues, concurrency limits, cancellation and a mechanism to stop the task reduce operational harm. In sensitive environments, running tools inside containers or restricted accounts may add isolation, provided that the container is not treated as a substitute for authorisation policies and host maintenance.
Related sources: [6] Python · [12] OWASP
SQL and reproducible investigative queries
SQL is useful for relating inventories, events, identities and configuration changes. The fundamental difference is between using a parameterised query and concatenating values into an SQL string. Python’s sqlite3 interface supports placeholders that keep data separate from query structure; this practice reduces the risk of injection when a value comes from an external input. Table or column identifiers do not always support parameterisation, so they must be selected from explicitly permitted lists.
A security query must preserve its meaning. COUNT(*) on an incomplete table does not necessarily count all real operations. A join between events from two sources may generate duplicate records if the key is not unique. The time window, time zones, ingestion delays and aggregation rules must appear in the report. The accuracy of a figure depends on the observed dataset; “we found no matches” is not equivalent to “there were no events”.
In real systems, it is important to limit the permissions of query accounts, avoid locks on production databases and control the volume of results. An investigative tool can work on a replica or an authorised extract. Index creation and extensive queries must be assessed for their cost, since a poorly designed audit can degrade the service it is intended to protect. For traceable processes, it is advisable to retain both the query definition and the version and period of the data examined.
Related sources: [7] Python · [13] OWASP
APIs: contracts, authentication and authorisation
An API allows two systems to exchange information through documented interfaces; its availability does not imply that every operation is authorised. HTTP responses have codes and bodies with distinct meanings. A 200 may indicate successful delivery of a representation; it does not prove that the information is accurate or that an operational decision is appropriate. A 401 and a 403 have different implications, although the details depend on the implementation. Automation must interpret the service’s particular contract and not infer meaning solely from the number.
Modern APIs may implement OAuth, temporary tokens, application keys or mutual authentication. Each mechanism requires the management of scope, expiry, secrets and revocation. A common mistake is to assume that knowing an object identifier allows it to be queried: OWASP calls the failure to authorise access to specific resources Broken Object Level Authorization. From the consumer’s side, possessing a technical credential does not authorise operations beyond the permission granted or remove obligations relating to data protection.
A robust client should include timeouts, secure connections, certificate validation, pagination, handling of unexpected formats and explicit error handling. If an API returns a URL, it should not automatically query any address supplied by third parties: the SSRF threat shows that a service may end up requesting internal resources by following externally controlled parameters. An allow-list of destinations and infrastructure controls reduce that risk, but redirects and name resolution must also be considered.
Related sources: [11] OWASP · [12] OWASP
Pagination, retries, quotas and partial failures
Obtaining the first page of an API does not mean retrieving the entire dataset. Some interfaces return a continuation cursor; others use offsets and limits. The client must retain the extraction state and detect duplicate or empty pages, without assuming that numbering remains stable while the source is being updated. If a query returns ten thousand records across batches, an error on page nine may leave a convincing report that is nevertheless materially incomplete.
Automatic retries are justified for transient failures, but they must be distinguished from permanent errors involving authorisation, validation or resource availability. It is reasonable to apply an increasing delay with random jitter, a bounded number of attempts and respect for Retry-After when the server indicates it. Retrying a 403 indefinitely does not correct permissions; resending a write operation without control may create duplicates or execute an action with material consequences twice.
It must be defined what constitutes a complete, partial or failed execution and how this is communicated. A process that stops after seven pages may retain those data for diagnosis, but must not label them as the complete dataset. Fault tolerance means making degradation explicit and facilitating recovery, not concealing errors. This criterion is essential for intelligence sources, vulnerability inventories, institutional records and services that update information continuously.
Related sources: [11] OWASP · [15] NIST
Security logs and useful observability
A useful log entry describes what happened according to a specific source, when it was observed, which technical correlation it allows and what the record’s limitations are. Full request bodies, tokens, passwords or personal data that are not necessary should not be collected automatically. OWASP recommends prioritising structured formats and excluding or protecting sensitive information. It also warns about log injection: including line breaks or delimiters without handling them may allow an external value to simulate new entries.
Observability is not limited to accumulating files. It includes source availability, processing times, rejection rates, ingestion delays, event volume and the behaviour of rules. An alert may disappear because suspicious activity has stopped or because the collector has stopped sending data. Without monitoring the health of the automation itself, these two situations may appear equivalent. Indicators showing how many records were processed, how many were discarded and the date of the last valid event are valuable.
Retention of and access to logs require technical and legal criteria. Records may reveal schedules, habits, approximate locations or decisions made by users and employees. They must be limited to legitimate purposes, protected and deleted in accordance with the applicable policy; a security need does not authorise processing indefinitely. Log-management standards provide good-practice guidance, but their adoption does not replace an analysis of legislation, contract, proportionality and rights in each jurisdiction.
Related sources: [10] OWASP · [16] NIST
Time correlation: from an isolated event to a hypothesis
Correlation links technical facts that share a key, a pattern or a time window. For example, a failed request followed by a successful authentication from the same origin may be relevant, but the match does not prove identity or causation. Keys must be chosen deliberately: session ID, request ID, account, device or resource. Each answers a different question and carries different risks of collision, rotation or spoofing.
Temporal sequencing depends on clocks. If one service records UTC and another uses local time without a time zone, sorting strings may produce a false account. Even with synchronised clocks, there are transmission delays, queues and records generated after the operation. Automation should retain the original timestamps, state the conversions and indicate when clock precision or source quality is insufficient. A five-minute window is an analytical decision, not a natural property of events.
Correlation also requires the handling of absence and duplicates. If a system fails and reports no events, a naïve rule may conclude that there were no accesses. If a collector resends the same batch, it may count the same event twice and trigger a false escalation. Event identifiers, provenance and duplicate handling should be recorded, and “not observed” should be distinguished from “discarded”. The practical case in this chapter uses precisely these limitations to avoid categorical conclusions without sufficient evidence.
Related sources: [9] Python · [10] OWASP · [23] IETF
Indicators, vulnerabilities and responsible enrichment
A domain, an IP address or a cryptographic hash may be used as an indicator to guide analysis, but its isolated presence does not demonstrate compromise. IP addresses may be shared, reassigned or belong to third-party infrastructure. Hashes identify matching bytes; a minimal change produces a different fingerprint even when the file is functionally similar. Indicators need context, a period of validity, an origin, a confidence level and a defined relationship to an incident.
Automated enrichment queries authorised sources, adds metadata and retains provenance. When investigating a vulnerability, the product, version, configuration, exposure and available mitigations must be identified; a textual match between a package name and a CVE may produce false positives. Component-analysis tools depend on the quality of the inventory and public data. Finding a high score is not enough to conclude that a vulnerability is exploitable in a particular deployment.
Sending indicators to third-party services may also disclose information. A URL for an internal document may contain a token, identifiers or confidential parameters; uploading it to a public scanner may create an additional exposure. Query policies should state what may be transmitted, on what basis and under which safeguards. Enrichment is a data-processing and risk-management activity, not a neutral operation merely because it is performed through an API.
Related sources: [22] OWASP · [19] OWASP
Hashes, manifests and the difference between integrity and authenticity
SHA-256 calculates a reproducible fingerprint from a file’s bytes. If a trusted reference copy is retained, comparison identifies changes to the content, although it does not explain who made them or why. Two files may display the same text and still differ in line breaks, encoding or metadata; their hashes reflect the bytes, not a legal interpretation of the document. The procedure should state how the file was obtained and what was retained, especially when the purpose is to preserve evidence.
A manifest containing file names and hashes makes it possible to verify a set of attachments. However, if one person can modify both the files and the manifest, the check proves only consistency between those altered elements. Strengthening authenticity and chain of custody requires independent controls, documented custody, signatures or seals as appropriate, acquisition records and restricted access. The hash is one technical element; it does not replace evidential procedures.
The Riesgo Tecnológico laboratories use an offline verifier so that readers can check matches and detect a deliberate alteration. The exercise teaches integrity relative to a manifest; it does not certify real files. The laboratory code avoids external communications and modifies only outputs within a controlled working folder. This approach makes learning reproducible without testing other people’s infrastructure or requiring administrative privileges.
Related sources: [8] Python · [16] NIST
Idempotent, reversible and observable automation
An idempotent task produces the same final effect when run more than once with the same input and relevant state. This property is fundamental to retries and recovery. Repeatedly creating the same ticket or blocking an account in several systems without checking its previous state may complicate an investigation. For operations that change resources, it is advisable to use idempotency keys, a record of decisions, prior validation and rollback mechanisms where they can be applied safely.
Reversibility has limits. An email that has been sent cannot be universally withdrawn, and deleted data may not be recoverable. For this reason, it is advisable to separate the observation phase from the execution of actions, especially in maintenance scripts. Dry-run mode can show what would be changed; it must not be presented as a guarantee that subsequent execution will take place in an identical state. Before a sensitive operation, requirements, permissions, dependencies and stop conditions should be checked.
Responsible automation needs an owner, a deactivation procedure and an explanation of its effects. Without these, the programme may continue running after a rule changes, a contract ends or a system is retired. Lifecycle management includes onboarding, review, changes, operation, incidents and decommissioning. Retaining the ability for human intervention is particularly important where rights, operational continuity or the preservation of evidence may be affected.
Related sources: [15] NIST · [14] OWASP
Automated testing, edge cases and independent review
A unit test checks a function with controlled inputs. An integration test evaluates interactions with other components; an end-to-end test verifies the complete workflow in an appropriate environment. None of these categories replaces the others. For a correlation rule, it is advisable to test valid events, out-of-range dates, duplicate timestamps, incomplete records and non-matching keys. Edge cases reveal problems that a demonstration with three well-formed rows usually conceals.
Expected results should be defined before changing the algorithm. If the rule flags a match within a five-minute window, it must be decided explicitly what happens exactly at the five-minute boundary, whether the limit is inclusive and what happens if sources arrive in reverse order. A test that checks only that the script did not raise an exception may pass even when the result is conceptually wrong. Tests must assess meaning, not merely execution.
It is also valuable to run tests with simulated failures: an API returning 429, a file that disappears, an impossible date record and a disk with insufficient space. The tool should fail in an explainable and safe way; it should not conceal errors or produce partial results labelled as complete. Review by another person makes it possible to challenge assumptions about the model, privacy, compliance, permissions and excessive dependence on a single data source.
Related sources: [15] NIST · [1] Python
Dependencies, SBOMs and artefact provenance
Scripts often integrate libraries from an open ecosystem. Each dependency adds functionality and also a relationship of trust. Responsible management includes identifying the versions actually used, reviewing maintenance, updating with tests and understanding transitive dependencies. Automated composition analysis can find known vulnerabilities, but does not, by itself, demonstrate that all the software is secure or that a finding is exploitable in the specific environment.
A software bill of materials (SBOM) describes components and relationships. Formats such as CycloneDX and SPDX allow inventories to be exchanged in a formal structure; their usefulness depends on the accuracy and currency of the data. An SBOM does not replace a security process and is not equivalent to a licence to use. Artefact provenance adds another dimension: knowing which source, process and environment produced a given result. SLSA provides levels and mechanisms to strengthen those assurances progressively.
NIST SSDF guidance places security within the development lifecycle, not only at the final deployment stage. In small projects, it is more effective to start with sustainable controls — review, testing, updates, a protected repository and incident records — than to copy a complex pipeline that cannot be maintained. The choice of tools should be proportionate to risks and resources. Unnecessary complexity can increase the attack surface that automation was intended to reduce.
Related sources: [18] SLSA · [19] OWASP · [20] SPDX · [22] OWASP
CI/CD: automating without granting excessive privileges
Continuous integration runs tests and checks when code changes; continuous deployment may publish artefacts to authorised environments. The danger arises when workflows receive broad permissions, run code from untrusted contributions while secrets are available, or download external actions without controlling their versions. A sound practice is to pin automation dependencies to verified references, restrict token permissions and clearly separate validation jobs from publication operations.
Long-lived credentials should be avoided where suitable temporary trust mechanisms exist, such as identity federation between CI services and the provider to which deployment takes place. Artefact attestations can add information about how a package was produced, but do not, by themselves, turn insecure code into secure code. Each chain of trust must be verified and documented; an “build successful” label does not guarantee that all relevant tests were run.
Rules that change applications or infrastructure should require explicit authorisation conditions. It may be reasonable to automate a static test completely while retaining human approval for deploying a migration or changing accounts. A security pipeline that becomes difficult to audit creates additional uncertainty. Useful automation makes it possible to answer what changed, who approved it, which controls were run and how to return to a known state if a regression appears.
Related sources: [14] OWASP · [21] GitHub
Responsibilities, privacy and the legal limits of tools
The fact that an organisation has the technical ability to read logs, accounts or communications does not mean that any processing is lawful. Automation may involve personal data, confidential business information, evidence subject to confidentiality or access governed by contract. Before programming, purposes, authorisations, minimum access, retention and responsible parties must be identified. A script that sends data to an external API creates a technical transfer that must be assessed from the perspectives of privacy and security.
Tool outputs may be used to block a session, initiate an employment investigation, correct a system or inform an authority. Each consequence requires a review proportionate to its impact. Where evidence is incomplete, the recommendation must state that limitation. An operational alert, a suspicion of contractual non-compliance, an administrative infringement and a criminal offence must not be confused: their requirements, procedures and safeguards differ and depend on the applicable legal system.
Programme documentation contributes to accountability. It is advisable to retain the purpose, owner, sources, scope, limitations, controls, failure protocol and supervision criteria. In the event of a complaint or audit, being able to reconstruct the rule will be more useful than merely listing the tools used. Quality does not consist of filling a programme with warnings, but of incorporating proportionate, reviewable decisions that respect the rights affected.
Related sources: [15] NIST · [10] OWASP · [17] NIST
Integrated case study: “The alert that arrived twice”
The fictional case takes place in an organisation that uses an administrative portal with an identity system, a web application and an event collector. A team automates a rule to detect access after the stated deactivation date of a supplier account. The first report shows two matches and recommends escalating an incident. However, one event was forwarded again by the collector; another has an HTTP denial response code; and the inventory contains an administrative deactivation marker that does not necessarily mean that all technical sessions have been revoked.
The task is to examine four CSV files: an identity inventory, authentication events, application operations and ingestion status. The records use fictional identifiers and documentation addresses, with no real people or network connections. The reader must check duplicates, normalise UTC time, identify telemetry gaps and distinguish a recorded session from an operation that was actually permitted. They will then run a small offline analyser using the standard library and compare its output with an expected result, citing the files that support each conclusion.
A defensible answer may establish that an account was administratively marked as deactivated while associated events persisted; it may identify that a 403 does not prove an export; and it must point out that duplicate ingestion distorts a naïve count. It cannot attribute the use to a specific person or assert data exfiltration without sufficient records. The appropriate measure includes preserving relevant evidence, investigating the deactivation process, reviewing sessions and permissions, checking continuity and documenting what information would be needed to increase confidence.
Related sources: [8] Python · [9] Python · [24] IETF
Implementation method: from a small test to a sustainable control
The first step in adopting defensive automation is to select a clearly bounded need, an authorised source and an easily verifiable result. It is advisable to start in read-only mode with a small dataset, build test cases and measure false-positive rates, rejected records and execution failures. If the process uses sensitive data, the test environment should use fictional substitutes and appropriate access controls. A good prototype makes explicit both what it can discover and what it cannot.
Responsibilities are then defined: who maintains the rule, who validates changes, who receives alerts and which actions are permitted without review. Execution limits, credential management, privacy, retention, backup and contingency procedures must be planned. More automated stages should be introduced only once the output is reliable; even then, high-impact decisions may require human approval. Changes to APIs, contracts, sources, software and threats should be reviewed periodically.
The expected result is a modest but auditable tool: identifiable data, explicit rules, explainable outputs and tests that detect regressions. Automation does not replace professional judgement or resolve through code the conflict between security, availability and rights. Its contribution is to free up time spent on repetitive tasks, organise evidence and make decisions more consistent. A small system that acknowledges uncertainty is better than a spectacular dashboard that hides its assumptions.
Related sources: [15] NIST · [21] GitHub
Teaching case file and offline analyser
“The alert that arrived twice”: four fictional CSV files, a matrix, an opinion, a guide, an expected output file, a reproducible offline Python programme and a SHA-256 verifier. The test teaches readers to distinguish duplicate re-ingestion, denied authorisation, administrative deactivation and telemetry gaps.
Download the case file “The alert that arrived twice” (ZIP) (materials in Spanish)Essential glossary
- Data contract
- Schema and rules for interpreting the inputs and outputs of a process.
- Validation
- Checking types, formats, limits and relationships before using a data item.
- Normalisation
- Explicit conversion between representations while preserving meaning and provenance.
- Correlation
- An analytical relationship between events based on defined keys and rules.
- Idempotency
- The property by which repeating an operation does not successively change its final effect.
- Detection rule
- A coded criterion that classifies observations under known conditions.
- Ingestion event
- A record of the collection process, which may repeat an event from its source.
- False positive
- A signal that satisfies a rule but does not represent the fact of interest.
- UTC timestamp
- The date and time of an instant expressed in UTC for consistent comparison.
- Parameterised query
- A query that keeps values separate from SQL instructions.
- API
- An agreed interface for exchanging data or invoking operations.
- Access token
- A technical credential with a defined scope, duration and set of permissions.
- SHA-256
- An algorithm that produces a fingerprint of binary content.
- Manifest
- A list of files and verifiable attributes, such as their fingerprints.
- SBOM
- A structured inventory of software components and relationships.
- Artefact provenance
- Verifiable information about the process and materials that produced a result.
- CI/CD
- Automation for building, testing and, where applicable, publishing software.
- Telemetry
- Observational data about the operation, activity and health of a service.
Annotated sources and standards
Primary documentation from Python, NIST/IETF standards, OWASP projects, supply-chain models and technical guidance consulted in October 2026. A technical recommendation is distinguished from any specific legal obligation. The cited SP 800-92 Rev. 1 is an initial draft; it is not presented as a final standard.
- Python · Tutorial oficial. Foundation for data structures, functions, modules and programme organisation. View source
- Python · Módulo csv. Structured reading and writing; handling headers and delimiters. View source
- Python · Módulo json. Serialisation and deserialisation; distinguishing data from objects and instructions. View source
- Python · Módulo pathlib. Paths and resolution of components; a normalised path does not constitute authorisation. View source
- Python · Módulo secrets. Generation of unpredictable values for authentication and token handling. View source
- Python · Módulo subprocess. Process invocation, exit codes and precautions when using the shell. View source
- Python · Módulo sqlite3. Parameterised queries, connection handling and parameter types. View source
- Python · Módulo hashlib. Calculation of cryptographic fingerprints such as SHA-256 over binary content. View source
- Python · Módulo datetime. Timestamps and representation of timezone-aware instants. View source
- OWASP · Logging Cheat Sheet. Event design, exclusion of secrets and mitigation of log injection. View source
- OWASP · API Security Top 10 (2023). Risks involving object-level authorisation, authentication, consumption and API resources. View source
- OWASP · Input Validation Cheat Sheet. Validation rules from the design stage and trust boundaries. View source
- OWASP · SQL Injection Prevention Cheat Sheet. Separation of data and statements, and allow-lists for identifiers. View source
- OWASP · CI/CD Security Cheat Sheet. Risks and defences in automated integration and deployment pipelines. View source
- NIST · SP 800-218 Secure Software Development Framework. Secure development practices that can be integrated into different software lifecycles. View source
- NIST · SP 800-92 Gestión de registros (2006). Final guidance on log management; Revision 1 exists as an initial draft. View source
- NIST · SP 800-92 Rev. 1 (borrador inicial). Guidance under development; do not present it as a current final version. View source
- SLSA · Especificación 1.2. Supply-chain provenance and assurance levels, without implying absolute security. View source
- OWASP · CycloneDX 1.7. Representation of components, dependencies, services and other software inventories. View source
- SPDX · Especificaciones. Standardisation of materials and licence documentation; the currently published version is 3.0. View source
- GitHub · Seguridad de GitHub Actions. Verified references, attestations, deployment permissions and workflow protection. View source
- OWASP · Dependency-Check. Composition analysis and association of dependencies with publicly known vulnerabilities. View source
- IETF · RFC 3339. Internet date and time format with explicit time-zone representation. View source
- IETF · RFC 5737. IPv4 prefixes reserved for examples and documentation, not real machine addresses. View source
