Every night, at 02:00, a script called cifrar_clientes.py wakes up on srv-web01, exports Rutalia's customer database, encrypts it and uploads it to an Amazon S3 bucket. It has been running for three years. Nobody has ever checked whether that bucket is public, who can read it, what permissions the access key used by the script has, or whether that key — which is also on Marta Ruiz's laptop — has ever been rotated. Rutalia's AWS root account was created in 2023 with the personal email address of a former IT manager and it has no second factor. And the email of the company's 180 people is in Microsoft 365, where an automatic forwarding rule may have spent months copying Nuria Campos's messages to an external mailbox without anybody knowing.
Everything we have built in the previous modules — the segmentation, the hardening, the EDR, MiRutalia's fixed code — protects what is inside Rutalia's perimeter. The cloud is not inside. And yet it contains a complete copy of the portfolio of 400 customers and all the company's email.
This lesson is about what changes and what does not when data lives on somebody else's infrastructure: the exact division of responsibilities, the misconfigurations that cause the overwhelming majority of cloud incidents — which are almost never the provider's fault —, how you write a permissions policy that does not give away the account, how you read the cloud's audit logs, what managed encryption really protects and from whom, and where your data legally is when the server is in Ireland and the company is in Zaragoza.
- What changes and what does not when you move systems to the cloud
Let us begin by demolishing the two opposing myths that circulate in every board meeting.
Myth 1: "the cloud is less secure". False as a general statement. The large providers have security teams, data centres and processes that no Spanish SME could afford. The physical infrastructure of AWS, Azure or Google is better protected than Rutalia's data centre, which is a room with air conditioning and a door with a lock.
Myth 2: "the cloud is secure, the provider takes care of that". Equally false, and far more dangerous. The provider secures their part. Yours is still yours, and it is precisely where the incidents happen.
What genuinely changes:
| Aspect | In Rutalia's data centre | In the cloud |
|---|---|---|
| The perimeter | Physical and network | Identity is the perimeter |
| A misconfiguration | Affects one machine | Can expose everything to the internet in one click |
| Speed of change | Days | Seconds; somebody creates 20 resources in an afternoon |
| Inventory | Machines you can see | Resources that appear and disappear on their own |
| Audit logging | You have to build it | It exists, but you have to enable it and look at it |
| Scale of a mistake | One badly configured server | One badly configured bucket and the whole internet reads it |
| Who can touch it | Whoever gets into the data centre | Whoever has an access key, from anywhere |
What does not change, and it is worth repeating because it gets forgotten:
- Personal data is still Rutalia's responsibility before the AEPD. The provider is a processor, not the controller (06-03).
- Passwords are still passwords and MFA is still necessary.
- Least privilege is still the guiding principle.
- Vulnerable code is still vulnerable in the cloud. MiRutalia with the IDOR of 04-03 is not fixed by migrating it.
- Service models: IaaS, PaaS and SaaS
The three classic models, with what each one gives you and what it demands:
| IaaS (infrastructure) | PaaS (platform) | SaaS (software) | |
|---|---|---|---|
| What you buy | Virtual machines, networks, disks | An environment in which to deploy your code | A finished application |
| Examples | EC2, Azure virtual machines | App Service, Cloud Run, RDS | Microsoft 365, Salesforce |
| You manage | Operating system, patches, application, data | Application and data | Only the data and who has access |
| The provider manages | Hardware, virtualisation, physical network | All of the above + operating system and engine | Everything except your configuration |
| Flexibility | Maximum | Medium | Minimum |
| Security burden on you | High | Medium | Low, but never zero |
The practical conclusion for an SME with ten IT people: the higher up the stack, the less security work. Migrating the ERP to a virtual machine in the cloud (IaaS) means carrying on patching the operating system, and the whole of module 04-01 still applies in full. Buying an ERP as a service (SaaS) moves that work to the provider, in exchange for less control and a new worry: that provider's security becomes your risk (06-04).
A sentence worth engraving: you can outsource the execution, never the responsibility.
- Deployment models: public, private, hybrid
| Model | What it is | Rutalia's case |
|---|---|---|
| Public | A provider's shared infrastructure | S3 and Microsoft 365 |
| Private | Dedicated infrastructure, your own or hosted | The Zaragoza data centre is, in practice, a rudimentary private cloud |
| Hybrid | A combination with integration between the two | Rutalia's actual situation |
| Multi-cloud | Several public providers | Not applicable; it would add complexity with no benefit |
Rutalia is a typical hybrid case and it has to be acknowledged, because hybrid environments have a risk of their own that nobody watches: the joins. The connection between the data centre and the cloud, the identities synchronised between Active Directory and Microsoft 365, and the credentials a local system uses to talk to the cloud. That is where the problems occur, and not on either side on its own.
- The shared responsibility model
This is the central concept of the whole lesson. The provider is responsible for the security of the cloud; you are responsible for security in the cloud.
flowchart TD
subgraph CUSTOMER["YOUR RESPONSIBILITY - security IN the cloud"]
D["Data and its classification"]
I["Identities and permissions (IAM)"]
C["Configuration of the services"]
A["Applications and their code"]
E["Client-side encryption and key management"]
R["Virtual network, security groups"]
SO["Operating system and patches (IaaS only)"]
end
subgraph PROVIDER["THE PROVIDER'S RESPONSIBILITY - security OF the cloud"]
H["Hardware and data centres"]
V["Virtualisation layer"]
RF["Physical and global network"]
SG["Managed services: database engine, storage"]
end
CUSTOMER --> PROVIDER
style CUSTOMER fill:#fff4e0
style PROVIDER fill:#e0f0ff
And the concrete split, service by service:
| Responsibility | IaaS | PaaS | SaaS |
|---|---|---|---|
| Physical security of the data centre | Provider | Provider | Provider |
| Hypervisor and isolation between customers | Provider | Provider | Provider |
| Patching the operating system | You | Provider | Provider |
| Patching the database engine | You | Provider | Provider |
| Network configuration and virtual firewall | You | You (in part) | Provider |
| Application code | You | You | Provider |
| Configuration of the service | You | You | You |
| Identity and permission management | You | You | You |
| Classification and protection of the data | You | You | You |
| Who has access and with what privileges | You | You | You |
| Backups of your data | You | You (usually) | You <- always forgotten |
The four rows in bold never change owner, whatever the model. And the last one deserves a separate comment: a SaaS provider guarantees the availability of their service, not the recovery of your data if you delete it. Microsoft 365 keeps deleted items for a limited, configurable time; if ransomware encrypts the files synchronised with OneDrive or an employee deletes a mailbox, the default retention may not be enough. It is a conversation Rutalia still owes itself and which is picked up again in 05-05.
- Rutalia's three cases
Let us apply the model to the three concrete cases:
Case 1 - The nightly export to S3 (IaaS/storage).
| Aspect | Who is responsible |
|---|---|
| That S3 does not lose the object (durability) | AWS |
| That the bucket is not public | Rutalia |
| That the bucket policy is correct | Rutalia |
| That the access key is not on Marta's laptop | Rutalia |
| That the file is encrypted, and with which key | Rutalia |
| That anomalous access is detected | Rutalia (by enabling CloudTrail and looking at it) |
| That the Irish data centre has physical access control | AWS |
Case 2 - Microsoft 365 (SaaS).
| Aspect | Who is responsible |
|---|---|
| That the service is available and patched | Microsoft |
| That Nuria has MFA | Rutalia |
| That there are no automatic forwarding rules to external domains | Rutalia |
| That a user does not share a SharePoint folder with "anyone with the link" | Rutalia |
| That the audit logs are retained and reviewed | Rutalia |
| That backups exist beyond the default retention | Rutalia |
Case 3 - A possible ERP migration. srv-erp01 has no vendor support. Three ways out are being considered, and the responsibility model changes completely in each one:
| Option | Model | What improves | What is still yours | Verdict |
|---|---|---|---|---|
| Move the VM as it is to the cloud | IaaS | Nothing in security terms: the same unsupported system, now reachable from the internet if you are careless | Everything | Worse: it moves the problem and adds exposure |
| Buy the same vendor's ERP as a service | SaaS | Patching, availability, updates | Identities, permissions, data, integration | Better, if the vendor offers it |
| Replace it with another SaaS ERP | SaaS | All of the above + a supported product | The same + data migration | Recommended, with 06-04 |
The first row is the most common mistake in "cloud" migrations: the famous lift and shift of an unsupported machine resolves nothing and makes the exposure worse.
- Why clouds fail: it is not the provider
Cloud incidents concentrate, year after year, in a very small set of causes, and practically all of them fall on the customer's side:
| Cause | Relative frequency | Example |
|---|---|---|
| Badly configured storage | Very high | A public bucket with customer data |
| Leaked credentials | Very high | An access key in a public Git repository |
| Excessive permissions | Very high | A policy with "Action": "*" |
| No MFA on privileged accounts | High | A root account with no second factor |
| Security groups open to the internet | High | SSH or RDP on 0.0.0.0/0 |
| Forgotten resources | Medium | An unpatched test instance from 2024 |
| Snapshots or images shared publicly | Medium | A disk copy with real data |
| No audit logging | Medium | Impossible to investigate |
| Provider vulnerabilities | Low | Isolation between customers |
This table is the argument against myth 1 in section 1: the cloud does not fail; the configuration fails. And that is good news, because it means that cloud security work is fundamentally configuration and identity hygiene, not advanced cryptography or expensive technology.
- Exposed storage: Rutalia's bucket
Rutalia's bucket is called rutalia-backups-clientes and it is in the eu-west-1 region (Ireland). The cifrar_clientes.py script uploads a clientes-YYYY-MM-DD.enc file every night.
The four mechanisms that control who accesses an S3 object, which have to be understood together because they interact:
| Mechanism | What it does | Desired state |
|---|---|---|
| Block public access | A master switch at account and bucket level | All four settings enabled |
| Bucket policy | JSON defining who can do what on the bucket | Restrictive and explicit |
| Object ACL | A legacy, per-object mechanism | Disabled |
| IAM policies | Permissions of the identities that access it | Least privilege |
The classic mistake — and the one that makes the headlines — is a bucket policy like this:
{
"Version": "2012-10-17",
"Statement": [{
"Sid": "PublicReadAccess",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::rutalia-backups-clientes/*"
}]
}"Principal": "*"literally means anybody on the internet, with no authentication."Action": "s3:GetObject"allows any object to be downloaded.- A bucket with this policy is equivalent to publishing the folder on a website.
Nobody writes this on purpose. It turns up in three ways: it was copied from a tutorial about serving images for a website, somebody set it "just for a moment to test something", or the bucket was created before block public access came enabled by default.
The correct policy for Rutalia:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyUnencryptedTransport",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::rutalia-backups-clientes",
"arn:aws:s3:::rutalia-backups-clientes/*"
],
"Condition": { "Bool": { "aws:SecureTransport": "false" } }
},
{
"Sid": "DenyUploadWithoutKmsEncryption",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::rutalia-backups-clientes/*",
"Condition": {
"StringNotEquals": { "s3:x-amz-server-side-encryption": "aws:kms" }
}
},
{
"Sid": "AllowOnlyTheBackupRole",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::123456789012:role/rutalia-backup-nocturno"
},
"Action": ["s3:PutObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::rutalia-backups-clientes",
"arn:aws:s3:::rutalia-backups-clientes/*"
]
}
]
}An analysis of the three statements:
DenyUnencryptedTransport: aDenythat applies to anybody, including the account itself, if the connection does not use TLS. In IAM, an explicitDenyalways prevails over anyAllow; this is the property that makes deny statements useful as a safety net.DenyUploadWithoutKmsEncryption: it prevents an object being uploaded without KMS-managed encryption. It guarantees that nobody can upload a file in the clear by mistake.AllowOnlyTheBackupRole: the policy's onlyAllow, limited to one specific role (section 11) and to two actions. Notice what is not there: there is nos3:GetObjectand nos3:DeleteObject. The backup process writes and neither reads nor deletes, which is exactly what a backup should be able to do in order to be ransomware-resistant.
- Checking that a bucket is not public
This is the section Laura works through on day one. It is three commands.
Check 1: block public access.
Correct output:
{
"PublicAccessBlockConfiguration": {
"BlockPublicAcls": true,
"IgnorePublicAcls": true,
"BlockPublicPolicy": true,
"RestrictPublicBuckets": true
}
}The four settings, one by one:
BlockPublicAcls: rejects any new attempt to set a public ACL.IgnorePublicAcls: ignores public ACLs that already exist. It is the one that fixes the past.BlockPublicPolicy: rejects bucket policies that grant public access.RestrictPublicBuckets: if a public policy already exists, it limits its effect to principals in the account itself and to AWS services.
All four must be true. If the command returns a NoSuchPublicAccessBlockConfiguration error, it means no block is configured at all: the worst possible result.
Enabling them:
aws s3api put-public-access-block \
--bucket rutalia-backups-clientes \
--public-access-block-configuration \
BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
# And, far better, across the WHOLE account, so that no future bucket is born public
aws s3control put-public-access-block --account-id 123456789012 \
--public-access-block-configuration \
BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=trueCheck 2: the verdict on the policy.
This command gives the answer directly: IsPublic: false means AWS has evaluated the policy and concludes that it grants no public access. It is more reliable than reading the JSON by eye, because policy evaluation has subtleties (conditions, service principals, wildcards) that are easy to get wrong.
Check 3: encryption, versioning and logging.
# Default encryption at rest?
aws s3api get-bucket-encryption --bucket rutalia-backups-clientes
# Versioning enabled? (it protects against deletion and overwriting)
aws s3api get-bucket-versioning --bucket rutalia-backups-clientes
# Is object access being logged?
aws s3api get-bucket-logging --bucket rutalia-backups-clientesAnd the sweep across the whole account, which is what you really have to run:
#!/usr/bin/env bash
# auditar_buckets.sh - Rutalia. Read-only.
for b in $(aws s3api list-buckets --query 'Buckets[].Name' --output text); do
pub=$(aws s3api get-bucket-policy-status --bucket "$b" \
--query 'PolicyStatus.IsPublic' --output text 2>/dev/null || echo "NO_POLICY")
blk=$(aws s3api get-public-access-block --bucket "$b" \
--query 'PublicAccessBlockConfiguration.RestrictPublicBuckets' \
--output text 2>/dev/null || echo "NO_BLOCK")
enc=$(aws s3api get-bucket-encryption --bucket "$b" \
--query 'ServerSideEncryptionConfiguration.Rules[0].ApplyServerSideEncryptionByDefault.SSEAlgorithm' \
--output text 2>/dev/null || echo "NO_ENCRYPTION")
printf "%-42s public=%-12s block=%-12s encryption=%s\n" "$b" "$pub" "$blk" "$enc"
done--queryuses JMESPath to extract a single value from the JSON response: it avoids having to parse the output with external tools.|| echo "NO_..."turns the "no configuration exists" error into a readable value, which is precisely the dangerous case.
Real output from the first run at Rutalia, on 3 May 2027:
rutalia-backups-clientes public=False block=True encryption=aws:kms rutalia-web-estatico public=True block=NO_BLOCK encryption=AES256 rutalia-pruebas-2024 public=NO_POLICY block=NO_BLOCK encryption=NO_ENCRYPTION rutalia-logs-nginx public=False block=True encryption=AES256
Three findings in five seconds:
rutalia-web-estaticois public. Here you have to investigate before acting: if it contains only the images from the corporate website, it is correct and deliberate. If it contains anything else, it is a breach. It turned out to contain, as well as the images, an internal-usecatalogo_tarifas_2025.pdf.rutalia-pruebas-2024has no block, no policy and no encryption. It is a forgotten resource, category 6 in the table in section 6. It contained a dump of the test database with real customer data. It is the same problem as the 9 test VMs of 04-01, now in the cloud.- None of them had object access logging enabled.
- Identity and permissions: the heart of cloud security
In a data centre, the perimeter is the network. In the cloud, the perimeter is identity: whoever has a valid credential can act from anywhere in the world, and no VLAN stops them.
The IAM concepts in AWS, with their mental equivalent:
| Concept | What it is | Analogy |
|---|---|---|
| Root account | The absolute owner of the account | The superuser that must not be used |
| IAM user | A permanent identity with credentials | A person or service account |
| Group | A set of users with the same permissions | An AD group |
| Role | An identity that is assumed temporarily, with no fixed credentials | A sudo with credentials that expire |
| Policy | A JSON document that grants or denies permissions | An ACL |
| Temporary credentials | Keys that expire in minutes or hours | A Kerberos ticket |
And the four policy evaluation rules, which you have to know in order not to write things that do not do what you think:
- Everything is denied by default. Without an explicit
Allow, nothing can be done. - An explicit
Allowgrants the permission. - An explicit
Denyalways wins, wherever it comes from. - Policies at different levels (account, role, resource, session) intersect: you need permission at every applicable level.
Rule 3 is what makes it possible to build guardrails: an organisation policy denying s3:PutBucketPolicy to everybody except one specific role stops anybody, not even an administrator, from making a bucket public by mistake.
- An over-permissive IAM policy and its fix
This is the actual policy currently attached to the rutalia-backup user that cifrar_clientes.py uses:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "FullAccess",
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}
]
}Translation: this user can do absolutely anything in the entire AWS account. Create and destroy servers, read and delete every bucket, create new users, change the billing, alter the audit logs. And its keys are on srv-web01 and on Marta's laptop.
How you end up here, because the mechanism is always the same: the script was failing with a permissions error, somebody tried "*" "to see if that was it", it worked, and there it stayed. For three years.
The fix, with the principle of least privilege genuinely applied:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "UploadNightlyBackup",
"Effect": "Allow",
"Action": [
"s3:PutObject"
],
"Resource": "arn:aws:s3:::rutalia-backups-clientes/clientes-*.enc",
"Condition": {
"StringEquals": {
"s3:x-amz-server-side-encryption": "aws:kms"
},
"IpAddress": {
"aws:SourceIp": "203.0.113.10/32"
}
}
},
{
"Sid": "ListOnlyOurOwnPrefix",
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::rutalia-backups-clientes",
"Condition": {
"StringLike": { "s3:prefix": "clientes-*" }
}
},
{
"Sid": "UseTheEncryptionKey",
"Effect": "Allow",
"Action": ["kms:GenerateDataKey", "kms:Encrypt"],
"Resource": "arn:aws:kms:eu-west-1:123456789012:key/a1b2c3d4-...",
"Condition": {
"StringEquals": { "kms:ViaService": "s3.eu-west-1.amazonaws.com" }
}
},
{
"Sid": "DenyDeletionAlways",
"Effect": "Deny",
"Action": [
"s3:DeleteObject",
"s3:DeleteObjectVersion",
"s3:PutBucketPolicy",
"s3:PutBucketAcl"
],
"Resource": "*"
}
]
}A line-by-line commentary on the decisions:
"Action": ["s3:PutObject"]and nothing else. The process uploads files. It does not need to read them, list them all or delete them. If an attacker steals these credentials tomorrow, they cannot download a single backup file."Resource"with a name pattern:clientes-*.enc. Not even inside the bucket can it write wherever it likes. An attacker cannot upload a maliciousindex.htmlor overwrite other objects.Conditionwiths3:x-amz-server-side-encryption: the upload is only allowed if it is encrypted with KMS. The technical policy enforces compliance; it does not depend on the script doing the right thing.Conditionwithaws:SourceIp: only from Rutalia's public IP. This single condition turns stolen credentials into a useless keyring for anybody who is not inside Rutalia's network. It is probably the line with the best effort-to-protection ratio in the whole policy.kms:ViaService: the encryption key can only be used through S3, not directly. It stops whoever holds these credentials encrypting or decrypting things on their own account.DenyDeletionAlways: an explicitDenywhich, by rule 3, prevails over any present or futureAllow. Even if somebody widens the permissions by mistake next year, this user will never be able to delete objects or change the bucket policy. It is a guardrail, not a door.
The result: if rutalia-backup's credentials leak tomorrow, the attacker can upload encrypted files to one specific prefix of one specific bucket, from a single IP address. Practically nothing.
- Roles versus long-lived access keys
An IAM access key is an identifier/secret pair that never expires. It is the equivalent of a password nobody ever changes and which, on top of that, travels through scripts, configuration files and laptops.
A role is an identity that is assumed temporarily and that hands out credentials expiring in minutes or hours.
| Access key | Role | |
|---|---|---|
| Expiry | Never | Minutes or hours |
| Where it lives | In a file, in the code, on a laptop | Nowhere: it is obtained on the fly |
| If it leaks | Valid until somebody revokes it | Useless within an hour |
| Rotation | Manual, and forgotten | Automatic by design |
| Auditing | Hard to know who used it | Every assumption is logged |
The rule: long-lived access keys should only exist when there is no alternative. And there almost always is one:
| Case | Alternative with no permanent key |
|---|---|
| An application on an EC2 instance | An instance role: the machine itself obtains temporary credentials |
| A container | A task role |
| A serverless function | An execution role |
| Your own server outside the cloud (Rutalia's case) | Federation: IAM Roles Anywhere with a certificate, or OIDC federation |
| A person | Federated sign-in with the corporate identity provider + MFA |
| A continuous integration system | OIDC federation with the repository provider |
Rutalia's case is the fourth: srv-web01 is in the Zaragoza data centre, not in AWS, so it cannot use an instance role. The two realistic ways out:
- In the short term: keep the key, but with the restricted policy of section 10 (including the IP condition), automatic rotation every 90 days and storage in the
systemdenvironment file with600permissions, as we did with MiRutalia's secrets in 04-03. - In the medium term: federation with a certificate from the internal PKI of 02-05, so that
srv-web01obtains temporary credentials by presenting its certificate. It removes the permanent key entirely.
- The AWS key on Marta's laptop
The finding of 3 May, during the workstation review:
[default]
aws_access_key_id = AKIAIOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
[rutalia-prod]
aws_access_key_id = AKIAI44QH8DHBEXAMPLE
aws_secret_access_key = je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEYWhy this is a first-order problem:
- It is the same key used by
cifrar_clientes.py, the one with"Action": "*". - It is in plain text in the user's profile, unencrypted, on a laptop that travels.
~/.aws/credentialsis one of the files that the information stealers we saw in 04-02 look for specifically: it is in a known path, in a known format, and it is directly monetisable.- Marta used it once, in 2024, to debug the script. She never deleted it.
- And, under the current policy, that key amounts to complete ownership of Rutalia's infrastructure in AWS.
The actions, in order:
# 1. Check when it was last used and from where
aws iam get-access-key-last-used --access-key-id AKIAI44QH8DHBEXAMPLE{
"UserName": "rutalia-backup",
"AccessKeyLastUsed": {
"LastUsedDate": "2027-05-03T02:00:14+00:00",
"ServiceName": "s3",
"Region": "eu-west-1"
}
}This query comes first for a reason: it says whether the key is still in use and which service uses it. If the last use had been two years ago, you disable it and that is that. Here it is in daily use at 02:00, which is the nightly script.
# 2. Create a NEW key for the service, deploy it and verify that it works
aws iam create-access-key --user-name rutalia-backup
# 3. Deactivate the old one WITHOUT deleting it, so you can roll back if something fails
aws iam update-access-key --user-name rutalia-backup \
--access-key-id AKIAI44QH8DHBEXAMPLE --status Inactive
# 4. After 48 h with no incidents, delete it for good
aws iam delete-access-key --user-name rutalia-backup \
--access-key-id AKIAI44QH8DHBEXAMPLE
# 5. Delete the file from Marta's laptop
shred -u ~/.aws/credentialsStep 3 — deactivate before deleting — is the difference between a controlled rotation and a service outage at two in the morning.
And the missing step, which is the most important one: find out where else that key is.
# Is it in MiRutalia's repository?
git log -p --all -S "AKIA" | grep -E "^\+.*AKIA"
# Is it in any file on the file server?
grep -rl "AKIA[0-9A-Z]\{16\}" /mnt/fs01/comun/ 2>/dev/nullThe pattern AKIA followed by 16 upper-case alphanumeric characters is the format of AWS key identifiers, and it is what the automated scanners crawling GitHub look for. A key published in a public repository is exploited, according to multiple documented experiments, within minutes.
- Credential rotation and how to audit it
Rutalia's policy: no access key may be more than 90 days old. The script that checks it:
#!/usr/bin/env python3
"""
auditar_claves_aws.py - Rutalia
Lists the IAM access keys with their age and last use.
Read-only: it modifies nothing. Exit code 2 if there are critical keys.
"""
import boto3
from datetime import datetime, timezone
WARN_THRESHOLD = 90 # days
CRITICAL_THRESHOLD = 180 # days
UNUSED_THRESHOLD = 90 # days without use -> a candidate for deletion
iam = boto3.client("iam")
now = datetime.now(timezone.utc)
critical = 0
print(f"{'USER':<24} {'KEY':<22} {'STATUS':<9} {'AGE':>5} {'LAST USED':>12} VERDICT")
print("-" * 100)
# The paginator walks ALL the users even if there are more than 100
for page in iam.get_paginator("list_users").paginate():
for user in page["Users"]:
name = user["UserName"]
keys = iam.list_access_keys(UserName=name)["AccessKeyMetadata"]
for key in keys:
kid = key["AccessKeyId"]
age = (now - key["CreateDate"]).days
# Last use: it may not exist if the key has never been used
usage = iam.get_access_key_last_used(AccessKeyId=kid)["AccessKeyLastUsed"]
if "LastUsedDate" in usage:
days_unused = (now - usage["LastUsedDate"]).days
usage_txt = f"{days_unused}d ago"
else:
days_unused = age
usage_txt = "NEVER"
# The verdict, combining age and use
if key["Status"] == "Inactive":
verdict = "inactive (delete)"
elif days_unused >= UNUSED_THRESHOLD:
verdict = "UNUSED -> DELETE"
critical += 1
elif age >= CRITICAL_THRESHOLD:
verdict = "CRITICAL: rotate now"
critical += 1
elif age >= WARN_THRESHOLD:
verdict = "warning: rotate"
else:
verdict = "ok"
print(f"{name:<24} {kid:<22} {key['Status']:<9} "
f"{age:>4}d {usage_txt:>12} {verdict}")
print(f"\n{critical} key(s) require immediate action.")
raise SystemExit(2 if critical else 0)Notes on the code:
get_paginator: cloud APIs return paginated results. Iterating only the first page is a very common mistake that makes the report look clean when it is not.- Two criteria are combined: age and last use. A 200-day key that is used daily has to be rotated; a 30-day key that has never been used has to be deleted, because it is pure attack surface.
"NEVER"is the most interesting verdict: a key that was created and never used is usually the leftover of a test, and nobody will miss it.- The exit code 2 lets you run it from
cronand be notified only when there is something to do, just like the hardening script of 04-01.
The output at Rutalia:
USER KEY STATUS AGE LAST USED VERDICT ---------------------------------------------------------------------------------------- rutalia-backup AKIAI44QH8DHBEXAMPLE Active 1094d 0d ago CRITICAL: rotate now rutalia-backup AKIAI55RH9EIBEXAMPLE Active 2d 0d ago ok mruiz-dev AKIAIOSFODNN7EXAMPLE Active 842d 401d ago UNUSED -> DELETE terraform-2024 AKIAJ77TH2KLCEXAMPLE Active 612d NEVER UNUSED -> DELETE srv-monitor AKIAK99UH3MNDEXAMPLE Active 120d 1d ago warning: rotate 3 key(s) require immediate action.
- The fake key canary
A trick that costs ten minutes and detects what nothing else detects. You create an IAM user with no permissions at all, with an access key, and you place that key in the places an attacker would look for credentials:
| Where the decoy is placed | What it detects |
|---|---|
A server's ~/.aws/credentials |
Compromise of that machine |
A config.py.bak file on \\fs01\comun |
An insider walking through the share (H3) |
| An old branch of MiRutalia's repository | A repository leak |
A credenciales_aws.txt file next to claves.xlsx |
The same scenario as the claves_admin_2026.xlsx of 03-03 |
The user has no permissions, so any attempt to use it fails. But the attempt is recorded in CloudTrail, and that is where the value lies:
{
"eventTime": "2027-06-11T03:47:22Z",
"eventName": "GetCallerIdentity",
"userIdentity": {
"type": "IAMUser",
"userName": "svc-aws-legacy-backup",
"accessKeyId": "AKIAQ11CANARIOEXAMPLE"
},
"sourceIPAddress": "192.0.2.66",
"errorCode": "AccessDenied"
}The alert is configured on any appearance of that key's identifier:
Rule: any CloudTrail event whose accessKeyId is AKIAQ11CANARIOEXAMPLE Severity: CRITICAL Action: an immediate alert to [email protected] + open an incident Expected false positives: ZERO
GetCallerIdentity is also the first command almost anybody who finds AWS credentials runs: it tells them whose they are. The canary fires in the first second.
And it is worth pointing out the most valuable piece of data in that event: sourceIPAddress. It says where the credential was used from, which in this example is 192.0.2.66, the IP of the attacker from the canonical scenario. It is a lead you get in no other way.
- MFA and protecting the root account
The AWS root account is the one created when the account was opened. Its permissions cannot be restricted: it can do everything, including closing the account and changing the billing details.
The state at Rutalia is the worst possible: the root account is tied to the personal email address of a former IT manager, it has no MFA, and its password is in claves.xlsx.
The rules for the root account, with no exceptions:
| Rule | Why |
|---|---|
| Mandatory MFA, preferably with a physical FIDO2 key | It is the only control that prevents use with a leaked password |
| The email address tied to a shared, monitored corporate mailbox, never a personal one | If the person leaves, the account is not lost |
| A unique, long password, in the corporate password manager | Not in claves.xlsx |
| No access keys | The root account must never be used through the API |
| Not used for operations: only for the tasks that require it | Billing changes, closing the account |
| An automatic alert on any root sign-in | It must be an exceptional and pre-announced event |
| Up-to-date emergency phone number and contact details | Account recovery |
Checking:
# Does the root account have MFA? (1 = yes)
aws iam get-account-summary --query 'SummaryMap.AccountMFAEnabled'
# Does root have access keys? (it must be 0)
aws iam get-account-summary --query 'SummaryMap.AccountAccessKeysPresent'
# A full credential report for every user
aws iam generate-credential-report
aws iam get-credential-report --query 'Content' --output text | base64 -d > report.csvThat report.csv is one of the most useful free tools there is: one row per user showing whether they have a password, whether they have MFA, when each key was last used, and since when. It is an identity audit of the whole account in a single command.
And the MFA plan for the rest of the AWS accounts fits into the six-phase plan of 02-03: no identity with write permissions without a second factor, and a condition in the policies denying sensitive actions if the session was not authenticated with MFA:
{
"Sid": "RequireMfaForSensitiveActions",
"Effect": "Deny",
"Action": ["iam:*", "s3:DeleteBucket", "kms:ScheduleKeyDeletion", "ec2:TerminateInstances"],
"Resource": "*",
"Condition": {
"BoolIfExists": { "aws:MultiFactorAuthPresent": "false" }
}
}The BoolIfExists condition is an important detail: it also covers the cases where the context key does not exist (access through a permanent access key, which never has MFA), denying those too.
- Audit logging: CloudTrail and its equivalents
Without audit logging there is no way of knowing what happened. In the cloud this is more serious than in the data centre, because there is no machine to examine: if somebody deletes a resource, it disappears without a trace except in the log.
| Provider | Audit service | What it records |
|---|---|---|
| AWS | CloudTrail | Every API call: who, what, when, from where |
| Azure | Activity log + Entra ID | The same |
| Google Cloud | Cloud Audit Logs | The same |
| Microsoft 365 | The unified audit log | Access, sends, sharing, configuration changes |
The correct CloudTrail configuration, which is where the mistakes are made:
| Setting | Correct value | Why |
|---|---|---|
| All regions | Yes | An attacker creates resources in a region you do not use, precisely for that reason |
| Destination | A bucket in another account or with object lock | So that the attacker cannot delete the evidence |
| Integrity validation | Enabled | It detects tampering with the log files |
| Encryption with KMS | Yes | The log contains sensitive information |
| Retention | 1 year as a minimum | The canonical scenario lasted 25 days; investigations look further back |
| Data events | At least on the sensitive buckets | By default, access to S3 objects is not logged |
The penultimate row hides a trap that costs dearly: CloudTrail, by default, logs operations on buckets but not reads of the objects. That is: it logs that somebody changed the bucket policy, but not that somebody downloaded the 400 customers. For that you have to explicitly enable data events, which carry an additional cost. For Rutalia, the decision is to enable them only on rutalia-backups-clientes: a few euros a month to know who reads the entire portfolio.
aws cloudtrail put-event-selectors --trail-name rutalia-trail \
--advanced-event-selectors '[{
"Name": "Object access in the backup bucket",
"FieldSelectors": [
{"Field": "eventCategory", "Equals": ["Data"]},
{"Field": "resources.type", "Equals": ["AWS::S3::Object"]},
{"Field": "resources.ARN", "StartsWith": ["arn:aws:s3:::rutalia-backups-clientes/"]}
]}]'
- Reading a CloudTrail event
A CloudTrail event is JSON. This is a real one from Rutalia's account, dated 11 June 2027:
{
"eventVersion": "1.09",
"eventTime": "2027-06-11T03:52:07Z",
"eventSource": "s3.amazonaws.com",
"eventName": "GetObject",
"awsRegion": "eu-west-1",
"sourceIPAddress": "192.0.2.66",
"userAgent": "[aws-cli/2.15.17 Python/3.11.6 Linux/6.1.0 exe/x86_64]",
"userIdentity": {
"type": "IAMUser",
"principalId": "AIDAI23HXD2O5EXAMPLE",
"arn": "arn:aws:iam::123456789012:user/rutalia-backup",
"accountId": "123456789012",
"userName": "rutalia-backup",
"accessKeyId": "AKIAI44QH8DHBEXAMPLE"
},
"requestParameters": {
"bucketName": "rutalia-backups-clientes",
"key": "clientes-2027-06-10.enc"
},
"responseElements": null,
"additionalEventData": {
"SignatureVersion": "SigV4",
"bytesTransferredOut": 148372911
},
"readOnly": true,
"eventID": "3f2a91c7-8b04-4e5d-9a13-2c7f1e08b4d6",
"recipientAccountId": "123456789012"
}How this event is read, field by field, and why it is a critical alert:
| Field | Value | Reading |
|---|---|---|
eventTime |
03:52 UTC | Outside the window of the nightly process, which runs at 02:00 |
eventName |
GetObject |
It is a download. The legitimate process only does PutObject |
sourceIPAddress |
192.0.2.66 |
It is not 203.0.113.10, Rutalia's public IP. It is the attacker from the canonical scenario |
userAgent |
aws-cli/2.15.17 |
The script uses boto3, not the CLI. Somebody is typing commands |
userName |
rutalia-backup |
The backup process's credential, being used by a person |
key |
clientes-2027-06-10.enc |
The previous day's copy of the customer portfolio |
bytesTransferredOut |
148,372,911 | 141 MB downloaded. It is the complete database |
Five independent anomalies, each one enough to raise an alert, and the conclusion is unmistakable: rutalia-backup's credentials are compromised and the customer portfolio is being exfiltrated. It is hypothesis H3 realised by another route, or the exfiltration phase of H1.
And here you can see the value of the restrictive policy in section 10: with "Action": ["s3:PutObject"] and the aws:SourceIp condition, this event would have been an AccessDenied. Two lines of JSON written in May would have turned a 141 MB leak into an alert with no impact.
The detection rules Rutalia configures on CloudTrail, all of them free or nearly so:
| # | Rule | Severity |
|---|---|---|
| 1 | A sign-in by the root account | CRITICAL |
| 2 | Use of any credential from an IP outside 203.0.113.0/24 |
HIGH |
| 3 | GetObject on rutalia-backups-clientes by any identity other than the restore role |
CRITICAL |
| 4 | PutBucketPolicy, PutBucketAcl or DeletePublicAccessBlock |
CRITICAL |
| 5 | StopLogging or DeleteTrail on CloudTrail |
CRITICAL: it is the erasing of tracks |
| 6 | CreateUser, CreateAccessKey, AttachUserPolicy |
HIGH |
| 7 | Any use of the canary key's identifier | CRITICAL |
| 8 | ConsoleLogin without MFA |
HIGH |
| 9 | Activity in a region Rutalia does not use | HIGH |
| 10 | AuthorizeSecurityGroupIngress with 0.0.0.0/0 |
HIGH |
Rule 5 deserves a comment: disabling logging is one of the first actions of a competent attacker, just like the wevtutil cl Security we saw in 04-02. An alert on StopLogging is one of the most valuable you can configure, because the very fact that it fires is already the proof.
- Virtual networks and security groups
Everything learned in 03-03 and 03-04 applies in the cloud in the same way, under different names:
| Data centre concept | AWS equivalent | Azure equivalent |
|---|---|---|
| VLAN | A subnet inside a VPC | A virtual network subnet |
| Stateful firewall | Security group (per instance) | Network security group |
| Stateless ACL | Network ACL (per subnet) | — |
| DMZ | Public subnet | Public subnet |
| Internal network | Private subnet, with no route to the internet | Private subnet |
| Bastion | A bastion instance or a managed access service | Azure Bastion |
The most frequent and most exploited mistake:
# Look for security groups with SSH or RDP open to the whole internet
aws ec2 describe-security-groups \
--filters "Name=ip-permission.cidr,Values=0.0.0.0/0" \
--query 'SecurityGroups[].{
Name:GroupName,
Id:GroupId,
Rules:IpPermissions[?contains([22,3389,3306,5432,6379,27017], FromPort)].[FromPort,ToPort]
}' --output table--filtersnarrows the query server-side to the groups that allow something from0.0.0.0/0.- The
--queryexpression then filters by the ports that should never be open to the internet: SSH (22), RDP (3389), MySQL (3306), PostgreSQL (5432), Redis (6379) and MongoDB (27017).
A port 22 open to 0.0.0.0/0 receives, on a freshly created machine, thousands of authentication attempts a day. It is not a hypothesis: it is the normal behaviour of the internet.
The correct configuration, which reproduces Rutalia's design:
| Resource | Inbound rule | Source |
|---|---|---|
| Load balancer / web server | 443 | 0.0.0.0/0 (it is the service) |
| Application server | 8000 | The load balancer's security group, not an IP range |
| Database | 5432 | The application's security group |
| Administration | 22 | Only from the bastion, or better: none at all, using managed access with no open port |
The technical detail worth noting: in AWS, a security group can reference another security group as a source, instead of an IP range. It is better than any address list, because it stays correct even when instances change IP, and it expresses the intent: "the database accepts connections from the application machines", which is exactly the flow matrix of 03-04.
- Snapshots, images and public copies
One leak route nobody watches: disk snapshots and machine images can be shared, and sharing them publicly is one click away.
# Are any of our snapshots public?
aws ec2 describe-snapshots --owner-ids 123456789012 \
--query 'Snapshots[].SnapshotId' --output text | tr '\t' '\n' | \
while read snap; do
perms=$(aws ec2 describe-snapshot-attribute --snapshot-id "$snap" \
--attribute createVolumePermission \
--query 'CreateVolumePermissions' --output text)
[ -n "$perms" ] && echo "SHARED: $snap -> $perms"
done
# Is any AMI public?
aws ec2 describe-images --owners 123456789012 \
--query 'Images[?Public==`true`].[ImageId,Name]' --output tableA public snapshot is a complete copy of the disk: operating system, configuration, credentials, data. Anybody can create a volume from it and mount it. It is one of the quietest ways of leaking an entire organisation, because it generates no traffic in your account at all.
The same caution applies to managed database snapshots: an RDS snapshot shared publicly exposes the whole database.
- Microsoft 365: conditional access
Rutalia's 180 people use Microsoft 365 for email, files and office work. It is by a long way the cloud system holding most of the company's data, and today the only protection is the password.
Conditional access is the mechanism that lets you decide, on each access attempt, whether to grant it, deny it or require something more, based on signals: who, from where, with which device, to which application and with what level of risk.
flowchart LR
U["Access attempt"] --> S{"Signals"}
S --> S1["User and group"]
S --> S2["Location / IP"]
S --> S3["Device: managed?"]
S --> S4["Application"]
S --> S5["Session risk"]
S1 --> D{"Decision"}
S2 --> D
S3 --> D
S4 --> D
S5 --> D
D -->|"Grant"| A["Access"]
D -->|"Grant with MFA"| M["MFA + Access"]
D -->|"Block"| B["Denied"]
The policies Rutalia puts in place, in deployment order:
| # | Policy | Scope | Effect |
|---|---|---|---|
| 1 | Block legacy authentication | Everybody | It closes IMAP, POP3 and basic SMTP, which do not support MFA |
| 2 | Mandatory MFA for administrators | Privileged roles | The most critical first |
| 3 | MFA for all users | Everybody | Phase 4 of the plan in 02-03 |
| 4 | Block access from countries where Rutalia does not operate | Everybody | It drastically reduces the noise |
| 5 | Require a compliant device to download files | Everybody | It links to the MDM of 04-02 |
| 6 | Non-persistent sessions on unmanaged devices | Everybody | No "keep me signed in" on somebody else's machine |
| 7 | MFA on medium or high sign-in risk | Everybody | It requires a higher licence; under consideration |
Policy 1 is the most important and the least often applied. The old email protocols — IMAP, POP3, SMTP with basic authentication — do not support a second factor: whoever has the password gets in, whatever MFA Rutalia has. It is the gap through which most mailbox compromises slip, and it is exactly the vector of hypothesis H2 (CEO fraud). Blocking it is a tick box, and you have to check first which old devices use it: at Rutalia, a multifunction printer that emailed scans, which was reconfigured with a modern connector.
Policy 4 deserves a warning: it is noise reduction, not a barrier. An attacker uses a server in Spain or a VPN within five minutes. It serves to remove the constant background of automated attempts, not to stop somebody determined.
- Microsoft 365: auditing and automatic forwarding rules
The automatic forwarding rule is the most reliable indicator of mailbox compromise there is. Its logic from the attacker's point of view: once inside Nuria Campos's mailbox, they do not want to have to come back in — that generates suspicious sign-ins. They want the email to come to them. So they create a rule that forwards the messages to an external mailbox and, often, moves them to a barely visible folder or marks them as read.
Connected to H2: the attacker spends weeks reading the correspondence between Nuria (payments) and the suppliers, learns the format of the invoices, the usual amounts and the tone of the messages, and at the right moment sends a request to change bank account details that is indistinguishable from the real ones. The forwarding rule is what makes all that preparation possible.
Detection:
# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName [email protected]
# 1. Mailbox rules that forward or redirect to EXTERNAL addresses
Get-Mailbox -ResultSize Unlimited | ForEach-Object {
$mailbox = $_.PrimarySmtpAddress
Get-InboxRule -Mailbox $mailbox -ErrorAction SilentlyContinue | Where-Object {
$_.ForwardTo -or $_.ForwardAsAttachmentTo -or $_.RedirectTo
} | ForEach-Object {
[PSCustomObject]@{
Mailbox = $mailbox
Rule = $_.Name
Enabled = $_.Enabled
Target = ($_.ForwardTo + $_.ForwardAsAttachmentTo + $_.RedirectTo) -join '; '
MoveTo = $_.MoveToFolder
Delete = $_.DeleteMessage
}
}
} | Where-Object { $_.Target -notmatch 'rutalia\.example' } | Format-Table -AutoSize -Wrap
# 2. Forwarding configured at MAILBOX level (different from rules; it gets forgotten)
Get-Mailbox -ResultSize Unlimited |
Where-Object { $_.ForwardingSmtpAddress -or $_.ForwardingAddress } |
Select-Object PrimarySmtpAddress, ForwardingSmtpAddress, DeliverToMailboxAndForwardThe points of the query that matter:
- Two different places are checked: the inbox rules (which the user or the attacker creates) and the mailbox-level forwarding (set in the properties). Looking at only one of the two is the usual mistake.
RedirectToas well asForwardTo: redirecting is stealthier, because the message does not appear as forwarded.MoveToFolderandDeleteMessage: if the rule also moves the message to "Deleted Items" or to a folder calledRSSor similar, and marks it as read, the intent to conceal is unmistakable. A legitimate rule does not hide messages.- The
-notmatch 'rutalia\.example'filter: internal forwarding is usually legitimate (a leave of absence, a stand-in); external forwarding almost never is.
An example of a finding at Rutalia on 19 June 2027:
Mailbox Rule Enabled Target MoveTo Delete ------- ---- ------- ------ ------ ------ [email protected] ... True [email protected] Deleted Items True
Note the name of the rule: three dots. It is a known trick: a name that is practically invisible in Outlook's rule list. Combined with forwarding to an external domain that imitates a plausible name, the local deletion and the move to deleted items, there is no possible benign interpretation.
The immediate response — disabling the rule, revoking sessions, changing the password, enabling MFA, reviewing the outbound messages and checking whether any supplier bank details have been modified — belongs to the process of 05-02 and 05-03. What belongs here is prevention and detection:
| Control | Effect |
|---|---|
| Block automatic external forwarding at organisation level | It removes the technique completely |
| An alert on the creation of forwarding rules | Detection within minutes |
| An alert on the creation of rules with empty or one-character names | Detection of the concealment pattern |
| An automated weekly check with the script above | A safety net |
| Enable mailbox audit logging for everybody | Without it, there is no history of what was read |
Organisation-level blocking is done with an outbound spam policy that rejects external automatic forwarding. There are legitimate exceptions — somebody redirecting their email during a leave of absence — and they are handled as documented exceptions, not by leaving forwarding open for everyone.
- Microsoft 365: external file sharing
SharePoint and OneDrive allow a file or a folder to be shared with a link. The default configuration is usually generous, and the result is that internal documents end up reachable through a link circulating by email, by messaging or by whatever means.
The sharing levels, from most to least dangerous:
| Level | Who gets access | Acceptable use at Rutalia |
|---|---|---|
| Anyone with the link | The whole internet, with no authentication | Disable |
| People in existing organisations | Guests already registered | Yes, for regular customers and suppliers |
| Specific people | Only those invited, after authenticating | The recommended default |
| Only people in the organisation | Internal | For the sensitive sites |
The configuration for Rutalia:
# Organisation level: remove anonymous links
Set-SPOTenant -SharingCapability ExternalUserSharingOnly `
-DefaultSharingLinkType Direct `
-DefaultLinkPermission View `
-RequireAnonymousLinksExpireInDays 30 `
-PreventExternalUsersFromResharing $trueSharingCapability ExternalUserSharingOnly: you can share with external people, but they have to authenticate. Anonymous links are removed.DefaultSharingLinkType Direct: when somebody clicks "Share", the preselected option is "specific people", not "anyone with the link". Defaults decide the behaviour of 90% of users.DefaultLinkPermission View: read by default, not edit.PreventExternalUsersFromResharing: a guest cannot pass the access on to third parties.
And an audit of what is already shared:
# A report of external sharing over the last 90 days
Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-90) -EndDate (Get-Date) `
-Operations SharingInvitationCreated,AnonymousLinkCreated,SharingSet `
-ResultSize 5000 |
Select-Object CreationDate, UserIds, Operations, AuditData |
Export-Csv -Path C:\auditoria\external_sharing.csv -NoTypeInformation -Encoding UTF8AnonymousLinkCreated is the operation to review first: every one of those lines is a file reachable without authentication.
- Encryption in the cloud: at rest, in transit and keys
Three layers, and it is important not to confuse them:
| Layer | What it protects | How it is achieved |
|---|---|---|
| In transit | Interception on the network | TLS, mandatory by policy (section 7) |
| At rest | Access to the physical media | The service's encryption, almost always a tick box |
| Client-side | All of the above + the provider itself | Encrypting before uploading |
The key management options at rest, ordered by control:
| Option | Who holds the key | Who can decrypt | Complexity |
|---|---|---|---|
| Provider-managed encryption (SSE-S3) | The provider | The provider and whoever has permissions on the object | None |
| Customer-managed key in KMS | The provider holds it; you control the policy | Only whoever has permission to use the key | Low |
| Imported key (BYOK) | You generate it, the provider holds it | The same, but you can revoke it | Medium |
| A dedicated hardware security module | You, on dedicated hardware | Only you | High and expensive |
| Client-side encryption | Only you | Only you | Medium: the management is yours |
The difference between the first and the second option is the most important one to understand. With provider-managed encryption, anybody with read permission on the object gets it decrypted: the encryption is transparent. With a customer-managed key in KMS, two permissions are needed: reading the object and using the key. That makes it possible to separate duties — the storage administrator cannot read the data if they have no permission on the key — and, above all, to revoke access to all the data at once by disabling the key.
Rutalia already does something better than all of this for the nightly export, even if it did not know it: cifrar_clientes.py encrypts client-side with AES before uploading. The key (AES_KEY) never reaches AWS. That means neither AWS nor anybody with access to the bucket can read the content.
With two conditions Rutalia was not meeting and which have to be sorted out:
- The key was embedded in
config.pyand committed to Git. Fixed in 04-03, but because it was exposed it has to be rotated, and the existing exports re-encrypted. - If the key is lost, the data is unrecoverable. Client-side encryption moves the whole key management risk to Rutalia. Key custody is needed: a copy in the corporate password manager, an offline copy in a sealed envelope, and a documented procedure. A backup you cannot decrypt is not a backup.
- What each encryption option really protects
This is the table worth having clear before a conversation with senior management, because it is where there is most marketing:
| Threat | The provider's SSE | KMS with a customer key | Client-side encryption |
|---|---|---|---|
| Physical theft of a disk in the data centre | Yes | Yes | Yes |
| An accidentally public bucket | No | No, unless the key policy prevents it | Yes: the content is unreadable |
| Stolen Rutalia credentials with read permission | No | No, if they also have permission on the key | Yes |
| An employee of the provider with internal access | It depends on their controls | It depends | Yes |
| A court order served on the provider | The provider hands over the data decrypted | The provider can hand over decrypted data | Only an unreadable blob is handed over |
| Loss of the key on your side | Not applicable | Recoverable if the policy allows it | Data unrecoverable |
| A provider error | Partial protection | Partial protection | Yes |
The two rows that sum up the decision:
- Faced with a legal request to the provider, only client-side encryption guarantees that what is handed over is unreadable. It is a relevant argument in the data sovereignty debate of the next section, especially for data considered strategic.
- Encryption does not protect against badly set permissions, which is the number one cause of incidents. A public bucket with the provider's encryption at rest still hands the data over in the clear to whoever asks for the object. Encrypting does not replace configuring properly.
- Sovereignty, regions and international transfers
When Rutalia uploads the customer portfolio to eu-west-1 (Ireland), it is carrying out a processing of personal data that has specific legal implications.
The concepts:
| Concept | What it means |
|---|---|
| Region | The geographical location of the data centre. You choose it and the data does not leave it unless you configure it to |
| Data residency | Where the data is physically stored |
| Data sovereignty | Which jurisdiction it is subject to, which does not always match where it is |
| International transfer | Sending personal data outside the European Economic Area |
The distinction between residency and sovereignty is the hardest and the most important. A data centre in Ireland is in the EU and its data is subject to the GDPR. But if the provider is a United States company, there are rules in that country that may oblige it to hand over data under its control, wherever it is. Hence the large companies in the sector have developed "sovereign cloud" programmes operated by European entities, and hence too client-side encryption is a weighty argument.
What Rutalia has to decide and document:
| Question | Rutalia's answer |
|---|---|
| Which region is the data in? | eu-west-1 (Ireland), EU |
| Is there replication to another region? | No; if it is enabled, it has to be documented |
| Are there sub-processors outside the EEA? | The provider's list is consulted |
| Which mechanism covers the transfers? | Standard contractual clauses and the applicable adequacy framework |
| Is there a signed data processing agreement? | Yes, the provider's; it has to be read |
| What personal data is actually in the cloud? | The customer portfolio (professional contacts) + all the email |
| Could it be minimised? | Yes: the export does not need the contacts' identity document numbers |
The full legal development — lawful bases, the processing agreement, the record of activities and international transfers — belongs to 06-03. What belongs here is the technical decision: choose a European region, do not replicate outside it without a conscious decision, encrypt the most sensitive material client-side and minimise what you upload.
That last point is the most forgotten and the most effective: the safest way to protect a piece of data in the cloud is not to upload it. Rutalia's nightly export includes fields the purpose of the backup does not need.
- Provider certifications and what to ask before you sign
A serious provider publishes its certifications. The ones that matter in Spain:
| Certification | What it attests | Relevance for Rutalia |
|---|---|---|
| ENS (the Spanish National Security Framework) | Compliance with the Spanish framework, by level | Essential if Rutalia provides services to public administrations |
| ISO/IEC 27001 | A certified information security management system | The international reference standard |
| ISO/IEC 27017 and 27018 | Controls specific to the cloud and to personal data in the cloud | They complement 27001 |
| SOC 2 Type II | An audit report on controls over a period | Very informative: Type II measures effectiveness over time, not just design |
| ISO 22301 | Business continuity | Relevant to the assets' RTO |
A nuance worth understanding: a certification attests to the scope it declares, not to everything the company does. You have to read the statement of applicability and check that the service you are about to buy is within the certified scope.
The questions Laura asks before buying any cloud service — and which are the entry point to 06-04:
- In which region is the data stored, and are there replicas outside the EEA?
- Who are your sub-processors and where are they?
- Which certifications do you hold and what exactly is their scope? Will you give me the SOC 2 report?
- How do my administrators authenticate? Do you support MFA and federation with my identity provider?
- Which audit logs do you give me, in what detail and for how long do you keep them?
- Can I encrypt with my own keys? Can I revoke them?
- What is your breach notification commitment and within what timeframe?
- How do I get all my data back if I leave, in what format and how quickly?
- What availability guarantees are there and what compensation, if any?
- Can I audit you or require an independent audit report?
Question 8 is the one almost nobody asks and the one that costs most later. A service you cannot extract your data from is a permanent dependency.
- Containers and serverless, at an introductory level
Two models that inevitably turn up when working in the cloud. The essentials, on top of what we already saw in 04-01:
Containers. The three control points:
| Point | Risk | Control |
|---|---|---|
| The image | Vulnerable libraries, malware, embedded secrets | Minimal images, scanning, a pinned tag (never :latest) |
| The registry | A public registry or one with no access control | A private registry, with authentication and scanning |
| Execution | A container running as root, privileged, mounting the Docker socket | An unprivileged USER, --cap-drop=ALL, no --privileged |
And the most repeated mistake: secrets inside the image. An image is a set of layers; a secret added in one layer is still there even if a later layer deletes the file. Secrets are injected at run time, through environment variables or a secrets manager, never in the Dockerfile.
Serverless. Functions that run on demand with no servers to manage. What changes:
| Advantage | New risk |
|---|---|
| There is no operating system to patch | The function's role usually has excessive permissions |
| Minimal surface | The function's dependencies are still yours |
| Automatic scaling | An invocation loop can cost a lot of money |
| Ephemeral lifetime | Hard to investigate: there is no machine to examine |
The main rule is the same as ever: one function, one role, minimum permissions. The typical mistake is reusing one broad role for twenty functions, so that compromising the silliest of them gives access to everything.
- CSPM and how to start without spending
CSPM (Cloud Security Posture Management) is the category of tools that continuously check your cloud's configuration against a catalogue of good practice and tell you what is wrong.
| Option | Cost | What it gives you |
|---|---|---|
| Manual checks with the CLI | €0 | What this lesson covers: enough to get started |
| Free configuration analysis tools | €0 | Hundreds of automated checks, a report in HTML |
| The provider's own services | Low | Built-in recommendations and a score |
| A commercial CSPM | High | Multi-cloud, correlation, continuous compliance |
For Rutalia, the recommendation is to start with the first two rows. A free configuration analysis tool runs hundreds of checks — including every one in this lesson — with a single command and a read-only user:
# Create an audit user with READ-ONLY permissions
aws iam create-user --user-name security-audit
aws iam attach-user-policy --user-name security-audit \
--policy-arn arn:aws:iam::aws:policy/SecurityAudit
aws iam attach-user-policy --user-name security-audit \
--policy-arn arn:aws:iam::aws:policy/job-function/ViewOnlyAccessThe SecurityAudit and ViewOnlyAccess managed policies are read-only: the tool can examine everything and change nothing. It is the correct configuration for any audit, and the same principle we applied to the scripts of 04-01 and 04-02.
And the hygiene rule that makes this work: run it monthly and compare with the previous month. What matters is not the snapshot, it is the drift. A public resource that appeared this month is more urgent than one that has been there for two years and has already been assessed.
- A 12-point checklist for Rutalia
| # | Check | How | Status today |
|---|---|---|---|
| 1 | Root account with MFA and no access keys | get-account-summary |
✗ No MFA |
| 2 | MFA on every identity with write permissions | The credential report | ✗ |
| 3 | No public bucket without documented justification | get-bucket-policy-status + account-level block |
✗ Two findings |
| 4 | No policy with "Action": "*" on "Resource": "*" |
A review of the attached policies | ✗ rutalia-backup |
| 5 | No access key older than 90 days or unused | auditar_claves_aws.py |
✗ Three keys |
| 6 | CloudTrail enabled in all regions, with integrity and 1 year | describe-trails |
✗ Only eu-west-1 |
| 7 | Data events enabled on the backup bucket | get-event-selectors |
✗ |
| 8 | No security group with 22/3389/5432 on 0.0.0.0/0 |
describe-security-groups |
✗ One instance |
| 9 | No snapshot or image shared publicly | describe-snapshot-attribute |
✓ |
| 10 | Encryption at rest enabled on every bucket and volume | get-bucket-encryption |
✗ One unencrypted |
| 11 | M365: legacy authentication blocked and no automatic external forwarding | Conditional access + the rules script | ✗ Both |
| 12 | M365: no anonymous sharing links | Get-SPOTenant + audit |
✗ |
Ten out of twelve in red. The good news: eight of them can be fixed in under a day and cost no money. Laura's plan for the first week of June 2027:
| Day | Actions |
|---|---|
| 1 | MFA on the root account (physical key); delete its keys if it has any; account-level block public access |
| 2 | A new least-privilege policy for rutalia-backup; rotate its key; delete the three unused keys |
| 3 | CloudTrail in every region with integrity validation; data events on the backup bucket; the ten alert rules |
| 4 | Block legacy authentication in M365; MFA for administrators; block automatic external forwarding |
| 5 | Close the security group; encrypt the outstanding bucket; review rutalia-pruebas-2024 and delete it; plant the fake key canary |
Common Mistakes and Tips
Mistake 1: believing that the provider handles security. They handle theirs. The configuration, the identities, the permissions and the data are yours in all three service models. Tip: put it in writing and go through the table in section 4 with every new service you buy.
Mistake 2: using long-lived access keys when there is an alternative. A key that never expires ends up on a laptop, in a repository or in an email. Tip: roles whenever possible; when that is not possible, a restrictive policy with an IP condition, 90-day rotation and automated auditing.
Mistake 3: "Action": "*" to stop it failing. It is always temporary and it always stays. Tip: start by denying everything and add specific permissions based on the errors; the CloudTrail log says exactly which permission is missing.
Mistake 4: enabling CloudTrail in only one region. An attacker creates resources in a region you do not use precisely because you do not look at it. Tip: all regions, always, with integrity validation and in a bucket that cannot be deleted.
Mistake 5: assuming that encryption at rest protects against a public bucket. It does not: the service decrypts transparently for whoever has read permission. Tip: encryption protects against theft of the media; permissions protect against access.
Mistake 6: forgetting backups of a SaaS. The provider guarantees its availability, not your deletions. Tip: check Microsoft 365's real retention against your RPO and decide whether you need an additional backup (05-05).
Mistake 7: leaving test resources with real data. rutalia-pruebas-2024 is the cloud version of the 9 test VMs. Tip: anonymise the data in non-production environments, and tag every resource with an owner and an expiry date.
Mistake 8: blocking countries and thinking you are done. It is noise reduction, not a barrier. Tip: use it as one more signal in conditional access, never as the main control.
Tip 9: tag everything from day one. Owner, environment, criticality and review date on every resource. Without tags, in two years nobody knows what anything is or who can switch it off, and that is exactly how forgotten resources are born.
Tip 10: build guardrails, not just rules. An explicit organisation-level Deny on PutBucketPolicy stops anybody making a bucket public, even by mistake. It is worth more than ten pages of written policy.
Tip 11: measure the drift, not the snapshot. Run the audit monthly and compare. What is new is what is urgent.
Tip 12: the best protection for a piece of data in the cloud is not to upload it. Before designing the encryption, ask whether that field needs to be there.
Exercises
Exercise 1: fixing an IAM policy
Marta needs a new MiRutalia function to be able to generate temporary download links for the delivery notes stored in the rutalia-albaranes bucket. She proposes this policy:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:*", "kms:*", "iam:PassRole"],
"Resource": "*"
}]
}a) List all the problems with this policy, ordered by severity.
b) What could an attacker who obtained these credentials do? Give three concrete examples and order them by impact.
c) Rewrite the policy applying least privilege, commenting on each element.
d) The function will run on srv-web01 itself, in the Zaragoza data centre. What credential mechanism do you propose and why?
Exercise 2: interpreting CloudTrail events
This sequence appears in CloudTrail on Sunday 15 August 2027:
03:11:04 ConsoleLogin userIdentity=Root sourceIP=198.51.100.88 MFAUsed=No responseElements=Success 03:12:39 CreateUser userName=svc-monitor-aws sourceIP=198.51.100.88 03:12:51 AttachUserPolicy userName=svc-monitor-aws policyArn=...AdministratorAccess 03:13:02 CreateAccessKey userName=svc-monitor-aws sourceIP=198.51.100.88 03:21:17 StopLogging name=rutalia-trail sourceIP=198.51.100.88 03:44:52 DeletePublicAccessBlock bucket=rutalia-backups-clientes sourceIP=192.0.2.66 03:45:30 PutBucketPolicy bucket=rutalia-backups-clientes sourceIP=192.0.2.66 04:02:11 GetObject bucket=rutalia-backups-clientes key=clientes-2027-08-14.enc bytesOut=151203344
a) Reconstruct the attack step by step, explaining the purpose of each action. b) Which is the most serious event and why? And which is the most revealing about the attacker's level? c) There is a striking detail between the events at 03:21 and 03:44. Identify it and explain what it means. d) Which controls from this lesson would have prevented or detected each phase? e) The downloaded file is encrypted client-side. Is this a serious incident? Reason your answer.
Exercise 3: deciding on the ERP migration
Andrés Vidal has received three offers to resolve the problem of srv-erp01, which has been without vendor support for four years:
| Offer | Description | Annual cost |
|---|---|---|
| A | Move the virtual machine as it is to a cloud instance | €4,200 |
| B | Buy the cloud version of the same ERP, managed by the vendor | €18,000 |
| C | Replace it with another ERP as a service, with data migration | €26,000 the first year, €19,000 thereafter |
a) Assess each offer from the point of view of the shared responsibility model: which responsibilities move and which stay. b) Which of the three makes Rutalia's security posture worse, and why? c) With the information available, which do you recommend? Justify it with at least three technical arguments. d) Whichever is chosen, give five controls that must be applied anyway. e) Write three questions you would ask the provider of the chosen option before signing.
Solutions
Solution 1
a) The problems, from most to least serious:
"Action": ["iam:*"]with"Resource": "*": by far the most serious. It allows users to be created, the administrator policy to be attached and access keys to be created. That is: these credentials can become a full administrator of the account in two API calls. Every other restriction in the policy is irrelevant while this is there."iam:PassRole"with no restriction: it allows any role in the account to be assigned to a new service. It is a classic and little-known privilege escalation route: even withoutiam:*, unrestrictedPassRolelets you launch an instance with an administrator role and act from there."kms:*"on"*": it allows anything encrypted in the account to be decrypted and, worse, key deletion to be scheduled, which would irreversibly destroy all the data encrypted with them."s3:*"on"*": full access to every bucket, not justrutalia-albaranes. That includesrutalia-backups-clienteswith the whole portfolio, and alsos3:DeleteObjectands3:PutBucketPolicy."Resource": "*"throughout: with no scoping at all.- No
Conditionanywhere: it can be used from any IP, without encryption, without MFA. - No guardrail
Deny: nothing stops a future change widening the permissions still further. - It is missing what is actually needed: to generate temporary download links, all you need is
s3:GetObject.
b) Three attacker actions, by impact:
- Persistence and takeover of the account (maximum impact):
iam:CreateUser+iam:AttachUserPolicywith the administrator policy +iam:CreateAccessKey. The attacker obtains permanent access independent of the stolen credentials. Even if Rutalia rotates the original key, they are still inside. It is exactly the sequence in exercise 2. - Exfiltration of the customer portfolio (very high impact):
s3:GetObjectonrutalia-backups-clientes. All 400 customers and their history. It realises H3. - Irreversible destruction (maximum impact, of a different kind):
kms:ScheduleKeyDeletionon the encryption keys, pluss3:DeleteObjecton the backups. The data encrypted with those keys becomes unrecoverable for ever, even for AWS. It is a destruction scenario worse than ransomware, because there is no key to pay for.
c) The corrected policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadDeliveryNotesForPresignedUrl",
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::rutalia-albaranes/albaranes/*",
"Condition": {
"Bool": { "aws:SecureTransport": "true" }
}
},
{
"Sid": "DecryptWithTheDeliveryNoteKey",
"Effect": "Allow",
"Action": ["kms:Decrypt"],
"Resource": "arn:aws:kms:eu-west-1:123456789012:key/ALBARANES-KEY-ID",
"Condition": {
"StringEquals": { "kms:ViaService": "s3.eu-west-1.amazonaws.com" }
}
},
{
"Sid": "PermanentGuardrail",
"Effect": "Deny",
"Action": [
"iam:*", "sts:AssumeRole",
"kms:ScheduleKeyDeletion", "kms:DisableKey", "kms:PutKeyPolicy",
"s3:DeleteObject", "s3:DeleteObjectVersion",
"s3:PutBucketPolicy", "s3:PutBucketAcl", "s3:DeletePublicAccessBlock",
"cloudtrail:StopLogging", "cloudtrail:DeleteTrail"
],
"Resource": "*"
}
]
}A comment on each element:
s3:GetObjectonly, and on a specific prefix inside a specific bucket. It neither writes, nor deletes, nor lists other buckets. Generating a temporary download link is an operation done with the local signing of the credentials: it requires no additional API permission.kms:Decrypton a single key, withkms:ViaServiceso that it can only be used through S3. If the delivery notes are encrypted with S3's managed key, this statement is not even needed.aws:SecureTransport: true: over HTTPS only.- The
Denystatement is the most valuable in the long run: by the precedence rule, it prevails over anyAllowanybody adds in future. It explicitly blocks the four families of actions that turn a read permission into a total compromise: escalation through IAM, destruction of keys, deletion of objects and switching off the audit trail. - What is NOT there:
iam:*,PassRole,kms:*ands3:*. The difference between this policy and the original is the difference between being able to read a few PDFs and owning the infrastructure.
d) Because srv-web01 is in the Zaragoza data centre and not in AWS, it cannot use an instance role. A two-stage proposal:
In the short term (this week): an access key dedicated exclusively to this function — not reusing rutalia-backup's — with the policy above plus an aws:SourceIp condition limited to 203.0.113.10/32, automatic rotation every 90 days and storage in the systemd EnvironmentFile with 600 permissions, like MiRutalia's secrets in 04-03.
In the medium term (this quarter): certificate-based federation, so that srv-web01 presents the certificate from the internal PKI of 02-05 and obtains one-hour temporary credentials. The advantages: there is no permanent key to steal, rotation is automatic, every credential issuance is logged, and the certificate is revoked instantly if the machine is compromised.
And in both cases, a design decision that reduces the problem: one identity per function. The delivery note function must not share credentials with the nightly backup process, even though both live on the same machine. If one is compromised, the other remains intact.
Solution 2
a) Reconstruction of the attack:
| Time | Action | Purpose |
|---|---|---|
| 03:11 | Root account sign-in without MFA from 198.51.100.88 |
The attacker has the root password. Probably from claves.xlsx, or from the former IT manager's personal email. With root, they already have everything |
| 03:12 | Creates the user svc-monitor-aws |
A name chosen to look like a legitimate service account: masquerading, just like the OfficeTelemetryAgent of 04-02 |
| 03:12 | Attaches the administrator policy to it | The new user can do everything |
| 03:13 | Creates an access key for it | Persistence: permanent API access, independent of the root password. Even if Rutalia changes the password, they are still inside |
| 03:21 | StopLogging on CloudTrail |
Erasing tracks: from here on there will be no log |
| 03:44 | DeletePublicAccessBlock on the backup bucket |
Preparing public access to the bucket |
| 03:45 | PutBucketPolicy |
Makes the bucket reachable |
| 04:02 | GetObject of 151 MB |
Exfiltration of the entire customer portfolio |
b) The most serious is the root ConsoleLogin without MFA at 03:11. Everything else follows from it: with the root account, the attacker owns the infrastructure and no later control can stop them. It is the failure of control 1 in the checklist.
The most revealing about the attacker's level is the StopLogging at 03:21. It shows they know exactly what CloudTrail is, where it is and why it is in their way. This is not an automated scan: it is somebody who understands AWS and who is thinking about leaving no trace, just like whoever clears the Windows logs. And, with a touch of irony, it is the action that gives them away most: StopLogging itself is logged before the logging stops.
In second place, creating the service-named user in the first minute shows that their priority is persistence before the objective, which is the behaviour of an experienced attacker.
c) The striking detail is the change of IP address: the actions up to 03:21 come from 198.51.100.88, and from 03:44 onwards they come from 192.0.2.66.
What it means:
- The new credentials are in use. The actions from
192.0.2.66are performed with the access key created at 03:13, from another machine. The attacker has handed the baton from the console session to the API credentials. 192.0.2.66is the IP of the attacker from the canonical scenario in 01-04, the same one as the beaconing, the same one as thecertutildownload in the exercise in 04-02. It is the same actor, or at least the same infrastructure. That turns this incident from "somebody has got into our AWS" into "the intrusion we have been watching for months has spread to the cloud", and completely changes the scope of the investigation.- It may indicate two people or two phases: whoever has the root password (perhaps obtained from
claves.xlsx, that is, from inside) and whoever operates the attack infrastructure. It is a common pattern in organised crime, where initial access and its exploitation are sold and bought by different actors.
And a fourth important detail: there are 23 minutes of silence between 03:21 and 03:44. That suggests the attacker stopped the logging, waited to see whether any alarm went off, and only then carried on. It is a deliberate check that nobody is watching.
d) Controls by phase:
| Phase | Preventive control | Detective control |
|---|---|---|
| Root sign-in | MFA with a physical key (control 1): it would have prevented it completely | An alert on any root ConsoleLogin (rule 1) |
| User and policy creation | An organisation policy denying iam:* except to one specific role |
An alert on CreateUser/AttachUserPolicy (rule 6) |
| Key creation | The same | An alert on CreateAccessKey (rule 6) |
StopLogging |
An organisation policy denying it to everybody, root included | An alert on StopLogging (rule 5): the most valuable of all |
DeletePublicAccessBlock |
Account-level block public access, which takes precedence over the bucket's | An alert (rule 4) |
PutBucketPolicy |
A guardrail Deny in the organisation policy |
An alert (rule 4) |
GetObject |
A bucket policy allowing reads only to the restore role | An alert on any GetObject in that bucket (rule 3) |
The StopLogging row is worth underlining: organisation-level policy mechanisms exist that not even the root account of a member account can bypass. It is the ultimate guardrail, and it is free.
e) Yes, it is a serious incident, and you have to resist the temptation to play it down because the file is encrypted. The reasons:
- The encryption protects that file, not the account. The attacker has an administrator user with their own access key. They can create instances, read other buckets, delete the backups, alter the infrastructure and make Rutalia pay the bill. The download is a symptom, not the problem.
- The AES key may have been exposed.
AES_KEYwas embedded inconfig.pyand committed to Git for years. If the attacker has had access to MiRutalia's repository — and it is the same actor who was inside — they have the key. You have to assume the file is readable unless proven otherwise. The rotation in 04-03 protects future exports, not earlier ones. - Even if the key is safe today, the data is still out there. A patient attacker keeps the file and waits for the key to leak or the algorithm to age. For data with long-term value, "encrypted" means "for now".
- It is a personal data breach that has to be assessed under 06-03. Strong encryption with an uncompromised key is a solid argument for concluding that there is no high risk to the data subjects; but it is a conclusion that has to be documented with evidence, not assumed.
- There are 23 minutes with no logging and an unknown administrator user. What you cannot see is what worries you most: we do not know what they did between 03:21 and 03:44.
Conclusion: the incident response process (05-02) is triggered at maximum priority. Immediate actions: disable svc-monitor-aws's keys and delete the user after preserving the evidence, change the root password and enable MFA on it, re-enable CloudTrail, restore block public access, rotate every credential in the account, and — very importantly — investigate how they obtained the root password, which is the question that decides whether the problem is solved or merely covered up.
Solution 3
a) Assessment from the shared responsibility model:
Offer A - IaaS, lift and shift (€4,200).
| Moves to the provider | Stays with Rutalia |
|---|---|
| Physical security, power, hardware | An unsupported, unpatched operating system |
| Availability of the infrastructure | An application with no vendor support |
| Physical network | Virtual network configuration, firewalling, access |
| Backups, identities, data, compliance |
What moves is what Rutalia had already reasonably solved (the data centre works) and what is kept intact is what the problem actually is: an unsupported system. And a new responsibility is added: correctly configuring a virtual network and a set of cloud permissions, a discipline the team has no experience in yet.
Offer B - SaaS from the same vendor (€18,000).
| Moves | Stays |
|---|---|
| Operating system, engine, patches, updates | Identities and permissions |
| Availability and platform backups | Configuration of the service |
| The support problem disappears | Data and its classification |
| Integration with Active Directory and with MiRutalia | |
| Supplier risk (06-04) |
Offer C - SaaS from another vendor (€26,000 / €19,000). The same as B, plus: data migration — with its own leak and loss risk —, training for 180 people, and a period with both systems running side by side.
b) Offer A makes Rutalia's security posture worse. Four specific reasons:
- It does not solve the root cause. The system is still unsupported and unpatched. It is the literal definition of moving the problem.
- It loses the mitigations that already work. The current isolation of
srv-erp01— VLAN 20, no internet egress,fw-zgz01rules, Suricata signatures onsec-sensor01— is the fruit of the work in 03-04 and it is tested. In the cloud it all has to be rebuilt from scratch, with a team with no experience and a very real possibility of a badly set security group. - It increases the exposure. An unpatched system in the data centre requires the attacker to get into Rutalia's network first. The same system in the cloud is one configuration away from being reachable from the internet. And the ERP supplier's access (
198.51.100.77, hypothesis H5) has to be redesigned too. - It adds a dependency without resolving any. Now there is one more cloud account to manage, with its identities, its audit log and its billing.
It is also the option senior management finds most attractive because of the price, and that is why it has to be argued properly: €4,200 to remain just as exposed but with more surface to watch.
c) Recommendation: offer B, with the caveats in part e). The technical arguments:
- It removes the root cause at the lowest real cost. The risk Rutalia has formally accepted since 15 January — a critical system (asset A002, RTO 8 h / RPO 4 h) with no patches — disappears. The vendor becomes responsible for patching and updates, and that is contractually enforceable.
- It resolves hypothesis H5 at the same time. The ERP supplier's permanent access to Rutalia's internal network ceases to exist: there is no longer an internal machine to reach. One of the five hypotheses in the threat model is eliminated, not mitigated.
- It is the option with the lowest project risk. The same application, the same data, the same processes, the same training. Option C triples the cost in the first year and adds the risk of a functional migration, the resistance to change of 180 people and a period of dual running. That project risk is real and usually underestimated.
- It is affordable and reversible. €18,000 against C's €26,000. If in two years the vendor does not deliver, you rethink it with real service data and without having spent three years' budget.
When the recommendation would change to C: if the vendor would not give availability commitments in writing, if their roadmap indicated the product was going to be discontinued, or if they could not evidence certifications and audit logging. In that case, paying to stay tied to a vendor that has already shown it will abandon the product would be repeating the mistake.
d) Five controls that apply in any of the three options:
- Mandatory MFA and federation with Active Directory. Nobody reaches the ERP with a loose password, and staff departures are reflected automatically (02-03).
- Least privilege and a quarterly permissions review, using the role×asset matrix of 02-02. The
proveedor_erprole stops being permanent access and becomes on-demand access, with a window and an approval. - Exportable audit logging retained for 12 months, integrated with the rest of Rutalia's logs. Without this there is no way to investigate anything, and in a SaaS there is no machine to examine.
- Your own backup and a periodic export of the data, independent of the provider. It covers both accidental deletion and the provider disappearing. It is the control most often forgotten in SaaS.
- A signed data processing agreement, with the obligations on breach notification, sub-processors, data location and return on termination (06-03 and 06-04).
And a sixth that only applies to A, and which on its own calls that option into question: rebuilding in full the network isolation that protects srv-erp01 today, including the absence of internet egress and the specific detection signatures.
e) Three questions for the provider of option B:
-
"How do I get all my data back if I decide to leave, in what format, how quickly and at what cost? And what happens to it if you cease trading or discontinue the product?" It is the most important question and the one almost nobody asks. Rutalia has already lived through this product being abandoned once: it cannot afford to be trapped again, this time with the data in somebody else's house.
-
"Which audit logs do you give me, at what level of detail, in what format and for how long do you keep them? Can I export them automatically to my own store?" Without logs there is no detection and no investigation, and in a SaaS Rutalia cannot build its own. If the answer is "a PDF report on request", that is a negative answer.
-
"What is your commitment on security incident notification and within what timeframe? Do you also notify me of incidents that do not affect me directly? Which certifications do you hold, with what scope, and will you give me the audit report?" The GDPR requires Rutalia to notify within 72 hours of becoming aware; if the provider takes two weeks to tell them, Rutalia is in breach because of a third party.
Additional questions worth including: where the data is stored and which sub-processors are involved; whether they support identity federation and MFA; what availability guarantees they offer against the 8-hour RTO of asset A002; and whether the service can be trialled with anonymised data before signing.
Conclusion
You have understood what genuinely changes when you take systems out of the data centre, and you have demolished the two opposing myths: the cloud is not inherently insecure, and nobody takes care of your security for you either. You know that the perimeter becomes identity, that a misconfiguration which in the data centre affects one machine can expose everything to the internet in one click, and that the sentence which orders everything else is that you can outsource the execution, never the responsibility.
You have mastered the shared responsibility model with its concrete split by service model, and you can identify the four rows that never change owner — configuration, identities, data and who has access — and the fifth that is always forgotten: backups of a SaaS. You have applied it to Rutalia's three real cases, including the analysis of why moving an unsupported virtual machine to the cloud makes the security posture worse rather than better.
You know why clouds fail — configuration and credentials, almost never the provider — and you have the concrete checks: get-public-access-block with its four settings and what each one means, get-bucket-policy-status as a reliable verdict, and a sweep of the whole account that in five seconds found a public bucket with an internal catalogue and a forgotten 2024 bucket with real customer data.
You have written a least-privilege IAM policy understanding every piece: a single action, a resource pattern instead of a wildcard, encryption and source-IP conditions that turn stolen credentials into a useless keyring, kms:ViaService to scope the use of the key, and Deny statements as guardrails that prevail over any present or future Allow. And you know that two lines of that policy would have turned a 141 MB leak into a simple AccessDenied.
You know the difference between roles and long-lived keys, you know that there is almost always an alternative to a permanent key and what it is in each case, and you have solved Rutalia's awkward case: a server outside the cloud, with an IP-restricted key in the short term and certificate federation in the medium term. You have handled the finding of the key on Marta's laptop with the correct procedure — check the last use, create the new one, deactivate before deleting, and find out where else it is —, you have a script that audits the age and the use of every key in the account, and you have planted a fake key canary that fires on the first GetCallerIdentity and hands you the attacker's IP.
You know how to protect the root account — MFA with a physical key, a corporate mailbox, no access keys, an alert on any sign-in — and you have configured CloudTrail as it should be: all regions, integrity validation, a destination the attacker cannot delete, and data events enabled on the bucket that matters, because by default who downloads the objects is not logged. You have read a CloudTrail event field by field and found five independent anomalies in a single JSON document. And you have ten detection rules, with the most valuable of all: the alert on StopLogging, because the very attempt to erase the tracks is the proof.
You have taken the segmentation of 03-04 into the cloud with security groups that reference each other instead of IP ranges, you know how to look for administration ports open to 0.0.0.0/0 and you know the quiet leak route of snapshots and images shared publicly.
In Microsoft 365 you have seven prioritised conditional access policies, starting with the one almost nobody applies and which matters most: blocking legacy authentication, which is the gap through which mailbox compromises slip and the vector of H2. You know how to detect automatic forwarding rules in the two places where they are configured, how to recognise the concealment pattern — an invisible name, local deletion, a move to deleted items — and how to close the technique off at the root by blocking external forwarding at organisation level. And you have closed down external file sharing by changing the defaults, which is what decides the behaviour of 90% of users.
You understand encryption in the cloud in its three layers and the five key management options, with the honest table of what each one really protects against which threat: that the provider's encryption at rest does not protect against a public bucket, that a customer-managed key lets you revoke access to everything at once, and that only client-side encryption makes a legal request to the provider hand over an unreadable file — at the price of the loss of the key being irreversible. You know how to distinguish residency from sovereignty, what to ask about regions and transfers, what the ENS, ISO 27001 and a SOC 2 Type II really attest to, and you have ten questions to ask before signing, including the one almost nobody asks: how you get your data back if you leave.
And you take away a twelve-point checklist of which ten are currently in red, with the good news that eight can be fixed in under a day and without spending a euro.
You have protected the path, the endpoints, the application and the cloud. On paper, Rutalia is in a radically different position from six months ago. But there is a question none of the four previous lessons has answered, and it is the only one that really matters: does it work?
You do not know. You know the rules are written, the policies are applied and the scripts show green. You do not know whether a real attacker, probing for a week, would find a route you have not considered. You do not know whether require_ownership() is in all forty views or in thirty-nine. You do not know whether one of the 151 uninventoried machines is left with a forgotten service. You do not know whether the IDOR fix holds up against a genuine attempt. And the only honest way to find out is to actively look for your own flaws, before somebody else does.
The last lesson of the module, Penetration Testing and Vulnerability Assessment, is about exactly that: what each kind of test answers and how a scan, a pentest and a red team exercise differ; the Spanish legal framework, where testing without written authorisation is an offence under articles 197 bis and 264 of the Criminal Code, and what the agreement that makes it lawful must contain; the methodologies and the phases of a real test; vulnerability management as a continuous process, which is what Rutalia needs most, with prioritisation that goes beyond CVSS; how you read a pentest report and turn it into a plan with owners and deadlines; and a legal, free lab in which to practise everything you have learned without committing an offence. It is time to check whether all this really works.
