Hello! I'm osi

I build and break things

(and pretend to be a bear on the internet)

osi, a bear with green ears and a purple stripe
← back to writeups

Reading the Accu-Chek SmartGuide without the Roche app

The Accu-Chek SmartGuide is a continuous glucose monitor made by Roche Diabetes Care. Its Android app, com.roche.smartguide.eu version 1.2.4 (build date 2026-09-16, from an APKPure XAPK), talks to the sensor over Bluetooth Low Energy. This work replaced the phone with a standalone ESP32-S3 reader with a 200x200 e-paper display, so the sensor can be read without an account, a phone, or Roche's cloud.

The first surprise is that there is almost no glucose algorithm to reverse. The sensor implements the Bluetooth SIG CGM Service (0x181F) and sends its own records in mg/dL, with trend and status bits already computed. The second surprise is that reading those records is still not a matter of connecting and subscribing. Roche wraps every useful characteristic in the Authorization Control Service (ACS, 0x183D): a PIN, a P-256 key exchange, an AES-128-GCM channel, and an X.509 client certificate issued by Roche's PKI.

A .NET app hiding in a shared library

There is no dex to feed to jadx. The app is Xamarin/.NET MAUI, and its logic lives in 209 managed assemblies inside lib/arm64-v8a/libassembly-store.so. That file is a Xamarin assembly store: magic XABA, format version 3 (0x80010003), 13-byte index entries, and each assembly payload stored as XALZ plus LZ4. Parse the store, decompress each entry, then run ilspycmd -p over Core.dll. The 221 resulting C# files are the authority for every byte layout below; the relevant namespaces are Sensor/Transport/AcsService, Sensor/Adapter/AcsAdapter.cs, Adapter/Acs/Crypto and Transport/CgmService.

The GATT surface

ServiceUUIDCharacteristics
CGM0x181FMeasurement 2AA7 (notify), Feature 2AA8, Status 2AA9, SessionStart 2AAA (read/write), SessionRunTime 2AAB, ControlPoint 2AAC (write/indicate), RACP 2A52
ACS0x183DStatus 2B2F (read/notify), DataIn 2B30 (write), DataOut notify/indicate 2B31/2B32, ControlPoint 2B33
RCS0x1829ControlPoint 2B1F, used only to propose connection parameters
DIS0x180AManufacturer, model, serial, firmware, hardware, software revisions

The sensor advertises as AC-<model><serial>, for example AC-2A1234567. The app strips the prefix, takes two characters as the model and the rest as the serial. Service UUIDs are 16-bit; characteristics use the standard 128-bit base. Discovery filters on the CGM service and flags ACS support when 0x183D is present.

Pairing starts with a read

There is no passkey prompt. Bonding is triggered by a plain read of ACS Status (2B2F), and this path has no passkey exchange. The six-digit PIN printed on the sensor applicator's twist cap is not a Bluetooth passkey: it is used only inside the ACS key exchange, as the secret that authenticates the confirmation code.

After bonding, the client asks for the ATT MTU with ACS control-point opcode 221, then downloads everything it needs to frame the session: restriction maps, security configurations, key descriptors and the handle-to-UUID map, plus a 16-bit certificate nonce. All of that happens before any encrypted traffic exists.

One buffer, reversed

The ACS framing is the part most likely to waste an afternoon, because the app builds little-endian structs and then reverses whole buffers for the wire. Every field therefore arrives in the opposite order from its natural encoding.

A DataIn write (2B30) carries the security configuration id, the variable nonce, the GCM tag and the ciphertext:

[securityConfigId u16]
[variableNonce, 4 bytes, reversed]
[GCM mac, 16 bytes, reversed]
[ciphertext, reversed]

The plaintext is [resourceHandle u16][payload], and that whole buffer is reversed before encryption. On receive the transform is undone: strip the header, reverse the remainder, decrypt. The nonce is the client's 4-byte fixed prefix from opcode 35 concatenated with a 4-byte big-endian counter that increments before every DataIn frame and has to be persisted across reconnects.

Only DataIn and DataOut are encrypted. The ACS control point (2B33) stays plaintext for the whole handshake, which is why the key exchange can bootstrap itself without a prior key.

Every write is segmented with a one-byte header, (counter << 2) | first | (last << 1), and each segment carries at most MTU minus one bytes. The control point uses the same header for long requests such as the certificate-carrying ECDH step.

When porting this, mirror the C# rather than "fix" it: a locally consistent but differently ordered implementation fails the GCM tag check.

The restriction-map byte that is a length

The restriction map declares which handle needs which security configuration for which operation. Each protected resource is encoded as:

[type u8][handle u16][opsLen u8][opsLen/4 x (opCode u16, securityConfigId u16)]

opsLen is the length of the op list in bytes, four per pair, not a count of pairs. The app's parser bounds the list with it and walks four bytes at a time. Read as a count, it consumes four op pairs instead of one, so the cursor lands inside the next descriptor and every later handle is wrong. The visible symptom is a protected read failing with "no security configuration for resource", which looks like a permissions problem rather than a parsing one.

