The SIM: identity in a card
A network cannot see a person, only a key it shares with a card. Learn what that key proves, what it cannot, and how a SIM swap goes round it
A phone authenticates to the network. An attacker records every radio message in the exchange, including the network's random challenge and the SIM's answer. Can the attacker now pretend to be that SIM next time?
A mobile network does not know who you are. It knows a number and a key. This chapter follows that key: what is on the card, how the network and the card prove themselves to each other without ever sending it, what 5G hides that 2G to 4G did not, and where the cryptography stops and a shop assistant’s judgment starts.
What the card holds
A SIM is a small computer: a chip with a processor, a small amount of memory and an operating system, defined by ETSI TS 102 221 for the UICC (the Universal Integrated Circuit Card, the physical card). The part that matters for identity is a handful of values.
| Value | What it is | Who knows it |
|---|---|---|
| IMSI | International Mobile Subscriber Identity: up to 15 digits. The first three are the mobile country code (MCC), the next two or three the mobile network code (MNC), the rest the subscriber number (MSIN). | SIM and network. Sent over the air in older generations. |
| K | The secret key, 128 bits. The root of everything. | SIM and the operator’s subscriber database only. Never transmitted. |
| OPc | A 128-bit value derived from K and the operator’s own constant (OP). Mixed into every calculation so two operators using the same K still get different answers. | SIM and the operator’s database. |
| ICCID | Integrated Circuit Card Identifier: the card’s serial number, printed on it, up to 20 digits. | Everyone. It names the plastic, not the subscriber. |
| MSISDN | The phone number. Held by the network. It is not on the card as an identity. | Network; the card may store a copy for display. |
| Applets and keys | Programs that run on the card (for example the menu behind USSD and SIM toolkit services) and the operator’s keys for updating them over the air. | Operator. |
The phone number is the part people think of as “the SIM”. It is not. The IMSI identifies the subscription; the number is a label that the operator’s database attaches to an IMSI. A SIM swap changes which IMSI and card a number points at. Keep that in mind: it is why the cryptography below cannot stop one.
The lab’s SIM, in ran/ue.yaml, holds IMSI 999700000000001: MCC 999, MNC 70, MSIN 0000000001. 999 is the test country code that ITU-T E.212 reserves for internal use; Nigeria’s is 621. No lab step uses 621.
Proving who you are without saying the secret
If the phone sent K to the network, anyone listening to the radio, or any rogue base station, would have it. The design goal is a challenge and response.
- The network picks a random 128-bit number, RAND, and computes from K, OPc and RAND an expected answer, XRES, plus a few other values.
- It sends the phone RAND and a second field, AUTN (the authentication token).
- The SIM runs the same calculation with the K it holds. It gets RES.
- The phone sends RES back. The network compares it with XRES. A match proves the SIM knows K.
The calculation is a set of functions called Milenage, specified in 3GPP TS 35.206 and built on AES, the same block cipher that protects your web traffic. Each function takes K, OPc and RAND (and for one of them, the sequence number) and gives a different output: one produces the answer RES, one a MAC (message authentication code, a keyed checksum), two produce the keys that later protect the radio link, and one produces a mask called AK. (Two more, f1* and f5*, do the same jobs for re-synchronisation.) The lesson on hashing, MACs and signatures explains why a MAC proves knowledge of a key without revealing it. Here the same idea runs both ways.
Why both sides prove themselves. In the first mobile networks only the phone was checked. A fake base station could therefore sit between a phone and the network and the phone would believe it. AUTN fixes that. It is 16 bytes made of three parts:
- SQN xor AK (6 bytes): the sequence number, hidden by the mask AK so a listener cannot read it.
- AMF (2 bytes): the authentication management field, a few flag bits. The lab’s value is
8000. - MAC (8 bytes): computed from K, OPc, RAND, the sequence number and the AMF field.
The SIM recomputes the MAC from its own K. If it does not match, the challenge did not come from someone holding K, and the SIM refuses it: a MAC failure. Both ends have now proved they hold the same secret.
The sequence number. The MAC alone would let an attacker record a genuine challenge and replay it to the phone later. The sequence number (SQN) stops that. The network increments it for each challenge. The SIM keeps the highest value it has accepted and rejects any challenge whose SQN is not ahead of it, within a window. If the network’s counter has fallen behind the SIM’s, for example after a database restore, the SIM answers with an AUTS (the re-synchronisation token), carrying its own counter, and the network adopts it. That reply is called a synchronisation failure. Remember the three outcomes: success, MAC failure (wrong key or a fake network), synch failure (right key, wrong counter).
What 5G adds: concealing the identity
Generations before 5G had one weakness that this protocol does not fix. To start, the phone must say who it is. In 2G, 3G and 4G the first message can carry the IMSI in clear (after the first time the phone usually sends a temporary identity instead, which is also readable and changes only now and then). Anyone with a cheap radio receiver, an IMSI catcher, can log which IMSIs are nearby.
5G separates the two. The permanent identity is the SUPI (Subscription Permanent Identifier). In nearly every network it is the IMSI, written imsi-999700000000001. The phone never sends it. It sends a SUCI (Subscription Concealed Identifier). 3GPP TS 33.501 defines how it is built: the MCC and MNC stay readable, because the serving network must route to your home network, and the MSIN is encrypted to a public key of the home network, using a fresh random value each time. The SIM holds the public key. Only the home network’s UDM (Unified Data Management, the function that holds subscriber data) holds the private key and can reverse it. Two registrations by the same phone therefore produce two different SUCIs, and a listener cannot link them.
A SUCI has these fields, which you decode in the lab:
| Field | Meaning | Lab value |
|---|---|---|
| SUPI type | 0 = IMSI | 0 |
| MCC, MNC | Home network | 999, 70 |
| Routing indicator | Picks which UDM group serves the subscriber | 0000 |
| Protection scheme | 0 = null (nothing hidden), 1 = Profile A (Curve25519), 2 = Profile B (secp256r1) | 0 |
| Home network public key id | Which of the home network’s keys was used | 0 |
| Scheme output | The MSIN, encrypted (or, under the null scheme, readable) | 0000000001 |
The lab uses the null scheme, so you can read the IMSI. A live 5G SIM uses Profile A or B. The lab’s UDM is configured with both keys (core/udm.yaml, hnet), but the simulated phone is not set to use them, a difference the lab’s README lists.
The 5G authentication exchange
Registration in 5G has a fixed order. The phone sends a Registration request with its SUCI. The AMF (Access and Mobility Management Function, the first core function the phone talks to) passes it to the AUSF (Authentication Server Function), which asks the UDM. The UDM de-conceals the SUCI, finds the subscriber in the UDR (Unified Data Repository, the database front end), reads K and OPc and the current SQN, runs Milenage, and returns an authentication vector. The network then sends the phone RAND and AUTN in an Authentication request.
Two details differ from 4G. First, the answer the phone sends is RES*, not RES. RES* mixes RES with RAND and the serving network’s name, so an answer calculated for one network cannot be replayed to another. Second, the AMF does not check it alone. The AMF holds only a hash of the expected answer, HXRES*, and the AUSF, in the home network, makes the final comparison. A visited network therefore cannot decide on its own that a roamer authenticated.
After that, a Security mode command selects the algorithms that protect the signalling, keys derived from K protect later messages, and the AMF sends Registration accept. In the lab this takes about 0.6 seconds from request to accept, much of it spent in the chain of HTTP calls between the core’s functions, which all go through a proxy.
eSIM
An eSIM is the same card without the plastic: an eUICC (embedded UICC) soldered into the phone, with several profiles on it. A profile is a whole SIM’s contents: IMSI, K, OPc and applets. The GSMA’s SGP.22 specification describes how a consumer device downloads one. The operator’s server (an SM-DP+, Subscription Manager Data Preparation) prepares the profile, encrypted for that one eUICC. The phone’s software (the LPA, Local Profile Assistant) fetches it using an activation code, often shown as a QR code.
Nothing about authentication changes: K is still on the chip and never leaves. What changes is the logistics and the risk. There is no shop counter and no card to cut, so the check on who may download a profile is entirely in the operator’s app and back office. That check is the same one a SIM swap attacks.
SIM swap: where the binding breaks
Everything above proves that the card holds K. Nothing proves the card belongs to the person who owns the number. A SIM swap (also SIM replacement fraud) attacks that gap:
- An attacker collects the victim’s personal details.
- They ask the operator, an agent or an online channel to move the number to a new SIM or eSIM, claiming loss or damage.
- The operator re-points the number to a new IMSI and K. The old card stops working.
- Calls and texts, including bank one-time codes sent by SMS, now reach the attacker.
The cryptography ran perfectly. The attacker’s card authenticates because the operator issued it. This is why defences are about process: checks before a swap, a delay or notification when one happens, and banks that use signals other than an SMS code. The NCC requires every SIM to be linked to the subscriber’s National Identification Number (NIN), and says an operator may replace the SIM of a registered subscriber only when the subscriber presents a NINas of 2026-11. Linkage gives the operator one more thing to check at the counter. It does not remove the need to check it.
Who issues the SIM in a virtual operator
Kolanut Mobile in its launch year is a Tier 1 operator. The NCC’s virtual operator framework (section 4.2) lets a Tier 1 Services Virtual Operator run its own brand, sales and distribution, but gives it no switching and no control of numbering; a Tier 2 Simple Facilities Virtual Operator may own and issue its own SIM and run its own HLR, HSS and authentication centre, relying on its host’s number rangesas of 2026-11. So in its launch year the SIMs Kolanut sells are Lumora Mobile’s: Lumora generates K, holds it, and runs the authentication. The agents in the markets sell cards whose secrets Kolanut has never seen. At Tier 2, Kolanut would hold K for its own subscribers, which makes it responsible for protecting the file that contains them. Keys leave the SIM factory in an encrypted batch file, so a leak of that file is a leak of every K in it. The MVNO Business course covers the licence and its fees.
You will find the same secret in two places, read the phone’s identity off a recorded registration, check the network’s challenge by hand, and see what a wrong key looks like. Work in labs/telecoms. Steps 1, 2 and 7 need the live core (see the README for SCTP). Every other step reads files in traces/ and works on any machine with Docker or Python.
1. The key on the phone’s side (live core; reading ran/ue.yaml needs no core).
grep -E "supi|key|op:|opType|amf|imei" ran/ue.yamlsupi: 'imsi-999700000000001', key: '465B5CE8B199B49FAA5F0A2EE238A6BC', op: 'E8ED289DEBA952E4283B54E88E6183CA', opType: 'OPC', amf: '8000' and imei: '356938035643803', followed by the imeiSv line. This is the file standing in for the card. The key is K, the op value (with opType: 'OPC') is the OPc, and the IMEI identifies the handset, not the subscription.2. The same key in the network’s database (live core).
docker compose up -d
scripts/subscriber.sh add 999700000000001 465B5CE8B199B49FAA5F0A2EE238A6BC E8ED289DEBA952E4283B54E88E6183CA 2340000000001
scripts/subscriber.sh show 999700000000001provisioned: 999700000000001, then a record. Find imsi: '999700000000001', msisdn: [ '2340000000001' ] and, under security:, k: '465B5CE8B199B49FAA5F0A2EE238A6BC', opc: 'E8ED289DEBA952E4283B54E88E6183CA', amf: '8000' and sqn: Long('64'). The K and OPc match step 1 character for character. That is the whole shared secret. Note the number is on the network side, attached to the IMSI. The sqn is the network’s counter; 64 is where this record starts.3. Read the SUCI from a recorded registration.
docker run --rm -v "$PWD/traces:/t:ro" nicolaka/netshoot:v0.13 \
tshark -r /t/attach-and-browse.pcapng -o nas-5gs.null_decipher:TRUE \
-Y 'nas-5gs.mm.message_type == 0x41' -V | grep -iE "suci|supi|mcc|mnc|routing|scheme|key|msin"999; MNC 70; routing indicator 0000; protection scheme 0 (null); home network public key identifier 0; scheme output 0000000001. Together they are the AMF’s own log line, suci-0-999-70-0000-0-0-0000000001: type 0, 999, 70, routing 0000, scheme 0, key id 0, MSIN 0000000001. (A live run’s AMF log shows the same string.) The raw bytes in the message are 01 99f907 0000 00 00 0000000010: the digits are stored in swapped-nibble pairs, which is why 0000000001 appears as ...10. A live network would show a scheme of 1 or 2 and a different string of bytes on every registration.4. Read the challenge and the answer.
scripts/ladder.sh traces/attach-and-browse.pcapng | head -18The first 18 lines of the ladder (the middle ones are the core looking up the subscriber’s data), with these steps at these times in seconds from the start of the capture: 8.058 Registration request (gNB to AMF); then the AMF asking the AUSF, the AUSF asking the UDM and the UDM reading the UDR; 8.245 Authentication request (AMF to the cell); 8.263 Authentication response; 8.280 the AUSF reporting the result to the UDM; 8.370 Security mode command; 8.386 Security mode complete; 8.659 Registration accept. Request to accept is about 0.6 s. The exchange you want is the two lines at 8.245 and 8.263: 18 ms for the SIM to check the network and answer.
To see the values, repeat the tshark command from step 3 with -Y 'nas-5gs.mm.message_type == 0x56 || nas-5gs.mm.message_type == 0x57'. The Authentication request carries, in this recording, RAND bb31141c553fe451382dae5068bac80e and AUTN f2e50daf5f8e80000e6d297caf0fa76f. The Authentication response carries RES* 9dad3bb47a01afbfe0bceea0168eaee7 (tshark labels the field plain “RES”). The key never appears. Another recording of the lab has different values every time: RAND is random.
5. Check the network’s AUTN yourself (needs pip install cryptography).
Create milenage.py:
# Milenage (3GPP TS 35.206) with the lab SIM.
import sys
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
K = bytes.fromhex("465B5CE8B199B49FAA5F0A2EE238A6BC")
OPC = bytes.fromhex("E8ED289DEBA952E4283B54E88E6183CA")
def E(x): # AES-128 encrypt one block with K
e = Cipher(algorithms.AES(K), modes.ECB()).encryptor()
return e.update(x) + e.finalize()
def xor(a, b): return bytes(p ^ q for p, q in zip(a, b))
def rot(x, bits): # rotate a 128-bit block left by a multiple of 8 bits
n = bits // 8
return x[n:] + x[:n]
def milenage(rand, sqn, amf):
temp = E(xor(rand, OPC))
# OUT1 = E_K(TEMP xor rot(IN1 xor OPc, 64)) xor OPc, IN1 = SQN || AMF || SQN || AMF
out1 = xor(E(xor(temp, rot(xor(sqn + amf + sqn + amf, OPC), 64))), OPC)
# OUT2 = E_K(rot(TEMP xor OPc, 0) xor c2) xor OPc; AK = first 6 bytes, RES = last 8
out2 = xor(E(xor(xor(temp, OPC), bytes(15) + b"\x01")), OPC)
return out1[:8], out2[8:], out2[:6] # MAC-A, RES, AK
rand = bytes.fromhex(sys.argv[1]); autn = bytes.fromhex(sys.argv[2])
sqn_ak, amf, mac = autn[:6], autn[6:8], autn[8:]
_, _, ak = milenage(rand, bytes(6), amf) # AK needs only K, OPc and RAND
sqn = xor(sqn_ak, ak)
mac_a, res, _ = milenage(rand, sqn, amf)
print("SQN ", int.from_bytes(sqn, "big"))
print("MAC (AUTN)", mac.hex())
print("MAC (calc)", mac_a.hex())
print("RES ", res.hex(), "-> MATCH" if mac == mac_a else "-> MAC MISMATCH")python3 milenage.py bb31141c553fe451382dae5068bac80e f2e50daf5f8e80000e6d297caf0fa76fSQN 64, then the same MAC twice, 0e6d297caf0fa76f, and RES 1b3d364b2e9f8b9a -> MATCH. Your script, holding only K and OPc from step 1, has recovered the sequence number the network hid with AK (64, the starting value from step 2) and recomputed the MAC the network sent. The phone does exactly this. (The RES* in the response is derived from this RES plus the network name and RAND, by a further key derivation in TS 33.501, so it is not the same string.)6. A wrong key, in the traces.
scripts/ladder.sh traces/unknown-subscriber.pcapng
scripts/ladder.sh traces/wrong-key.pcapngunknown-subscriber: a Registration request at 8.844 s and a Registration reject at 9.035 s, 0.19 s later, with 5GMM cause 11, “PLMN not allowed”. The network has no record of the SUCI, so it stops before any challenge. (Cause 11 is Open5GS’s choice; other cores answer differently.) wrong-key: Registration request at 11.229 s; Authentication request at 11.544 s; Authentication failure at 11.563 s with cause 21 (“Synch failure”); Registration reject at 11.609 s with cause 111, “Protocol error, unspecified”. The network and the phone hold different keys, so the AUTN the network built with its K cannot be verified with the phone’s K.
Run your script on that recording’s challenge: python3 milenage.py 64c286166a886e9f4572523def15e860 c010e57a977b80009d7ae5f642b6ce40. You get SQN 198022807121524, MAC (AUTN) 9d7ae5f642b6ce40, MAC (calc) d78624b09e431be2 and -> MAC MISMATCH. The wrong key turned the sequence number into noise, a number far ahead of any real counter. The lab’s quirk: a real phone checks the MAC first and answers “MAC failure” (cause 20). UERANSIM 3.2.6 checks the sequence number first, sees nonsense, and answers “Synch failure” (cause 21). Taught, not hidden: the symptom differs, the cause (wrong K) is the same.
7. Change the key on a live core (optional; live core).
docker compose --profile phone up -d ue # registers: the baseline
scripts/subscriber.sh remove 999700000000001
scripts/subscriber.sh add 999700000000001 00000000000000000000000000000000 E8ED289DEBA952E4283B54E88E6183CA 2340000000001
docker compose restart ue
docker compose logs ue | tail -20The first start ends with Initial Registration is successful. After the key is changed and the phone restarts, it receives an Authentication request and fails. The end of its log (timestamps vary per run):
[nas] [debug] Authentication Request received
[nas] [debug] Sending Authentication Failure due to SQN out of range
[nas] [error] Initial Registration failed [UNSPECIFIED_PROTOCOL_ERROR]
[nas] [debug] Handling Registration Reject abnormal case
[nas] [info] UE switches to state [MM-DEREGISTERED/ATTEMPTING-REGISTRATION]
[nas] [error] Network failing the authentication check“SQN out of range” is the simulator’s quirk from step 6: with the wrong key, the sequence number it unmasks is garbage, and UERANSIM 3.2.6 checks that before the MAC. A real phone would report a MAC failure. The last line is the phone’s conclusion once its retry timer runs out: it no longer trusts this network. Put the right key back with remove and add and restart the phone; it registers at once.
999700000000002, with the same K and OPc as the first: scripts/subscriber.sh add 999700000000002 465B5CE8B199B49FAA5F0A2EE238A6BC E8ED289DEBA952E4283B54E88E6183CA 2340000000002. Edit supi in ran/ue.yaml to imsi-999700000000002, then docker compose restart ue. (On a machine without SCTP, reason from step 5: the challenge and the check are the same.) The phone registers. The network can tell that the key works and that this IMSI is provisioned. It cannot tell that the card is a copy of another card’s secret, or that a second device with the first IMSI would also work: authentication proves knowledge of K, not that the card is the only holder of it, and not who is holding it. Now ask what a SIM swap changes in this database (the MSISDN’s link to an IMSI, and the new K) and what a careful operator would check before it changes.Kolanut Mobile is in its launch year. Its first SIM swap complaint arrives: a trader's number was moved to a new SIM at a market agent's stall using a photocopied ID. The SIMs and the swap system are Lumora Mobile's; Kolanut owns the customer, the agents and the brand. You lead customer care. What do you do first?
- DOC ETSI TS 133 501: Security architecture and procedures for 5G System (3GPP TS 33.501)
The authority for 5G-AKA, RES* and HXRES*, and for the SUCI and its protection schemes. The annexes give worked key derivations. Skip the sections on non-3GPP access first time. Read: clause 6.1 (authentication and key agreement), clause 6.12 (subscription identifier privacy), annex C (SUCI schemes).
- DOC ETSI TS 135 206: Milenage algorithm set (3GPP TS 35.206)
The functions your milenage.py implements, with the rotation and constant values and a reference implementation in an annex. The test data to check your own code against is in the companion TS 35.207. It is short and readable. Read: the algorithm description (clause 4) and the reference code annex.
- DOC ETSI TS 102 221: Smart cards; UICC-Terminal interface
What the card physically is and how the phone talks to it. Read the overview and the file structure to see where IMSI and ICCID live. Skip the electrical and protocol detail. Read: scope, overview and file system clauses.
- DOC GSMA eSIM: consumer specification SGP.22
Describes how a profile is prepared, downloaded and activated on an eUICC. The architecture section covers the SM-DP+ and LPA you met above. It is the document behind every QR code a mobile operator shows. Read: architecture overview, then the profile download procedure.
- DOC Open5GS quickstart
The core the lab runs. Read how a subscriber is registered with its IMSI, K, OPc and AMF fields, the same record you saw in the lab, and how the core is brought up.
- BOOK From GSM to LTE-Advanced Pro and 5G Martin Sauter, 2021
The standard readable account of authentication and the SIM in every generation. The chapters on GSM subscriber identity and on LTE security show what 5G changed. Read: the authentication and SIM sections of the GSM and LTE chapters.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.