aboutsummaryrefslogtreecommitdiffhomepage
path: root/DPA.ipynb
blob: 3b5a455ba56b8185c5f6d211b6c57358566b96e6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Differential Power Analysis"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook demonstrates the functionality of the `DPA` class, which implements Differential Power Analysis side-channel attack. The attack is first performed and evaluated on leakage traces simulated by the `LeakageTarget` class and subsequently on leakage traces simulated by the `EmulatorTarget` class."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Initialisation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyecsca.ec.mult import LTRMultiplier\n",
    "from pyecsca.ec.mod import mod\n",
    "from pyecsca.ec.point import Point, InfinityPoint\n",
    "from pyecsca.ec.model import ShortWeierstrassModel\n",
    "from pyecsca.ec.curve import EllipticCurve\n",
    "from pyecsca.ec.params import DomainParameters\n",
    "from pyecsca.sca.attack.DPA import DPA\n",
    "from pyecsca.sca.attack.CPA import CPA\n",
    "from pyecsca.sca.attack.leakage_model import HammingWeight\n",
    "from pyecsca.sca.target.leakage import LeakageTarget\n",
    "from pyecsca.sca.trace import Trace\n",
    "from pyecsca.sca.trace.edit import stretch\n",
    "from pyecsca.sca.trace.process import rolling_mean\n",
    "from pyecsca.codegen.client import EmulatorTarget\n",
    "from rainbow import TraceConfig\n",
    "from rainbow.leakage_models import HammingWeight\n",
    "from random import randint\n",
    "import holoviews as hv\n",
    "import multiprocessing as mp\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hv.extension(\"bokeh\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We first define the elliptic curve parameters we are going to be using for the demonstration."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = ShortWeierstrassModel()\n",
    "coords = model.coordinates[\"projective\"]\n",
    "p = 0xd7d1247f\n",
    "a = mod(0xa4a44016, p)\n",
    "b = mod(0x73f76716, p)\n",
    "n = 0xd7d2a475\n",
    "h = 1\n",
    "gx, gy, gz = mod(0x54eed6d7, p), mod(0x6f1e55ac, p), mod(1, p)\n",
    "generator = Point(coords, X=gx, Y=gy, Z=gz)\n",
    "neutral = InfinityPoint(coords)\n",
    "\n",
    "curve = EllipticCurve(model, coords, p, neutral, {\"a\": a, \"b\": b})\n",
    "params = DomainParameters(curve, generator, n, h)\n",
    "\n",
    "add = coords.formulas[\"add-1998-cmo\"]\n",
    "dbl = coords.formulas[\"dbl-1998-cmo\"]\n",
    "scl = coords.formulas[\"z\"]\n",
    "\n",
    "mult = LTRMultiplier(add, dbl, None)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We create and initialize an instance of the `LeakageTarget` class with the above elliptic curve parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "target = LeakageTarget(model, coords, mult, HammingWeight())\n",
    "target.set_params(params)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using the attack, we will try to recover an 8-bit scalar used in the scalar multiplication operation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scalar_bit_length = 8\n",
    "secret_scalar = 229"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will perform scalar multiplication on 10 000 random points on the curve and simulate 10 000 corresponding leakage traces, which we will then use to evaluate the attack. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_of_traces = 2000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "generated_points, generated_traces = target.simulate_scalar_mult_traces(num_of_traces, secret_scalar)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performing the attack"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We create and initialize an instance of the `DPA` class containing the attack's implementation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mult.init(params, params.generator)\n",
    "real_pub_key = mult.multiply(secret_scalar)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dpa = DPA(generated_points, generated_traces, mult, params)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We perform the attack and test that the scalar we recovered is correct."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "recovered_scalar = dpa.perform(scalar_bit_length, real_pub_key)\n",
    "print(recovered_scalar)\n",
    "print(recovered_scalar == secret_scalar)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can visualize the differences of means calculated during the attack. Below are shown DOMs for correct and incorrect guess of the second bit of the scalar, followed by DOMs of correct guesses for fourth and sixth bit of the scalar to show the location of peeks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Correct difference of means when guessing 2. bit (guessed scalar 192 = 1100 0000)\n",
    "dpa.plot_difference_of_means(dpa.doms['guess_one'][0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Incorrect difference of means when guessing 2. bit (guessed scalar 128 = 1000 0000)\n",
    "dpa.plot_difference_of_means(dpa.doms['guess_zero'][0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Correct difference of means when guessing 4. bit (guessed scalar 224 = 1110 0000)\n",
    "dpa.plot_difference_of_means(dpa.doms['guess_zero'][2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Correct difference of means when guessing 6. bit (guessed scalar 229 = 1110 0100)\n",
    "dpa.plot_difference_of_means(dpa.doms['guess_one'][-2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluating the effectiveness of the attack"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will evaluate how the success rate of the attack increases with an increasing number of traces and subsequently evaluate how the success rate for a fixed number of traces changes with increasing noise. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To have a convenient way of generating random subsets, we define the following function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def select_random_sample(size, points, traces):\n",
    "    sample_points = []\n",
    "    sample_traces = []\n",
    "    selected_numbers = []\n",
    "    for _ in range(size):\n",
    "        num = randint(0, num_of_traces - 1)\n",
    "        if num not in selected_numbers:\n",
    "            selected_numbers.append(num)\n",
    "        sample_points.append(points[num])\n",
    "        sample_traces.append(traces[num])\n",
    "    return sample_points, sample_traces"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Success rate with changing number of traces"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We take subsets of different sizes and plot the success rate of the DPA corresponding to them. For each size, we perform the DPA 100 times on 100 generated subsets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def DPA_traces(points, traces, sample_size, scalar_length, pub_key, multiplier, domain_params):\n",
    "    sample_points, sample_traces = select_random_sample(sample_size, points, traces)\n",
    "    sample_dpa = DPA(sample_points, sample_traces, multiplier, domain_params)\n",
    "    recovered = sample_dpa.perform(scalar_length, pub_key)\n",
    "    return recovered == secret_scalar\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number_of_subsets = 17\n",
    "successes_rates_traces = []\n",
    "number_of_samples = [x * 100 for x in range(1, number_of_subsets)]\n",
    "for num in number_of_samples:\n",
    "    with mp.Pool() as pool:\n",
    "        result_objects = [pool.apply_async(DPA_traces, args=(generated_points, generated_traces, num, scalar_bit_length, \n",
    "                                                             real_pub_key, mult, params)) for _ in range(100)]\n",
    "        results = [result.get() for result in result_objects]\n",
    "    successes_rates_traces.append(sum(results) / 100)\n",
    "    print(f\"done for {num}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We plot the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(number_of_samples, successes_rates_traces, color='black')\n",
    "plt.ylim([0, 1])\n",
    "plt.xlabel('number of traces')\n",
    "plt.ylabel('DPA success rate')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Success rate with fixed number of traces and changing noise"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As we now know the the minimum amount of traces needed for 100% success rate, we generate 100 subsets with that amount of traces and perform DPA for each subset. We do this multiple times with different amount of noise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def normalize_trace(trace: Trace):\n",
    "    min_val = np.min(trace.samples)\n",
    "    max_val = np.max(trace.samples)\n",
    "    scaled_samples = (trace.samples - min_val) / (max_val - min_val) \n",
    "    trace.samples = scaled_samples   \n",
    "\n",
    "def DPA_noise(points, traces, sample_size, standard_deviation, scalar_length, pub_key, multiplier, domain_params):\n",
    "    sample_points, sample_traces = select_random_sample(sample_size, points, traces)\n",
    "    for trace in sample_traces:\n",
    "        normalize_trace(trace)\n",
    "    noise = np.random.normal(0, standard_deviation, sample_traces[0].samples.shape)\n",
    "    for trace in sample_traces:\n",
    "        trace.samples = trace.samples + noise\n",
    "    sample_dpa = DPA(sample_points, sample_traces, multiplier, domain_params)\n",
    "    recovered = sample_dpa.perform(scalar_length, pub_key)\n",
    "    return recovered == secret_scalar\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number_of_subsets = 17\n",
    "successes_rates_noise = []\n",
    "sample_size = 1600\n",
    "noise_sds = [0.05 * x for x in range(number_of_subsets)] \n",
    "for sd in noise_sds:\n",
    "    with mp.Pool() as pool:\n",
    "        result_objects = [pool.apply_async(DPA_noise, args=(generated_points, generated_traces, sample_size, sd, scalar_bit_length, \n",
    "                                                             real_pub_key, mult, params)) for _ in range(100)]\n",
    "        results = [result.get() for result in result_objects]\n",
    "    successes_rates_noise.append(sum(results) / 100)\n",
    "    print(f\"done for {sd}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We plot the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(noise_sds, successes_rates_noise, color='black')\n",
    "plt.ylim([0, 1])\n",
    "plt.xlabel('Gaussian noise (standard deviation)')\n",
    "plt.ylabel('DPA success rate')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## DPA on leakage traces simulated by `EmulatorTarget`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We gather leakage traces simulated by the `EmulatorTarget`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('/data/xbatora/traces_8bit.pickle', 'rb') as f:\n",
    "    traces_emulator = pickle.load(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "points_emulator = []\n",
    "max_length = 0\n",
    "for trace in traces_emulator:\n",
    "    if(len(trace) > max_length):\n",
    "        max_length = len(trace)\n",
    "    points_emulator.append(Point(coords, **trace.meta['coords']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The traces are not equally long. We `stretch` them to the same length. This should also reduce misalignment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stretched_traces = []\n",
    "for trace in traces_emulator:\n",
    "    stretched_traces.append(stretch(trace, max_length))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We recover the second bit of the scalar. We know it should equal one, so we plot its corresponding DOM that should show a peak."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "recovered_scalar = 128 #1000 0000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dpa_emulator = DPA(points_emulator, stretched_traces, mult, params)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "recovered_scalar = 128 #1000 0000\n",
    "res = dpa_emulator.recover_bit(recovered_scalar, 1, scalar_bit_length, real_pub_key)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The peak is not visible"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dpa_emulator.plot_difference_of_means(dpa_emulator.doms['guess_one'][0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The peak is not visible due to a significant misalignment. We apply rolling mean to the traces, which should reduce the misalignment. We perform the DPA again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rolling_mean_traces = []\n",
    "for trace in stretched_traces:\n",
    "    rolling_mean_traces.append(rolling_mean(trace, 3000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dpa_emulator = DPA(points_emulator, rolling_mean_traces, mult, params)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "recovered_scalar = 128 #1000 0000\n",
    "res = dpa_emulator.recover_bit(recovered_scalar, 1, scalar_bit_length, real_pub_key)\n",
    "print(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dpa_emulator.plot_difference_of_means(dpa_emulator.doms['guess_one'][0])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}