uint16_t handle = 0;
uint8_t opBytes = 0;
if (!c.u16(handle) || !c.u8(opBytes)) break;

// opsLen is a byte length: four bytes per (opCode, securityConfigId) pair.
for (int i = 0; i + 4 <= (int)opBytes; i += 4) {
  uint16_t op = 0, sc = 0;
  if (!c.u16(op) || !c.u16(sc)) return count;
  pr.ops[pr.opCount].opCode = op;
  pr.ops[pr.opCount].secConfigId = sc;
}

The map that changes after the handshake

Opcode 1 returns four responses in sequence: a restriction map, the security configurations (opcode 12), the key descriptors (opcode 14), and finally a plain success. Opcode 4 returns the map ids as 16-bit pairs.

The non-obvious part is that the map in force after the key exchange is not the one active before it. AcsAdapter deliberately fetches every map except the active one, subscribes to ACS Status, and only then performs the exchange. When it completes, the sensor sends a Status notification whose second field is the new map id, and the app blocks waiting for it before selecting the matching pre-downloaded map.

ACS Status is exactly three bytes: [flags u8][currentRestrictionMapId u16]. Bit 0 of the flags says security controls are active, bit 1 says security is established. A client that only reads the pre-exchange map ends up holding a map that protects nothing, which is why the exchange can appear to succeed while every subsequent read still fails.

The simulator built for this project makes the behaviour visible: map 0 protects nothing, map 1 requires authenticated and encrypted access to every CGM characteristic, and the switch is announced only after the confirmation random number is exchanged.

The key exchange

The exchange is a sequence of control-point procedures, mostly in the 17 to 35 range, plus the certificate nonce query:

CodeProcedurePayload and result
224GetCertificateNonce16-bit nonce used to bind a certificate request to this sensor
35SetAcClientNonceFixed4 random bytes, reversed; becomes the fixed nonce prefix
17StartKeyExchange[keyId][3][0xFF], answered by 18
27KeyExchangeEcdhclient X.509 certificate DER; answered by 28 with the sensor's public key
33KeyExchangeKdfanswered by 34 with HKDF salt and info, both reversed
29Confirmation code32 bytes, reversed; answered by 30 with the sensor's code
31Confirmation random32 bytes, reversed; answered by 32 with the sensor's random

The certificate sent in opcode 27 is not decoration: its public key is the ECDH key pair. The client computes Z from its private scalar and the sensor's X and Y coordinates, then derives a 16-byte key with HKDF-SHA256 using the salt and info from response 34. Coordinates and KDF parameters arrive byte-reversed, so X and Y become 32-byte big-endian integers once flipped.

Authentication is a three-stage HMAC chain over the PIN, both public keys and a fresh random number:

// auth = PIN as ASCII, left-padded with zeros to 32 bytes
// salt = HMAC-SHA256(0^32, remotePub || localPub)
hmacSha256N(zeros, 32, saltBlocks, 4, salt);
// key  = HMAC-SHA256(salt, derivedKey || auth)
hmacSha256_2(salt, 32, derivedKey, 16, auth, 32, key);
// code = HMAC-SHA256(key, random)
hmacSha256_1(key, 32, random, 32, out);

Each public key contributes X then Y, 32 bytes each, so the salt message is 128 bytes. The exchange is mutually authenticated in a slightly unusual way: the client sends its code, the sensor replies with a code computed over its own random number, the client then sends its random number and receives the sensor's, recomputes the code with the sensor's random, and compares it with the code the sensor sent. Two randoms, one shared confirmation. A wrong PIN surfaces as response code 9, InvalidKeyExchangeConfirmationCode.

Once the exchange finishes, the client keeps the AES key id, the fixed nonce, the variable nonce counter and the derived key. The app stores this per device and treats it as established security, skipping the handshake on later connections, so there is one key exchange per sensor. Re-keying means sending opcode 19 to invalidate, dropping the stored state and pairing again.

The certificate gate

This is the piece that most likely decides whether a third-party reader can pair at all, and it is the one part not verified against hardware. The app never generates a certificate locally. It builds a PKCS#10 request and posts it to Roche's certificate API, so the sensor is presented with a certificate issued by Roche's CA rather than a self-signed one.

CSR fieldValue
OrganizationRoche Diabetes Care GmbH
Common name947
Serial numberthe app instance id, at most 36 characters
Surname303
Given namesensor model plus serial, or *
Pseudonymthe 16-bit nonce from opcode 224, or *
ExtensionsbasicConstraints critical CA=false, keyUsage critical with bits 200

The keyUsage value 200 encodes digitalSignature, nonRepudiation and keyAgreement, exactly what an ECDH client certificate needs. The request is signed with the same P-256 key used in the key exchange, and that private scalar is what the firmware has to keep next to the certificate.

