PCI DSS and keeping card data out of scope
Every system that sees a card number joins the audit. Scan for where the numbers already are, draw the flows, then move the card to where your servers never receive it
Tallowmere's checkout page posts the card form to its own server. The server logs the request, forwards the card to the provider and keeps the number for the refill job. The team can make one change this quarter. Which one takes the most systems out of PCI scope?
Who makes you follow PCI DSS
The Payment Card Industry Data Security Standard, PCI DSS, is a security standard for card data. It is not a law and not a rule of the Central Bank of Nigeria. A merchant follows it because the contract with its acquirer, and the card networks’ rules behind that contract, say so. The PCI Security Standards Council (PCI SSC) publishes the standard. Search results show its document library listing PCI DSS v4.0.1 with a summary of changes from v4.0, and a Council blog post announcing the publication of v4.0.1. Those results and secondary sources say v4.0.1 was published in June 2024 as a limited revision that corrects formatting and typographical errors and clarifies intent without adding or removing requirements, that v4.0 was retired on 31 December 2024 (one vendor glossary says after 31 March 2025, which disagrees with the Council’s blog), and that the revision did not move the 31 March 2025 effective date of the new requirements. This build read search summaries, not the standard itselfas of 2026-11.
Per a secondary source quoting the standard, PCI DSS applies to every entity that stores, processes or transmits cardholder data, wherever it is. Search results quoting the Council’s self-assessment forms also say that, even when a merchant meets a form’s eligibility criteria, whether it may use that form is governed by the card networks’ rulesas of 2026-11. In practice your acquirer tells you what to report and how. A small merchant reports with a self-assessment questionnaire, an SAQ: a form whose length depends on how much of your system touches card data. This chapter is about moving from a long form to a short one by changing the system, which is the only honest way to get there.
What counts as card data
The standard separates two kinds of data. Cardholder data is the card number (the primary account number, or PAN), the cardholder’s name and the expiry date. Sensitive authentication data is what proves the card is in the customer’s hand: the card verification code (CVV or CVC, the three or four digits on the card) and other data of that kind. Secondary sources (vendor and consultant pages) summarising PCI DSS v4.0.1 say three things. Sensitive authentication data may be collected to authorise a payment but must not be kept after authorisation, even if encrypted (requirement 3.3.1 and, for the card verification code, 3.3.1.2; one source adds that issuers and issuing services with a documented business need are treated differently). A stored PAN must be rendered unreadable (requirement 3.5.1), with keyed cryptographic hashes dealt with in 3.5.1.1. And a PAN shown on a screen or a report must be masked (requirement 3.4.1); this build did not confirm how many digits may be shown, so check the standard for the exact limit. The requirement numbers come from secondary sources, and this build found no official text for any of themas of 2026-11.
Two consequences matter to an engineer. The security code is the worse thing to find in a log, because a business that is not a card issuer has no allowed reason to keep it after the payment is authorised. And “unreadable” does not mean “base64” or “reversible with a key that sits in the same config file”. The design question is not how to store a card number safely. It is why you hold one.
How scope is drawn
Scope is the set of systems the standard’s requirements apply to. Each system in scope needs firewall rules, patching, access control, logging, vulnerability scans and evidence for an assessor or for your own answers. The cost of a system in scope is therefore a recurring one, and it is paid for every system that the card number touches or can reach.
The Council’s information supplement Guidance for PCI DSS Scoping and Network Segmentation (version 1.0, December 2016; version 1.1, May 2017) is guidance, and search results say its own disclaimer is that following it guarantees neither effective segmentation nor compliance with PCI DSS. Secondary summaries describe three categories: systems that store, process or transmit cardholder data (the cardholder data environment, or CDE, together with systems on the same network segment); connected-to systems, which can reach the CDE from another network; and security-impacting systems, which provide security services to the CDE or affect its configuration. A system is out of scope only if it has no access to the CDE and no effect on its security. Sources differ on how far connected-to systems are in scope for every requirement, and one calls the categories a recommended practice rather than a mandatory structure. A further supplement, Scoping and Segmentation Guidance for Modern Network Architectures, dates from September 2024; search results say it adds nothing to and replaces nothing in the Council’s standards or earlier supplementsas of 2026-11.
Read that as an engineer. Scope follows data and access, not org charts. A server that receives the number is in. The database it writes to is in. The backup of that database is in. The support laptops that read the logs are in. The stock system that reads the orders table is connected to a system that is in. Each is one more thing to defend, and the number can leave any of them.
Segmentation, placing the card systems on a network of their own, can keep the stock system and the rider app out. It does not help the system that receives the number, and it has to be tested, not assumed. The better question comes first: can the number avoid arriving at all?
How card numbers get where you did not plan
Name what goes wrong before the fix. A card number arrives in a request. From there it spreads through habits, not through design.
- The request log. A debug line that prints the request body, added to chase one bug and never removed, copies the number, the expiry and the security code into a file. Web server access logs do not hold bodies, but a query string can: a form sent with GET puts the number in the URL.
- The error handler. On an exception, “log the request so we can reproduce it” writes the same body, this time with a stack trace, to a file that goes to an error tracker run by someone else.
- The database row. “So the nightly job can charge again” is the usual reason a number is stored. Tallowmere’s first refill job did it.
- The copies. Backups, replicas, exports for analysts, a copy of production in a staging database, files attached to a support ticket, a screenshot in a chat thread. Removing the number from the live table touches none of them.
- The side channels. Analytics tags and session-recording tools on a payment page can capture what is typed. Message queues and dead-letter queues keep the failed payloads for days.
The lab builds Tallowmere’s first checkout with the first three habits and the fourth as a backup copy, then finds them. Each of the habits is common because it is helpful on the day it is added.
Finding the numbers: a regex, then Luhn
You cannot scope what you have not found. The search has two stages.
First, a pattern: 13 to 19 digits in a row, with optional spaces or dashes between them, the lengths card numbers usually have. That matches card numbers and plenty else: order numbers, phone numbers, tracking codes, the digit runs inside hashes. Second, the check digit. The last digit of a card number is chosen so that the Luhn sum comes out as a multiple of 10. From the right, double every second digit (subtract 9 if the double has two digits), then add everything. A random string of digits passes about one time in ten, so the check removes about nine in ten look-alikes and keeps every real number that it sees.
Work one by hand, as the lab does in code. Take 4242424242420001, a number the lab’s own scenarios use. From the right the digits are 1, 0, 0, 0, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4. The digits in even positions (counting from 0) are 1, 0, 2, 2, 2, 2, 2, 2, which add to 13. The digits in odd positions are 0, 0, 4, 4, 4, 4, 4, 4. Doubled they are 0, 0, 8, 8, 8, 8, 8, 8, which add to 48. The total is 13 + 48 = 61, and 61 is not a multiple of 10. The number fails.
That failure matters more than the arithmetic. The lab’s test numbers, built so the mock provider can force an outcome from the last four digits, are not Luhn-valid. A scanner with a Luhn check is blind to them. A real card number would be seen, so the scanner is correct, but a scan that has never found anything has not been tested. The lab therefore plants a known number first, and then builds Luhn-valid test numbers by changing one digit of each lab number, which is the only way to prove the scanner works on the files you care about.
Know what the scan cannot see. It reads text. It will miss a number split across fields, URL-encoded or base64-encoded, inside a compressed backup, in an image of a card, or in a system you do not run, such as a hosted log service. A clean scan lowers your worry. It does not prove the absence. The scan also never prints a whole number: it shows the first six and last four digits, because the scan report must not become another copy.
Three ways to take a card
If the number never arrives, none of the habits above can copy it. A merchant’s website can take a card in three ways, and the PCI Council’s FAQs treat them differently.
| Design | Who serves the form | Where the browser sends the card | Your servers see the number? | SAQ it points to |
|---|---|---|---|---|
| Own form, card to your server | You | To your server, which forwards it | Yes | The long form, SAQ D |
| Direct post | You | From your page straight to the provider | No | SAQ A-EP |
| Hosted fields or iframe | The provider, in a frame on your page | Straight to the provider | No | SAQ A, if every criterion holds |
| Redirect to the provider’s page | The provider | Straight to the provider | No | SAQ A, if every criterion holds |
The Council’s FAQ 1291 page shows in search results with its question (why SAQ A-EP is used for direct post and SAQ A for iframe or URL redirect), but only secondary sources give the answer. They say that with direct post the merchant’s website produces some or all of the page that accepts payment data and passes it to the processor, while with a redirect or an iframe the provider supplies the page, which is why the forms differ. One assessor’s blog adds that the provider must itself be PCI DSS compliant for the reduction to hold. This build did not read the FAQ’s answeras of 2026-11. Secondary sources, mostly vendor and consultant blogs, describe the forms this way: SAQ A is for fully outsourced e-commerce, with only card-not-present payments and no electronic storage, processing or transmission of account data by the merchant; SAQ A-EP is for merchants whose website can affect the security of a payment although the card goes to the processor; SAQ D is the full questionnaire for merchants that fit no lighter form; and SAQ P2PE is for card-present merchants using a validated point-to-point encryption solution. One source says a server that touches card data, even to forward it, means SAQ D. This build read none of the forms themselvesas of 2026-11.
Search results give two further pieces of Council material. A Council blog post (important updates for merchants validating to SAQ A) is summarised as saying that requirements 6.4.3 and 11.6.1, about payment-page scripts, were removed from SAQ A in January 2025 and replaced by an eligibility criterion, while staying in the standard itself; this build did not read the criterion’s wording, and secondary posts attribute detail on it to an FAQ 1588 whose page this build did not find. The official FAQ 1604 page shows in search results and says that merchants with e-commerce pages that complete SAQ A, even where payment processing is outsourced, still answer for the requirements in SAQ A, including ASV scanning (scans by an approved scanning vendor). A Council resource guide, as summarised, limits that to the merchant systems that host the page redirecting to the provider or embedding its form, and FAQ 1439 says a merchant that has outsourced all operations, including management of its website, may have no systems in scope for those requirementsas of 2026-11. Sources differ on the wording of the script criterion. Treat the table as the shape of the decision and your acquirer’s reading of the form as the answer.
The choice between an iframe and a redirect is a business trade-off. A redirect hands the whole page to the provider, which leaves you the least to defend and the least control of the experience. Hosted fields keep your page and its look, and make you answerable for the page and its scripts. A direct post keeps the most control and the most duty.
What the redesign does not remove
The redesign puts the card number out of reach of your servers. It leaves five things behind.
- The page. In hosted fields or a direct post the page that carries the payment form is yours. A script injected into it, from an analytics tag or a compromised library, can read what a customer types before the provider’s field receives it. Search results tie the newer script criterion to exactly this risk.
- The scans. External vulnerability scans by an approved scanning vendor continue for the systems that host your payment page, according to FAQ 1604 as it shows in search results.
- The provider’s own compliance. You must be able to show that the provider is compliant, and the contract should say who tells whom if the provider has a breach.
- The token and the key. A provider token is not a card number, but in the lab’s mock, anyone holding the API key can charge a saved token for its customer. The key becomes the secret to guard, and the token table becomes data that deserves a restricted role. See the chapter on tokenisation for what a token does and does not allow.
- The answer to the questionnaire. Scope is a decision your acquirer reviews, not one you declare.
Scope also comes back by accident, and the lab shows how. A fallback form, an analytics tag or a mis-bound field that sends the card to your server again puts the number back into a log, even if the server never uses it. Scope depends on what arrives, not on what the code does with it.
Where the CBN fits
Tallowmere is a pharmacy and not a licensed financial institution, so its PCI duty is the contractual one above. A Nigerian payments company also answers to its regulator. Search results show the CBN’s Risk-Based Cybersecurity Framework and Guidelines for Deposit Money Banks and Payment Service Banks (2024) on the CBN’s site. Digital-policy and law-firm summaries say its final version was issued on 31 May 2024 for implementation by 1 July 2024, that it replaces the framework of October 2018 for deposit money banks and payment service providers, and that it lists PCI DSS among the standards a third-party service provider must meet, according to the services it offers. This build did not read the document, and the summaries do not say what replaced the 2018 text for payment companies that are not banksas of 2026-11. A law-firm summary says the CBN issued a separate Risk-Based Cybersecurity Framework and Guidelines for Other Financial Institutions on 29 June 2022, with full compliance expected by 1 January 2023, covering institutions such as discount houses, bureaux de change, credit bureaux and finance companies. The search returned no copy on the CBN’s own site, and no source that says whether a given payments licence falls under itas of 2026-11. The honest reading is that a payments company should ask its regulator which framework applies to its licence, and treat PCI DSS as a separate, contractual standard that the CBN documents may point to. A chapter on licences later in this module covers what each licence allows.
Where to start
A scoping review is five steps in this order. List the places a card number is, by scanning and by asking. Draw the flows that carry it. Decide whether it can stop arriving. Prove the fix with a scan that has been shown to work. Then take the evidence to the acquirer and ask which form applies. Oghenekaro owns the last step. Feyisara owns the first four, and the order matters: the questionnaire is easy to answer once the system is simple, and hard to answer well before.
Lab
You work in labs/finance with the files from the module 2 project in it: ledger.py, wallet.py, reconcile.py and scenarios.py. Those are Owoleaf’s wallet, and here they stand in for Tallowmere’s checkout service. Every card number in the lab is a test number. The mock provider keeps only the last four digits of a card, and the wallet never writes the number to its own database, so the first scan, run on your project as it stands, should find nothing. Then you add a checkout in front of the wallet, written the way small teams write a first version, and scan again. Ports are the defaults: the provider on 8101, the switch on 8102, the wallet’s receiver on 9000 and the checkout on 8080. The numbers below come from my run. The counts of card numbers are fixed by what the lab sends, so yours should match them. Run the steps in order, because each builds on the files and the mock state left by the one before.
1. Start the mocks, with their logs in files. Everything the mocks print to the terminal goes to logs/, because logs are where card numbers hide.
cd labs/finance
mkdir -p logs
python3 mock_provider.py --fresh --webhook-url http://127.0.0.1:9000/provider > logs/provider.log 2>&1 & echo $! > logs/provider.pid
python3 mock_switch.py --fresh --callback-url http://127.0.0.1:9000/switch > logs/switch.log 2>&1 & echo $! > logs/switch.pid
sleep 1; cat logs/provider.log logs/switch.logmock_provider on http://127.0.0.1:8101 secret sk_test_owoleaf_mock webhooks -> http://127.0.0.1:9000/provider
mock_switch on http://127.0.0.1:8102 institution P01 key sw_test_owoleaf_mock callbacks -> http://127.0.0.1:9000/switchThe two programs keep running in the background, and their process ids are in logs/. The provider keeps its state in data/provider.sqlite and the switch in data/switch.sqlite. Both are SQLite files that the scan will read.
2. Run the module 2 scenarios. This produces the logs and databases a team would have after a day of testing.
python3 scenarios.py > logs/scenarios.log 2>&1
tail -3 logs/scenarios.log repaired by this run: 1 late reversal applied
unexplained breaks: 0
payout S-REVERSE is now reversed and S-TIMEOUT is settledAbout 80 seconds. The scenarios send card payments with the lab’s test cards through the wallet, as in the module 2 lab.
3. Write the scanner and prove it can see. Save this as pan_scan.py. It reads text files line by line and every text cell of every table in a SQLite file. It finds digit runs of 13 to 19 digits, applies the Luhn check, and prints only the first six and last four digits when it prints a number at all.
"""Find card numbers in files and SQLite databases: a regex for 13-19 digits, then the Luhn check.
Prints only the first six and last four digits of a hit, never the whole number."""
import os
import re
import sqlite3
import sys
from collections import Counter
CANDIDATE = re.compile(r"(?<![\d.])(?:\d[ -]?){12,18}\d(?!\d)") # 13 to 19 digits, optional spaces or dashes
def luhn_sum(digits):
"""From the right, double every second digit (subtracting 9 when that makes two digits) and add them all."""
total = 0
for i, ch in enumerate(reversed(digits)):
d = int(ch)
if i % 2 == 1:
d = d * 2 - 9 if d > 4 else d * 2
total += d
return total
def luhn_ok(digits):
return luhn_sum(digits) % 10 == 0
def mask(digits):
return digits[:6] + "*" * (len(digits) - 10) + digits[-4:]
def scan_text(text):
"""Yield (digits, passes_luhn) for each candidate in the text."""
for m in CANDIDATE.finditer(text):
digits = re.sub(r"\D", "", m.group())
if 13 <= len(digits) <= 19:
yield digits, luhn_ok(digits)
def scan_file(path):
"""Return [(where, digits, passes_luhn)] for a text file, or for every text cell of a SQLite file."""
hits = []
with open(path, "rb") as f:
head = f.read(16)
if head.startswith(b"SQLite format 3"):
db = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
for (table,) in db.execute("SELECT name FROM sqlite_master WHERE type = 'table'").fetchall():
for col in [r[1] for r in db.execute(f'PRAGMA table_info("{table}")')]:
for (v,) in db.execute(f'SELECT "{col}" FROM "{table}" WHERE typeof("{col}") IN (\'text\', \'blob\')'):
text = v.decode("latin-1") if isinstance(v, bytes) else v
hits += [(f"{path} [{table}.{col}]", d, ok) for d, ok in scan_text(text)]
else:
with open(path, errors="replace") as f:
for n, line in enumerate(f, 1):
hits += [(path, d, ok) for d, ok in scan_text(line)]
return hits
def walk(roots):
for root in roots:
if os.path.isfile(root):
yield root
continue
for base, dirs, files in os.walk(root):
dirs[:] = [d for d in dirs if d != "__pycache__"]
for name in sorted(files):
yield os.path.join(base, name)
if __name__ == "__main__":
found = Counter() # (place, passes Luhn) -> how many strings
for path in walk(sys.argv[1:]):
for where, digits, ok in scan_file(path):
found[(where, ok)] += 1
cards = other = 0
for place in sorted({p for p, _ in found}):
good, bad = found[(place, True)], found[(place, False)]
cards, other = cards + good, other + bad
if good:
print(f"CARD {good:3} pass Luhn ({bad} do not) {place}")
print(f"{cards} strings of 13 to 19 digits pass the Luhn check; {other} others do not")Test it on a file you control before you trust it. The file holds one Luhn-valid test number, one 16-digit tracking code and one 13-digit phone number.
printf 'order CO-000001 paid with 4111111111111111 on 2026-11-17\ntracking 1234567890123456 for the rider\nphone 2348031234567\n' > selftest.txt
python3 pan_scan.py selftest.txtCARD 1 pass Luhn (2 do not) selftest.txt
1 strings of 13 to 19 digits pass the Luhn check; 2 others do notThree digit strings, one card. The tracking code and the phone number are look-alikes that the check rejects. If your scanner reports three, the Luhn check is wrong.
Now scan the project as it stands: the logs, the mocks’ databases and your source files.
python3 pan_scan.py logs data/scenarios.sqlite data/provider.sqlite data/switch.sqlite wallet.py reconcile.py scenarios.py ledger.py0 strings of 13 to 19 digits pass the Luhn check; 7 others do notNo cards. That is a real result about the wallet: it never writes the number down, and the provider keeps the last four digits only. But the seven digit strings that fail the check include the six test numbers in scenarios.py (the seventh is a digit run inside a hash), and the next step shows why. A scan that never finds a card has not shown that it can.
4. See why the lab’s own numbers are invisible. Do the Luhn sum by code for one of the lab’s test numbers, then for a version with one digit changed. Then save testcards.py, which makes a Luhn-valid version of each lab number by changing the twelfth digit. The mock decides the outcome from the last four digits, so the changed numbers behave in the same way.
python3 -c "
from pan_scan import luhn_sum
for pan in ('4242424242420001', '4242424242410001'):
print(pan, luhn_sum(pan), luhn_sum(pan) % 10)""""Lab test card numbers that pass the Luhn check. The mock provider decides the outcome from the last four
digits (0001 success, 0002 decline, 0005 lost response), so we keep those and change one digit before them."""
from pan_scan import luhn_ok
def luhn_version(pan):
"""Change the 12th digit of a 16-digit number until the Luhn check passes. Exactly one digit does."""
for d in "0123456789":
candidate = pan[:11] + d + pan[12:]
if luhn_ok(candidate):
return candidate
raise ValueError("no digit works")
LAB_CARDS = {last4: luhn_version(f"424242424242{last4}") for last4 in ("0001", "0002", "0005")}
if __name__ == "__main__":
for last4, pan in LAB_CARDS.items():
print(last4, pan[:6] + "******" + pan[-4:], "passes Luhn:", luhn_ok(pan))python3 testcards.py4242424242420001 61 1
4242424242410001 60 0
0001 424242******0001 passes Luhn: True
0002 424242******0002 passes Luhn: True
0005 424242******0005 passes Luhn: TrueThe first number’s sum is 61, as in the worked example, so it fails. Changing one digit of 2 to 1 takes the sum to 60, a multiple of 10. The lab numbers 0001, 0002 and 0005 now pass the check, and the scanner can see them. These numbers were made for the lab. Use only them, or your provider’s published test numbers, and never a real card.
5. Add Tallowmere’s first checkout. Save these two files. checkout.py is a small web service in front of the wallet. It has three habits that look helpful: it logs every request while debugging, it keeps the card for the nightly refill job, and on an error it writes the request to an error log. shop.py stands in for the web page and posts twelve payments: eight good, two declines, one lost response and one badly typed amount that makes the handler raise.
"""Tallowmere's first checkout, written the way small teams write it: the browser posts the card to our server,
our server charges it through the wallet and keeps what the nightly refill job will need. Do not copy it."""
import argparse
import json
import os
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from wallet import PROVIDER_KEY, SWITCH_KEY, Api, Wallet, create
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=8080)
ap.add_argument("--db", default="data/checkout.sqlite")
ap.add_argument("--provider", default="http://127.0.0.1:8101")
ap.add_argument("--switch", default="http://127.0.0.1:8102")
ap.add_argument("--hook-port", type=int, default=9000)
a = ap.parse_args()
os.makedirs("logs", exist_ok=True)
create(a.db, 50)
w = Wallet(a.db, Api(a.provider, PROVIDER_KEY), Api(a.switch, SWITCH_KEY))
w.db.execute("""CREATE TABLE orders (order_key TEXT PRIMARY KEY, customer_id INTEGER, amount_kobo INTEGER,
card_number TEXT, expiry TEXT, state TEXT)""") # "so the refill job can charge again"
w.start(a.hook_port)
counter = [0]
def log(name, text):
with open(f"logs/{name}.log", "a") as f:
f.write(text + "\n")
class Checkout(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
log("checkout-access", fmt % args)
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
log("checkout-debug", f"POST {self.path} body={raw.decode()}") # habit 1: log the request while debugging
try:
order = json.loads(raw)
counter[0] += 1
key = f"CO-{counter[0]:06d}"
state = w.fund_card(order["customer_id"], order["amount_kobo"], order["card_number"], key)
with w.tx(): # habit 2: keep the card for the refill job
w.db.execute("INSERT INTO orders VALUES (?, ?, ?, ?, ?, ?)",
(key, order["customer_id"], order["amount_kobo"], order["card_number"], order["expiry"], state))
out, status = {"order": key, "state": state}, 200
except Exception as e:
log("checkout-errors", f"{e!r}\n{traceback.format_exc()}request: {raw.decode()}") # habit 3: dump the request on error
out, status = {"error": "internal"}, 500
body = json.dumps(out).encode()
self.send_response(status)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
print(f"checkout on http://127.0.0.1:{a.port} wallet database {a.db} logs in logs/", flush=True)
ThreadingHTTPServer(("127.0.0.1", a.port), Checkout).serve_forever()"""A stand-in for Tallowmere's web page: posts card payments to the checkout, as a browser form would."""
import argparse
import json
import urllib.error
import urllib.request
from testcards import LAB_CARDS
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=8080)
a = ap.parse_args()
# (customer, amount in kobo, card). 1,850,000 kobo is N18,500, the average refill. Cards 0002 declines, 0005 loses its response.
orders = [(c, 1_850_000, LAB_CARDS["0001"]) for c in range(1, 9)]
orders += [(9, 950_000, LAB_CARDS["0002"]), (10, 4_200_000, LAB_CARDS["0002"]), (11, 1_850_000, LAB_CARDS["0005"])]
for customer, amount, card in orders + [(12, "18500 naira", LAB_CARDS["0001"])]: # the last is a badly typed amount
body = {"customer_id": customer, "amount_kobo": amount, "card_number": card, "expiry": "12/28", "cvv": "123"}
req = urllib.request.Request(f"http://127.0.0.1:{a.port}/checkout", json.dumps(body).encode(), {"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req) as r:
print(r.status, json.loads(r.read()))
except urllib.error.HTTPError as e:
print(e.code, json.loads(e.read()))python3 checkout.py > logs/checkout.out 2>&1 & echo $! > logs/checkout.pid
sleep 2; cat logs/checkout.out
python3 shop.pycheckout on http://127.0.0.1:8080 wallet database data/checkout.sqlite logs in logs/200 {'order': 'CO-000001', 'state': 'credited'}
200 {'order': 'CO-000002', 'state': 'credited'}
200 {'order': 'CO-000003', 'state': 'credited'}
200 {'order': 'CO-000004', 'state': 'credited'}
200 {'order': 'CO-000005', 'state': 'credited'}
200 {'order': 'CO-000006', 'state': 'credited'}
200 {'order': 'CO-000007', 'state': 'credited'}
200 {'order': 'CO-000008', 'state': 'credited'}
200 {'order': 'CO-000009', 'state': 'failed'}
200 {'order': 'CO-000010', 'state': 'failed'}
200 {'order': 'CO-000011', 'state': 'credited'}
500 {'error': 'internal'}Eight credited, two failed on the declined card, the lost-response card credited, and a 500 for the badly typed amount. Every payment worked. Nothing in the output says that anything is wrong.
Scan again, including the checkout’s new files, and count the security codes in the debug log.
python3 pan_scan.py logs data/checkout.sqlite data/provider.sqlite data/switch.sqlite wallet.py reconcile.py scenarios.py ledger.py checkout.py shop.py
grep -c '"cvv"' logs/checkout-debug.log
python3 -c "
import sqlite3
db = sqlite3.connect('data/provider.sqlite')
for row in db.execute(\"SELECT reference, card_last4, status FROM charges WHERE reference LIKE 'CO-%' ORDER BY reference LIMIT 3\"):
print(row)"CARD 11 pass Luhn (0 do not) data/checkout.sqlite [orders.card_number]
CARD 12 pass Luhn (0 do not) logs/checkout-debug.log
CARD 1 pass Luhn (0 do not) logs/checkout-errors.log
24 strings of 13 to 19 digits pass the Luhn check; 12 others do not
12
('CO-000001', '0001', 'success')
('CO-000002', '0001', 'success')
('CO-000003', '0001', 'success')The scan finds 24 card numbers in three places: 12 in the debug log (the eleven that reached the provider and the badly typed one), one in the error log (the request that raised), and 11 in the orders table. The grep finds 12 security codes in the debug log, which the standard says must not be kept after authorisation. The provider’s own table holds the last four digits, card_last4, and nothing more: that is the shape to copy. The strings that fail the check are the six lab numbers in scenarios.py and digit runs inside event ids and hashes in the SQLite files. Those runs differ from one run to the next, so your count of others will not match, but the 24 and the 12 will.
6. Try the obvious fix. Copy the database, as a nightly backup would have, then null the card_number column and scan again.
cp data/checkout.sqlite data/backup-checkout.sqlite
python3 -c "
import sqlite3
db = sqlite3.connect('data/checkout.sqlite')
db.execute('UPDATE orders SET card_number = NULL')
db.commit()
print(db.execute('SELECT COUNT(*) FROM orders WHERE card_number IS NOT NULL').fetchone()[0], 'rows still hold a card number')"
python3 pan_scan.py logs data/checkout.sqlite data/backup-checkout.sqlite0 rows still hold a card number
CARD 11 pass Luhn (0 do not) data/backup-checkout.sqlite [orders.card_number]
CARD 12 pass Luhn (0 do not) logs/checkout-debug.log
CARD 1 pass Luhn (0 do not) logs/checkout-errors.log
24 strings of 13 to 19 digits pass the Luhn check; 2 others do notThe live table is clean. (The two others are digit runs inside event ids; your count may differ.) The scan still finds 24 numbers: 11 in the backup, 12 in the debug log and one in the error log. Removing the column fixed one of four places. This is why the cheapest control is to stop the number arriving.
7. Draw the scope. Save this as scope.py. It holds a list of Tallowmere’s systems and the flows between them, three ways of taking a card. For each design it prints which systems store, process or transmit the number (the card data environment), which are connected to those, and which SAQ the design points to. The list is illustrative: put your own systems in it. The SAQ line encodes the reading in the chapter and is not a ruling. Your acquirer gives the ruling.
"""Tallowmere's systems and the flows between them, three ways of taking a card. For each design, which of OUR systems
store, process or transmit the card number (the cardholder data environment), which are connected to those, and which
SAQ the design points to. The inventory is illustrative: replace it with your own."""
OURS = ["checkout server", "wallet service", "orders database", "log files", "backup store", "refill job",
"support laptops", "stock system", "rider app"]
OTHER = ["customer's browser", "payment provider"] # not ours: the customer's device and the provider's systems
# (from, to, carries the card number?). Flows that carry no card data still connect two systems.
COMMON = [("stock system", "orders database"), ("rider app", "checkout server")]
DESIGNS = {
"A card goes to our server": dict(form_from="our server", flows=COMMON + [
("customer's browser", "checkout server", True), ("checkout server", "wallet service", True),
("wallet service", "payment provider", True), ("checkout server", "orders database", True),
("checkout server", "log files", True), ("orders database", "backup store", True),
("refill job", "orders database", True), ("refill job", "payment provider", True),
("support laptops", "log files", True)]),
"B direct post to provider": dict(form_from="our server", flows=COMMON + [
("customer's browser", "payment provider", True), ("customer's browser", "checkout server", False),
("checkout server", "wallet service", False), ("wallet service", "payment provider", False),
("checkout server", "orders database", False), ("checkout server", "log files", False),
("orders database", "backup store", False), ("refill job", "orders database", False),
("refill job", "payment provider", False), ("support laptops", "log files", False)]),
"C hosted fields or redirect": dict(form_from="the provider", flows=COMMON + [
("customer's browser", "payment provider", True), ("customer's browser", "checkout server", False),
("checkout server", "wallet service", False), ("wallet service", "payment provider", False),
("checkout server", "orders database", False), ("checkout server", "log files", False),
("orders database", "backup store", False), ("refill job", "orders database", False),
("refill job", "payment provider", False), ("support laptops", "log files", False)]),
}
def classify(flows):
"""Our systems on a flow that carries the number are in the cardholder data environment (CDE); the rest that
share any flow with a CDE system are connected to it; the rest are out of scope."""
cde = {s for f in flows if len(f) == 3 and f[2] for s in f[:2] if s in OURS}
connected = {s for f in flows for s in f[:2] if s in OURS and s not in cde
and any(o in cde for o in f[:2])}
return cde, connected
def saq(design, cde):
if cde:
return "SAQ D: card data reaches our systems"
if design["form_from"] == "our server":
return "SAQ A-EP: our page can affect the payment, though the card goes to the provider"
return "SAQ A, if every criterion in the form holds and the acquirer allows it"
for name, design in DESIGNS.items():
cde, connected = classify(design["flows"])
page = {"checkout server"} - cde # it serves the page the customer pays on, so it keeps duties of its own
print(f"{name}\n card data environment ({len(cde)}): {', '.join(sorted(cde)) or 'none of ours'}")
print(f" connected to it ({len(connected)}): {', '.join(sorted(connected)) or 'none'}")
print(f" serves the payment page, still has duties: {', '.join(sorted(page)) or 'already counted above'}")
print(f" no card data, no link to it: {', '.join(sorted(set(OURS) - cde - connected - page)) or 'none'}")
print(f" points to: {saq(design, cde)}")python3 scope.pyA card goes to our server
card data environment (7): backup store, checkout server, log files, orders database, refill job, support laptops, wallet service
connected to it (2): rider app, stock system
serves the payment page, still has duties: already counted above
no card data, no link to it: none
points to: SAQ D: card data reaches our systems
B direct post to provider
card data environment (0): none of ours
connected to it (0): none
serves the payment page, still has duties: checkout server
no card data, no link to it: backup store, log files, orders database, refill job, rider app, stock system, support laptops, wallet service
points to: SAQ A-EP: our page can affect the payment, though the card goes to the provider
C hosted fields or redirect
card data environment (0): none of ours
connected to it (0): none
serves the payment page, still has duties: checkout server
no card data, no link to it: backup store, log files, orders database, refill job, rider app, stock system, support laptops, wallet service
points to: SAQ A, if every criterion in the form holds and the acquirer allows itWith the card going to your own server (A), seven of the nine systems are in the card data environment, and the two others are connected to it, so all nine are in scope. With the card going to the provider (B and C), none is in the environment. The checkout server keeps duties because it serves the payment page, and the other eight have no card data and no link to it. Designs B and C differ only in the SAQ line, because they differ in who serves the form.
8. Redesign: the card goes to the provider. Stop the first checkout and move its files aside. Save checkout2.py, browser.py and refill.py. In the new flow the server creates an order with a reference, the browser sends the card to the provider with that reference, and the server then asks the provider what happened through the wallet’s settle_charge, which ignores everything but the provider’s own record, as the module 2 project argued. The server keeps only the provider’s token (its authorization_code), the last four digits and the expiry month. The lab’s mock has no hosted fields, so browser.py posts to the provider’s /charges with the lab’s key. A real provider’s page uses a public key or a session so the browser never holds a secret key. The amount is also supplied by the browser here, and a different amount would be caught, as settle_charge compares it with the order.
"""Tallowmere's checkout after the redesign. The card goes from the customer's browser straight to the provider
(hosted fields); this server creates the order, then asks the provider what happened and keeps only a token."""
import argparse
import json
import os
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from wallet import PROVIDER_KEY, SWITCH_KEY, Api, Wallet, create
from generate import CARD_FEE_CAP, CARD_FEE_RATE
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=8080)
ap.add_argument("--db", default="data/checkout2.sqlite")
ap.add_argument("--provider", default="http://127.0.0.1:8101")
ap.add_argument("--switch", default="http://127.0.0.1:8102")
ap.add_argument("--hook-port", type=int, default=9000)
a = ap.parse_args()
os.makedirs("logs", exist_ok=True)
create(a.db, 50)
w = Wallet(a.db, Api(a.provider, PROVIDER_KEY), Api(a.switch, SWITCH_KEY))
w.db.execute("CREATE TABLE saved_cards (customer_id INTEGER, authorization_code TEXT, last4 TEXT, exp_month TEXT)")
w.start(a.hook_port)
counter = [0]
def log(name, text):
with open(f"logs/{name}.log", "a") as f:
f.write(text + "\n")
class Checkout(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
log("checkout2-access", fmt % args)
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
log("checkout2-debug", f"POST {self.path} body={raw.decode()}") # the same habit as before: log every request
try:
req = json.loads(raw)
if self.path == "/order": # 1. the order exists before any card is shown
counter[0] += 1
key = f"CO2-{counter[0]:06d}"
amount = req["amount_kobo"]
with w.tx():
w._begin(key, "fund_card", req["customer_id"], amount, min(CARD_FEE_CAP, round(amount * CARD_FEE_RATE)),
state="charging")
out = {"reference": key}
else: # 2. /confirm: ask the provider, never trust the browser
state = w.settle_charge(req["reference"])
status, got = w.provider.call("GET", f"/charges/{req['reference']}")
auth = got.get("charge", {}).get("authorization") if status == 200 else None
if state == "credited" and auth: # keep the token and the last four, nothing else
with w.tx():
w.db.execute("INSERT INTO saved_cards VALUES (?, ?, ?, ?)",
(w.op(req["reference"])["customer_id"], auth["authorization_code"], auth["card_last4"], auth["exp_month"]))
out = {"reference": req["reference"], "state": state}
status = 200
except Exception as e:
log("checkout2-errors", f"{e!r}\n{traceback.format_exc()}request: {raw.decode()}")
out, status = {"error": "internal"}, 500
body = json.dumps(out).encode()
self.send_response(status)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
print(f"checkout2 on http://127.0.0.1:{a.port} wallet database {a.db} logs in logs/", flush=True)
ThreadingHTTPServer(("127.0.0.1", a.port), Checkout).serve_forever()"""A stand-in for the customer's browser with the provider's hosted fields: the card goes to the provider, and only the
order reference goes to Tallowmere. With --leak the page also sends the form to Tallowmere, as a fallback or an analytics tag might."""
import argparse
import json
import urllib.error
import urllib.request
from testcards import LAB_CARDS
from wallet import PROVIDER_KEY
ap = argparse.ArgumentParser()
ap.add_argument("--port", type=int, default=8080)
ap.add_argument("--provider", default="http://127.0.0.1:8101")
ap.add_argument("--leak", action="store_true")
a = ap.parse_args()
def post(base, path, body, key=None):
headers = {"Content-Type": "application/json"}
if key:
headers["Authorization"] = f"Bearer {key}"
req = urllib.request.Request(base + path, json.dumps(body).encode(), headers)
try:
with urllib.request.urlopen(req) as r:
return json.loads(r.read())
except urllib.error.HTTPError as e:
return json.loads(e.read())
shop = f"http://127.0.0.1:{a.port}"
orders = [(c, 1_850_000, LAB_CARDS["0001"]) for c in range(1, 9)]
orders += [(9, 950_000, LAB_CARDS["0002"]), (10, 4_200_000, LAB_CARDS["0002"]), (11, 1_850_000, LAB_CARDS["0005"])]
for customer, amount, card in orders:
ref = post(shop, "/order", {"customer_id": customer, "amount_kobo": amount})["reference"]
# the hosted field: the browser talks to the provider, not to Tallowmere (the lab's mock uses its one API key for this)
post(a.provider, "/charges", {"reference": ref, "amount_kobo": amount, "customer_ref": f"C{customer:07d}",
"card_number": card, "save_card": True}, PROVIDER_KEY)
confirm = {"reference": ref}
if a.leak:
confirm.update(card_number=card, expiry="12/28")
print(post(shop, "/confirm", confirm))"""The nightly refill job after the redesign: it charges a saved card by its token. It has never seen a card number."""
import argparse
import sqlite3
from wallet import PROVIDER_KEY, Api
ap = argparse.ArgumentParser()
ap.add_argument("--db", default="data/checkout2.sqlite")
ap.add_argument("--provider", default="http://127.0.0.1:8101")
a = ap.parse_args()
provider = Api(a.provider, PROVIDER_KEY)
for customer, code, last4, exp in sqlite3.connect(a.db).execute("SELECT * FROM saved_cards ORDER BY customer_id"):
status, out = provider.call("POST", "/charges", {"reference": f"REFILL-{code}", "amount_kobo": 1_850_000,
"customer_ref": f"C{customer:07d}", "authorization_code": code})
print(f"customer {customer} card ending {last4} {status} {out['charge']['status']} {out['charge']['gateway_response']}")kill $(cat logs/checkout.pid)
mkdir -p old && mv logs/checkout* data/checkout.sqlite data/backup-checkout.sqlite old/
python3 checkout2.py > logs/checkout2.out 2>&1 & echo $! > logs/checkout2.pid
sleep 2; cat logs/checkout2.out
python3 browser.py
python3 pan_scan.py logs data
python3 refill.py
head -2 logs/checkout2-debug.logcheckout2 on http://127.0.0.1:8080 wallet database data/checkout2.sqlite logs in logs/{'reference': 'CO2-000001', 'state': 'credited'}
{'reference': 'CO2-000002', 'state': 'credited'}
{'reference': 'CO2-000003', 'state': 'credited'}
{'reference': 'CO2-000004', 'state': 'credited'}
{'reference': 'CO2-000005', 'state': 'credited'}
{'reference': 'CO2-000006', 'state': 'credited'}
{'reference': 'CO2-000007', 'state': 'credited'}
{'reference': 'CO2-000008', 'state': 'credited'}
{'reference': 'CO2-000009', 'state': 'failed'}
{'reference': 'CO2-000010', 'state': 'failed'}
{'reference': 'CO2-000011', 'state': 'credited'}0 strings of 13 to 19 digits pass the Luhn check; 5 others do notcustomer 1 card ending 0001 200 success Approved
customer 2 card ending 0001 200 success Approved
customer 3 card ending 0001 200 success Approved
customer 4 card ending 0001 200 success Approved
customer 5 card ending 0001 200 success Approved
customer 6 card ending 0001 200 success Approved
customer 7 card ending 0001 200 success Approved
customer 8 card ending 0001 200 success Approved
customer 11 card ending 0005 200 success ApprovedPOST /order body={"customer_id": 1, "amount_kobo": 1850000}
POST /confirm body={"reference": "CO2-000001"}The orders are credited and failed exactly as before. The scan finds no card numbers in the logs or any database, including the checkout’s, and the strings that fail the check are digit runs inside ids and hashes (your count of those will differ). The refill job charges nine saved cards by their tokens and has never seen a number. The debug logging is still switched on, and it is harmless now: the request bodies hold a reference and an amount. The scope fell because the number stopped arriving, and not because anyone’s habits improved.
Break it. Run the browser with its fallback on, the way a page might post the whole form to your server when the provider’s frame fails to load, or an analytics tag might copy form fields:
python3 browser.py --leak
python3 pan_scan.py logs dataThe checkout still ignores the card. It credits the same orders. Yet the scan finds eleven card numbers in logs/checkout2-debug.log (it may also report a stray pass or two in the provider’s database, where an id of 13 to 19 digits passes the check by chance, about one time in ten), so the log files, the people who read them and the systems that ship them are back in the card data environment, and scope.py would put you back on design A. Scope depends on what arrives. Moving the debug line in checkout2.py below the parse, and logging only the fields you need, would cut what is logged, and that is worth doing as a second line of defence. It does not take you back off design A once the number has been sent to your server. Stop what you started: kill $(cat logs/provider.pid logs/switch.pid logs/checkout2.pid).
Template
# Card-data scope statement: <company>
Author <name, role> · Signed by <head of engineering>, <compliance lead> · Date <date>
Decision needed: <what the readers must decide, and by when>
## Where card data enters, travels and is stored
| Step | System | Carries the card number? | Evidence |
|---|---|---|---|
Enters: <where the customer types it, and who serves that form>
Stored: <every place a number, a security code or a token is kept>
## Systems in scope, and why
| System | Why it is in scope | Owner |
|---|---|---|
## Taken out of scope
| System | What changed (tokenisation, hosted fields) | Evidence: command, output, date |
|---|---|---|
## What this cannot see
<Encoded, split or compressed numbers, systems we do not run, and anything else the scan misses.>
## Open findings
| # | Finding | Owner | Next step | Date |
|---|---|---|---|---|
## Duties that remain
<Page and scripts, external scans, provider's compliance, API key, the acquirer's answer.>
## Next review
<Date, and the changes that bring it forward.> WORKED EXAMPLE
At Tallowmere, Feyisara writes it as the engineer who owns scoping; the head of engineering and Oghenekaro sign. At a larger company a security engineer writes it and the compliance lead signs too.
Tallowmere card-data scope statement, 20 November 2026.
Decision needed. Confirm the redesign as the answer to the bank’s questionnaire, and the open findings below.
Flow. The browser sends the card to the provider’s hosted fields and nowhere else. The checkout server receives an order reference, asks the provider what happened, and stores only a token, the last four digits and the expiry month. The refill job charged nine saved cards by token.
In scope. The checkout server, because it serves the page that carries the provider’s frame; the provider’s API key and the token table, because the key can charge a saved token. Feyisara owns all three.
Taken out. Eight of nine: wallet service, orders database, log files, backup store, refill job, support laptops, stock system, rider app. scope.py put seven in the card data environment and two connected to it before, and none after. The scan found 24 card numbers and 12 security codes before; after, it printed 0 strings of 13 to 19 digits pass the Luhn check; 5 others do not, and the same scanner found 1 card in 3 strings on its self-test.
Cannot see. Encoded, split or compressed numbers; systems we do not run.
Open findings.
- In a test run, a fallback that posts the form to our server put eleven numbers back in the debug log (
--leak). Feyisara removes the fallback by 4 December 2026. - The old backup, debug log and error log, moved aside and still holding 11, 12 and 1 numbers, are not destroyed. Feyisara, 27 November.
- The acquirer has not confirmed the form: SAQ A, if every criterion holds and it allows it. Oghenekaro, 18 December.
Duties that remain. The page and its scripts, external scans of its host, proof the provider is compliant, the key and token table, the acquirer’s answer.
Next review 12 February 2027, or when the payment page changes.
Now you
You are the part-time engineer who looks after the booking system of a clinic group in Enugu with twelve staff. Its booking page posts the card to the group’s own web server, which forwards it to the payment provider. The server keeps the number in the booking database to charge missed-appointment fees, the nightly backup copies that database, and when a payment fails the request is emailed in full to a shared mailbox that four reception PCs read. The provider offers hosted fields, and the practice manager has asked whether the group should move to them. Treat the web server, booking database, backup store, fee job, shared mailbox and reception PCs as your six systems. Run pan_scan.py on test data you generate, put them into scope.py, and write the scope statement for today’s design, with the redesign shown as what would come out of scope and what evidence would prove it. The owner and the practice manager will read it and decide whether to fund the change this quarter.
Self-check
Tallowmere takes about 300 patients' refills by card, ₦18,500 on average, and the acquirer's questionnaire has arrived. Today the browser posts the card to Tallowmere's server. Nine engineers, none of them full time on security, can spend about a month. Oghenekaro wants the shortest honest answer to the questionnaire, and Feyisara wants to remove the numbers from logs and backups for good. What do they do?
- DOC PCI Security Standards Council document library PCI Security Standards Council, 2026
Where the standard, the SAQs and the supplements are published. Open PCI DSS v4.0.1 and read requirements 3.3 to 3.5 on what may be stored, and the eligibility box at the top of SAQ A. This build did not read them, so the requirement numbers in the chapter are unconfirmed.
- DOC Guidance for PCI DSS Scoping and Network Segmentation, version 1.1 PCI Security Standards Council, 2017
The Council's own account of the cardholder data environment, connected-to and security-impacting systems, and segmentation. Read the scoping categories and the segmentation section. It is guidance from 2017 and does not replace any requirement; this build saw it through search results only.
- POST PCI DSS Scoping and Segmentation Guidance for Modern Network Architectures PCI Security Standards Council, 2024
The Council's announcement of the 2024 supplement for cloud and other modern setups. Read it for what the supplement adds to the 2017 guidance. Per search results it is guidance only and adds no requirements.
- DOC Tokenization Guidelines Information Supplement PCI Security Standards Council, 2011
The Council's advice on how tokenisation affects the scope of a merchant's environment. Read what makes a token safe and where it does not shrink scope. It is advisory, from 2011, and this build did not read the PDF.
- DOC FAQ 1291: why SAQ A-EP for direct post and SAQ A for iframe or redirect PCI Security Standards Council
The Council's question on the difference the table in this chapter rests on. Read the technical differences between the three designs. This build saw only the question, with the answer in secondary sources.
- DOC FAQ 1604: ASV scans under SAQ A PCI Security Standards Council
The Council's FAQ on external vulnerability scans for e-commerce merchants that outsource payment processing. Read what it says about redirect and iframe pages. Search results quoted only its opening statement, so check the full text.
- DOC Risk-Based Cybersecurity Framework and Guidelines for Deposit Money Banks and Payment Service Banks (2024) Central Bank of Nigeria, 2024
The CBN's current cybersecurity framework for banks and payment service banks. Read how it treats third-party service providers and which standards it names. It does not say which framework covers other payment companies, and this build did not read the PDF.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.