Merge pull request #2654 from Antiklesys/master
[RRG-proxmark3.git] / tools / hitag2crack / common / hitagcrypto.c
blob42e43e6f067ef7f9576ab4360fb9898140245f31
1 /***************************************************************************
2 * A copy of the GNU GPL is appended to this file. *
3 * *
4 * This licence is based on the nmap licence, and we express our gratitude *
5 * for the work that went into producing it. There is no other connection *
6 * between RFIDler and nmap either expressed or implied. *
7 * *
8 ********************** IMPORTANT RFIDler LICENSE TERMS ********************
9 * *
10 * *
11 * All references to RFIDler herein imply all it's derivatives, namely: *
12 * *
13 * o RFIDler-LF Standard *
14 * o RFIDler-LF Lite *
15 * o RFIDler-LF Nekkid *
16 * *
17 * *
18 * RFIDler is (C) 2013-2015 Aperture Labs Ltd. *
19 * *
20 * This program is free software; you may redistribute and/or modify it *
21 * under the terms of the GNU General Public License as published by the *
22 * Free Software Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE *
23 * CLARIFICATIONS AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your *
24 * right to use, modify, and redistribute this software under certain *
25 * conditions. If you wish to embed RFIDler technology into proprietary *
26 * software or hardware, we sell alternative licenses *
27 * (contact sales@aperturelabs.com). *
28 * *
29 * Note that the GPL places important restrictions on "derivative works", *
30 * yet it does not provide a detailed definition of that term. To avoid *
31 * misunderstandings, we interpret that term as broadly as copyright law *
32 * allows. For example, we consider an application to constitute a *
33 * derivative work for the purpose of this license if it does any of the *
34 * following with any software or content covered by this license *
35 * ("Covered Software"): *
36 * *
37 * o Integrates source code from Covered Software. *
38 * *
39 * o Is designed specifically to execute Covered Software and parse the *
40 * results (as opposed to typical shell or execution-menu apps, which will *
41 * execute anything you tell them to). *
42 * *
43 * o Includes Covered Software in a proprietary executable installer. The *
44 * installers produced by InstallShield are an example of this. Including *
45 * RFIDler with other software in compressed or archival form does not *
46 * trigger this provision, provided appropriate open source decompression *
47 * or de-archiving software is widely available for no charge. For the *
48 * purposes of this license, an installer is considered to include Covered *
49 * Software even if it actually retrieves a copy of Covered Software from *
50 * another source during runtime (such as by downloading it from the *
51 * Internet). *
52 * *
53 * o Links (statically or dynamically) to a library which does any of the *
54 * above. *
55 * *
56 * o Executes a helper program, module, or script to do any of the above. *
57 * *
58 * This list is not exclusive, but is meant to clarify our interpretation *
59 * of derived works with some common examples. Other people may interpret *
60 * the plain GPL differently, so we consider this a special exception to *
61 * the GPL that we apply to Covered Software. Works which meet any of *
62 * these conditions must conform to all of the terms of this license, *
63 * particularly including the GPL Section 3 requirements of providing *
64 * source code and allowing free redistribution of the work as a whole. *
65 * *
66 * As another special exception to the GPL terms, Aperture Labs Ltd. grants*
67 * permission to link the code of this program with any version of the *
68 * OpenSSL library which is distributed under a license identical to that *
69 * listed in the included docs/licenses/OpenSSL.txt file, and distribute *
70 * linked combinations including the two. *
71 * *
72 * Any redistribution of Covered Software, including any derived works, *
73 * must obey and carry forward all of the terms of this license, including *
74 * obeying all GPL rules and restrictions. For example, source code of *
75 * the whole work must be provided and free redistribution must be *
76 * allowed. All GPL references to "this License", are to be treated as *
77 * including the terms and conditions of this license text as well. *
78 * *
79 * Because this license imposes special exceptions to the GPL, Covered *
80 * Work may not be combined (even as part of a larger work) with plain GPL *
81 * software. The terms, conditions, and exceptions of this license must *
82 * be included as well. This license is incompatible with some other open *
83 * source licenses as well. In some cases we can relicense portions of *
84 * RFIDler or grant special permissions to use it in other open source *
85 * software. Please contact sales@aperturelabs.com with any such requests.*
86 * Similarly, we don't incorporate incompatible open source software into *
87 * Covered Software without special permission from the copyright holders. *
88 * *
89 * If you have any questions about the licensing restrictions on using *
90 * RFIDler in other works, are happy to help. As mentioned above, we also *
91 * offer alternative license to integrate RFIDler into proprietary *
92 * applications and appliances. These contracts have been sold to dozens *
93 * of software vendors, and generally include a perpetual license as well *
94 * as providing for priority support and updates. They also fund the *
95 * continued development of RFIDler. Please email sales@aperturelabs.com *
96 * for further information. *
97 * If you have received a written license agreement or contract for *
98 * Covered Software stating terms other than these, you may choose to use *
99 * and redistribute Covered Software under those terms instead of these. *
101 * Source is provided to this software because we believe users have a *
102 * right to know exactly what a program is going to do before they run it. *
103 * This also allows you to audit the software for security holes (none *
104 * have been found so far). *
106 * Source code also allows you to port RFIDler to new platforms, fix bugs, *
107 * and add new features. You are highly encouraged to send your changes *
108 * to the RFIDler mailing list for possible incorporation into the *
109 * main distribution. By sending these changes to Aperture Labs Ltd. or *
110 * one of the Aperture Labs Ltd. development mailing lists, or checking *
111 * them into the RFIDler source code repository, it is understood (unless *
112 * you specify otherwise) that you are offering the RFIDler Project *
113 * (Aperture Labs Ltd.) the unlimited, non-exclusive right to reuse, *
114 * modify, and relicense the code. RFIDler will always be available Open *
115 * Source, but this is important because the inability to relicense code *
116 * has caused devastating problems for other Free Software projects (such *
117 * as KDE and NASM). We also occasionally relicense the code to third *
118 * parties as discussed above. If you wish to specify special license *
119 * conditions of your contributions, just say so when you send them. *
121 * This program is distributed in the hope that it will be useful, but *
122 * WITHOUT ANY WARRANTY; without even the implied warranty of *
123 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the RFIDler *
124 * license file for more details (it's in a COPYING file included with *
125 * RFIDler, and also available from *
126 * https://github.com/ApertureLabsLtd/RFIDler/COPYING *
128 ***************************************************************************/
130 // Author: unknown.
131 // Modifications for RFIDler: Tony Naggs <tony.naggs@gmail.com>, Adam Laurie <adam@aperturelabs.com>
133 // uncomment this to build file as a standalone crypto test program
134 // #define UNIT_TEST
135 // also uncomment to include verbose debug prints
136 // #define TEST_DEBUG
138 //#include <GenericTypeDefs.h>
139 #include "hitagcrypto.h"
141 #ifdef UNIT_TEST
142 #include <stdio.h>
143 #endif
145 #if defined(UNIT_TEST) && defined(TEST_DEBUG)
146 // Note that printf format %I64x prints 64 bit ints in MS Visual C/C++.
147 // This may need changing for other compilers/platforms.
148 #define DEBUG_PRINTF(...) printf(__VA_ARGS__)
149 #else
150 #define DEBUG_PRINTF(...)
151 #endif
154 /* Brief info about NXP Hitag 1, Hitag 2, Hitag S and Hitag u (mu)
156 Hitag 125kHz RFID was created by a company called Mikron (Mikron Gesellschaft
157 fur Integrierte Mikroelektronik Mbh), of Austria, for micropayment applications.
158 At about the same time, late 1980s to early 1990s, Mikron developed the
159 similarly featured Mifare micropayment card for 13.56MHz RFID.
160 (Mikron's European Patent EP 0473569 A2 was filed 23 August 1991, with a
161 priority date of 23 Aug 1990.)
162 Mikron was subsequently acquired by Philips Semiconductors in 1995.
163 Philips Semiconductors division subsequently became NXP.
165 + Modulation read/write device -> transponder: 100 % ASK and binary pulse
166 length coding
167 + Modulation transponder -> read/write device: Strong ASK modulation,
168 selectable Manchester or Biphase coding
169 + Hitag S, Hitag µ; anti-collision procedure
170 + Fast anti-collision protocol
171 + Hitag µ; optional Cyclic Redundancy Check (CRC)
172 + Reader Talks First mode
173 + Hitag 2 & later; Transponder Talks First (TTF) mode
174 + Temporary switch from Transponder Talks First into Reader Talks First
175 (RTF) Mode
176 + Data rate read/write device to transponder: 5.2 kbit/s
177 + Data rates transponder to read/write device: 2 kbit/s, 4 kbit/s, 8 kbit/s
178 + 32-bit password feature
179 + Hitag 2, S = 32-bit Unique Identifier
180 + Hitag µ = 48-bit Unique Identifier
181 + Selectable password modes for reader / tag mutual authentication
182 (Hitag 1 has 2 pairs of keys, later versions have 1 pair)
183 + Hitag 2 & Hitag S; Selectable encrypted mode, 48 bit key
185 Known tag types:
187 HITAG 1 2048 bits total memory
189 HITAG 2 256 Bit total memory Read/Write
190 8 pages of 32 bits, inc UID (32),
191 secret key (64), password (24), config (8)
193 HITAG S 32 32 bits Unique Identifier Read Only
194 HITAG S 256 256 bits total memory Read/Write
195 HITAG S 2048 2048 bits total memory Read/Write
197 HITAG µ RO64 64 bits total memory Read Only
198 HITAG µ 128 bits total memory Read/Write
199 HITAG µ Advanced 512 bits total memory Read/Write
200 HITAG µ Advanced+ 1760 bits total memory Read/Write
202 Default 48-bit key for Hitag 2, S encryption:
203 "MIKRON" = O N M I K R
204 Key = 4F 4E 4D 49 4B 52
209 // We want the crypto functions to be as fast as possible, so optimize!
210 // The best compiler optimization in Microchip's free XC32 edition is -O1
211 #if defined(__GNUC__) && !defined(__clang__)
212 #pragma GCC optimize("O1")
213 #endif
215 // private, nonlinear function to generate 1 crypto bit
216 static uint32_t hitag2_crypt(uint64_t x);
219 // macros to pick out 4 bits in various patterns of 1s & 2s & make a new number
220 #define pickbits2_2(S, A, B) ( ((S >> A) & 3) | ((S >> (B - 2)) & 0xC) )
221 #define pickbits1x4(S, A, B, C, D) ( ((S >> A) & 1) | ((S >> (B - 1)) & 2) | \
222 ((S >> (C - 2)) & 4) | ((S >> (D - 3)) & 8) )
223 #define pickbits1_1_2(S, A, B, C) ( ((S >> A) & 1) | ((S >> (B - 1)) & 2) | \
224 ((S >> (C - 2)) & 0xC) )
225 #define pickbits2_1_1(S, A, B, C) ( ((S >> A) & 3) | ((S >> (B - 2)) & 4) | \
226 ((S >> (C - 3)) & 8) )
227 #define pickbits1_2_1(S, A, B, C) ( ((S >> A) & 1) | ((S >> (B - 1)) & 6) | \
228 ((S >> (C - 3)) & 8) )
231 static uint32_t hitag2_crypt(uint64_t x) {
232 const uint32_t ht2_function4a = 0x2C79; // 0010 1100 0111 1001
233 const uint32_t ht2_function4b = 0x6671; // 0110 0110 0111 0001
234 const uint32_t ht2_function5c = 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
235 uint32_t bitindex;
237 bitindex = (ht2_function4a >> pickbits2_2(x, 1, 4)) & 1;
238 bitindex |= ((ht2_function4b << 1) >> pickbits1_1_2(x, 7, 11, 13)) & 0x02;
239 bitindex |= ((ht2_function4b << 2) >> pickbits1x4(x, 16, 20, 22, 25)) & 0x04;
240 bitindex |= ((ht2_function4b << 3) >> pickbits2_1_1(x, 27, 30, 32)) & 0x08;
241 bitindex |= ((ht2_function4a << 4) >> pickbits1_2_1(x, 33, 42, 45)) & 0x10;
243 DEBUG_PRINTF("hitag2_crypt bitindex = %02x\n", bitindex);
244 return (ht2_function5c >> bitindex) & 1;
248 * Parameters:
249 * Hitag_State* pstate - output, internal state after initialisation
250 * uint64_t sharedkey - 48 bit key shared between reader & tag
251 * uint32_t serialnum - 32 bit tag serial number
252 * uint32_t initvector - 32 bit random IV from reader, part of tag authentication
254 void hitag2_init(Hitag_State *pstate, uint64_t sharedkey, uint32_t serialnum, uint32_t initvector) {
255 // init state, from serial number and lowest 16 bits of shared key
256 uint64_t state = ((sharedkey & 0xFFFF) << 32) | serialnum;
258 // mix the initialisation vector and highest 32 bits of the shared key
259 initvector ^= (uint32_t)(sharedkey >> 16);
261 // move 16 bits from (IV xor Shared Key) to top of uint64_t state
262 // these will be XORed in turn with output of the crypto function
263 state |= (uint64_t) initvector << 48;
264 initvector >>= 16;
266 // unrolled loop is faster on PIC32 (MIPS), do 32 times
267 // shift register, then calc new bit
268 state >>= 1;
269 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
270 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
271 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
272 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
273 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
274 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
275 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
276 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
278 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
279 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
280 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
281 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
282 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
283 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
284 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
285 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
287 // highest 16 bits of IV XOR Shared Key
288 state |= (uint64_t) initvector << 47;
290 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
291 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
292 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
293 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
294 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
295 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
296 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
297 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
299 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
300 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
301 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
302 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
303 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
304 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
305 state = (state >> 1) ^ (uint64_t) hitag2_crypt(state) << 46;
306 state ^= (uint64_t) hitag2_crypt(state) << 47;
308 DEBUG_PRINTF("hitag2_init result = %012I64x\n", state);
309 pstate->shiftreg = state;
310 /* naive version for reference, LFSR has 16 taps
311 pstate->lfsr = state ^ (state >> 2) ^ (state >> 3) ^ (state >> 6)
312 ^ (state >> 7) ^ (state >> 8) ^ (state >> 16) ^ (state >> 22)
313 ^ (state >> 23) ^ (state >> 26) ^ (state >> 30) ^ (state >> 41)
314 ^ (state >> 42) ^ (state >> 43) ^ (state >> 46) ^ (state >> 47);
317 // optimise with one 64-bit intermediate
318 uint64_t temp = state ^ (state >> 1);
319 pstate->lfsr = state ^ (state >> 6) ^ (state >> 16)
320 ^ (state >> 26) ^ (state >> 30) ^ (state >> 41)
321 ^ (temp >> 2) ^ (temp >> 7) ^ (temp >> 22)
322 ^ (temp >> 42) ^ (temp >> 46);
328 * Return up to 32 crypto bits.
329 * Last bit is in least significant bit, earlier bits are shifted left.
330 * Note that the Hitag transmission protocol is least significant bit,
331 * so we may want to change this, or add a function, that returns the
332 * crypto output bits in the other order.
334 * Parameters:
335 * Hitag_State* pstate - in/out, internal cipher state after initialisation
336 * uint32_t steps - number of bits requested, (capped at 32)
338 uint32_t hitag2_nstep(Hitag_State *pstate, uint32_t steps) {
339 uint64_t state = pstate->shiftreg;
340 uint32_t result = 0;
341 uint64_t lfsr = pstate->lfsr;
343 if (steps == 0)
344 return 0;
346 // if (steps > 32)
347 // steps = 32;
349 do {
350 // update shift registers
351 if (lfsr & 1) {
352 state = (state >> 1) | 0x800000000000;
353 lfsr = (lfsr >> 1) ^ 0xB38083220073;
355 // accumulate next bit of crypto
356 result = (result << 1) | hitag2_crypt(state);
357 } else {
358 state >>= 1;
359 lfsr >>= 1;
361 result = (result << 1) | hitag2_crypt(state);
363 } while (--steps);
365 DEBUG_PRINTF("hitag2_nstep state = %012I64x, result %02x\n", state, result);
366 pstate->shiftreg = state;
367 pstate->lfsr = lfsr;
368 return result;
371 // end of crypto core, revert to default optimization level
372 #if defined(__GNUC__) && !defined(__clang__)
373 #pragma GCC reset_options
374 #endif