Two modes exist. A constrained request binds the certificate to one sensor through the given name and the sensor nonce. A wildcard request sends * for both but keeps CN=947, giving one certificate valid for any sensor; the app caches it and refreshes when under 30 days remain. The request goes to POST /cs/pki/v3/certificate with a bearer token and a Content-Digest header, and the certificate comes back in dcdCertificate as base64 DER.

Getting a token is its own puzzle: login goes through a Keycloak realm under the app's white-label flow, and the code is exchanged at the gateway's own token endpoint with client credentials and an API key baked into the app. The enrollment script implements the path; the values themselves are not reproduced here.

Whether the API will issue a certificate for a given account, and whether the sensor accepts the chain, is unverified. There is no generated client-certificate header in the tree, and the firmware is written to refuse pairing with an explicit "sin certificado" error when that header is absent.

The CRC that blocked pairing

The CGM characteristics are SIG records with a Roche trailer: a CRC-16 over the whole characteristic value, low byte first. The app's Crc.cs builds its table from the reflected polynomial, and the table's first entries give it away: 0x0000, 0x1189, 0x2312, 0x329B. That is CRC-16/MCRF4XX (reflected 0x1021, init 0xFFFF, no final xor, check value 0x6F91), not CCITT-FALSE, whose table starts 0x0000, 0x1021, 0x2042, 0x3063 and whose check value is 0x29B1.

The distinction cost real time because the failure is quiet. During pairing the only CRC'd frame the app parses is the CGM control-point reply, five bytes:

[0x28][requestOpCode][responseCode][crc lo][crc hi]

The parser requires exactly five bytes and validates the CRC before looking at anything else. With the wrong CRC variant the app accepted the connection, completed the ACS exchange, received that reply, and dropped the link roughly 100 ms later. No error, no diagnostic. The simulator reproduced it deterministically once the app was pointed at it. crc16Roche() now uses the reflected variant, and the host test pins the known answer 0x6F91 for the string 123456789.

Reading the records

With the channel open, a measurement notification is a list of records followed by one CRC for the characteristic value:

[size u8][flags u8][glucose SFLOAT 2][timeOffset u16]
[status u8]         if flags & 0x80
[cal/temp u8]       if flags & 0x40
[warning u8]        if flags & 0x20
[trend SFLOAT 2]    if flags & 0x01
[quality SFLOAT 2]  if flags & 0x02
...
[crc16 lo][crc16 hi]

size counts the whole record including itself. Glucose is an IEEE-11073 16-bit SFLOAT, normally exponent 0 or -1, already in mg/dL. timeOffset is minutes since the session start, and the session start is recovered as now - timeOffset from the status characteristic. Trend is in mg/dL per minute, with the app's arrow thresholds at plus and minus 1 and 2; rate-exceeded status bits override the numeric value.

The other CGM characteristics have no flags octet at all, and the app's parsers reject any other length:

CharacteristicLayoutLength
Status 2AA9timeOffset u16, 3 status octets, CRC7
Feature 2AA83 feature octets, type/location octet, CRC6
SessionRunTime 2AABhours u16, CRC4
SessionStart 2AAAyear u16, month, day, hour, minute, second, timezone, DST, CRC11

Status is a 24-bit little-endian annunciation field: one word carrying SessionStopped, CalibrationRequired, CalibrationNotAllowed, temperature alarms and rate-of-change alerts.

Two defects in this repository are worth recording because they are the same class of mistake. The firmware's status, feature and run-time parsers still assume a leading flags byte, so they misdecode frames the app accepts. And the app requires RACP responses to be exactly four bytes, [opCode][operator][operand][responseCode], with records following as separate measurement notifications; the firmware's RACP parser starts reading records at offset 3 and expects them in the same buffer.

What the tests establish

Two host test suites run without hardware. The reader's suite makes 57 checks, including P-256 ECDH, AES-128-GCM and the confirmation code against golden vectors generated with Python's cryptography library, plus a full key exchange and encrypted traffic against a mock sensor. The vectors are the independent evidence; the mock mostly proves framing and ordering, since it was written from the same specification as the client.

The simulator adds 44 checks from the other side: it implements the ACS server, runs the reader's own client through the exchange, exercises encrypted traffic both ways, re-keys after InvalidateAllEstablishedSecurity, and rejects a wrong PIN. Because it advertises as a real sensor, the official app can be pointed at it too, which is how the CRC failure and the post-exchange map switch were observed rather than merely inferred.

Open questions

The remaining unknowns are all on the physical sensor. It is unconfirmed whether the real device restricts the CGM characteristics behind ACS exactly as the simulator does, what bond type it demands, and whether it accepts a certificate issued through the enrollment API. The certificate lifetime is server-set and cannot be read from the APK. The RACP sequence-number convention is assumed to track timeOffset, and the record interval is taken to be five minutes from the sensor's own interval report. Until a real sensor is paired, those are assumptions with a clear failure mode, not established facts.