-
Notifications
You must be signed in to change notification settings - Fork 112
/
BGEAttack.cpp
1773 lines (1517 loc) · 65.6 KB
/
BGEAttack.cpp
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* BGEAttack.cpp
*
* Created on: Apr 7, 2013
* Author: ph4r05
*/
#include "BGEAttack.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
namespace wbacr {
namespace attack {
BGEAttack::BGEAttack() {
this->coding = NULL;
this->wbaes = NULL;
}
BGEAttack::~BGEAttack() {
;
}
using namespace std;
using namespace NTL;
using namespace boost;
using namespace wbacr::attack;
using namespace wbacr::laeqv;
const int BGEAttack::shiftIdentity[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
const int BGEAttack::shiftT2[16] =
{0, 4, 8, 12,
13, 1, 5, 9,
10, 14, 2, 6,
7, 11, 15, 3
};
std::string composeFunction(GF256_func_t f, GF256_func_t g){
unsigned int x; // warning, if is type BYTE, then it will overflow and loop forever
fction_t nf;
for(x=0; x<=(GF256-1); x++){
//cout << "; X=" << x << endl;
//cout << "; g["<<CHEX(x)<<"] = " CHEX(g[x]) << ";" << endl;
//cout << "; f[g["<<CHEX(x)<<"]] = " CHEX(f[g[x]]) << ";" << endl;
nf.f[x] = f[g[x]];
nf.finv[f[g[x]]] = x;
}
return hashFunction(nf.f);
}
void BGEAttack::Rbox(W128b& state, bool encrypt, int r, bool noShift, int colMask2compute){
int i=0;
W32b ires[N_BYTES]; // intermediate result for T2,T3-boxes
W128b ares[N_BYTES]; // intermediate result for T1-boxes
// encryption/decryption dependent operations and tables
const int (&shiftOp)[N_BYTES] = noShift ? this->shiftIdentity : (encrypt ? (this->wbaes->shiftRows) : (this->wbaes->shiftRowsInv));
W32XTB (&edXTab)[N_ROUNDS][N_SECTIONS][N_XOR_GROUPS] = encrypt ? (this->wbaes->eXTab) : (this->wbaes->dXTab);
W32XTB (&edXTabEx)[2][15][4] = encrypt ? (this->wbaes->eXTabEx) : (this->wbaes->dXTabEx);
AES_TB_TYPE1 (&edTab1)[2][N_BYTES] = encrypt ? (this->wbaes->eTab1) : (this->wbaes->dTab1);
AES_TB_TYPE2 (&edTab2)[N_ROUNDS][N_BYTES] = encrypt ? (this->wbaes->eTab2) : (this->wbaes->dTab2);
AES_TB_TYPE3 (&edTab3)[N_ROUNDS][N_BYTES] = encrypt ? (this->wbaes->eTab3) : (this->wbaes->dTab3);
#ifdef AES_BGE_ATTACK
GF256_func_t (&edOutputBijection)[N_ROUNDS][N_BYTES] = encrypt ? (this->wbaes->eOutputBijection) : (this->wbaes->dOutputBijection);
#endif
// Last round = special case. Just T1 boxes && 128-bot XOR cascade
if (r==(N_ROUNDS-1)){
for(i=0; i<N_BYTES; i+=4){
W128CP(ares[i+0], edTab1[1][i+0][state.B[shiftOp[i/4+0*4]]]);
W128CP(ares[i+1], edTab1[1][i+1][state.B[shiftOp[i/4+1*4]]]);
W128CP(ares[i+2], edTab1[1][i+2][state.B[shiftOp[i/4+2*4]]]);
W128CP(ares[i+3], edTab1[1][i+3][state.B[shiftOp[i/4+3*4]]]);
}
// and finally compute XOR cascade again, now for T1[1] - output T1
// 1st level of XORs
for(i=0;i<N_BYTES;i+=2){
op8xor_128(ares[i+0], ares[i+1], edXTabEx[1][i/2], ares[i+0]); // 1 xor 2 --> 1
}
// Finish XOR cascade by hand
op8xor_128(ares[0], ares[2], edXTabEx[1][8], ares[0]); // 0 xor 2 --> 0
op8xor_128(ares[4], ares[6], edXTabEx[1][9], ares[4]); // 4 xor 6 --> 4
op8xor_128(ares[8], ares[10], edXTabEx[1][10], ares[8]); // 8 xor 10 --> 8
op8xor_128(ares[12], ares[14], edXTabEx[1][11], ares[12]); // 12 xor 14 --> 12
op8xor_128(ares[0], ares[4], edXTabEx[1][12], ares[0]); // 0 xor 4 --> 0
op8xor_128(ares[8], ares[12], edXTabEx[1][13], ares[8]); // 8 xor 12 --> 8
op8xor_128(ares[0], ares[8], edXTabEx[1][14], ares[0]); // 0 xor 8 --> 0
for(i=0; i<N_BYTES; i++){
state.B[i] = ares[0].B[idxTranspose(i)];
}
} else {
// Firt round -> need to apply T1 boxes & 128-bit XOR cascade before
if (r==0){
// At first we have to put input to T1 boxes directly, no shift rows
// compute result to ares[16]
for(i=0; i<N_BYTES; i++){
// Note: Tbox is indexed by cols, state by rows - transpose needed here
W128CP(ares[i], edTab1[0][i][state.B[idxTranspose(i)]]);
}
// 1st level of XORs
for(i=0;i<N_BYTES;i+=2){
op8xor_128(ares[i+0], ares[i+1], edXTabEx[0][i/2], ares[i+0]); // 1 xor 2 --> 1
}
// Finish XOR cascade
op8xor_128(ares[0], ares[2], edXTabEx[0][8], ares[0]); // 0 xor 2 --> 0
op8xor_128(ares[4], ares[6], edXTabEx[0][9], ares[4]); // 4 xor 6 --> 4
op8xor_128(ares[8], ares[10], edXTabEx[0][10], ares[8]); // 8 xor 10 --> 8
op8xor_128(ares[12], ares[14], edXTabEx[0][11], ares[12]); // 12 xor 14 --> 12
op8xor_128(ares[0], ares[4], edXTabEx[0][12], ares[0]); // 0 xor 4 --> 0
op8xor_128(ares[8], ares[12], edXTabEx[0][13], ares[8]); // 8 xor 12 --> 8
op8xor_128(ares[0], ares[8], edXTabEx[0][14], ares[0]); // 0 xor 8 --> 0
W128CP(state, ares[0]);
}
// Perform rest of the operations on 4 tuples.
for(i=0; i<N_BYTES; i+=4){
// Apply type 2 tables to all bytes, counting also shift rows selector.
// One section ~ 1 column of state array, so select 1 column, first will
// have indexes 0,4,8,12. Also take ShiftRows() into consideration.
ires[i+0].l = edTab2[r][i+0][state.B[shiftOp[i/4+0*4]]].l;
ires[i+1].l = edTab2[r][i+1][state.B[shiftOp[i/4+1*4]]].l;
ires[i+2].l = edTab2[r][i+2][state.B[shiftOp[i/4+2*4]]].l;
ires[i+3].l = edTab2[r][i+3][state.B[shiftOp[i/4+3*4]]].l;
// XOR results of T2 boxes
op8xor(ires[i+0], ires[i+1], edXTab[r][i/4][0], ires[i+0]); // 1 xor 2
op8xor(ires[i+2], ires[i+3], edXTab[r][i/4][1], ires[i+2]); // 3 xor 4
op8xor(ires[i+0], ires[i+2], edXTab[r][i/4][2], ires[i+0]); // (1 xor 2) xor (3 xor 4) - next XOR stage
// Apply T3 boxes, valid XOR results are in ires[0], ires[4], ires[8], ires[12]
// Start from the end, because in ires[i] is our XORing result.
ires[i+3].l = edTab3[r][i+3][ires[i].B[3]].l;
ires[i+2].l = edTab3[r][i+2][ires[i].B[2]].l;
ires[i+1].l = edTab3[r][i+1][ires[i].B[1]].l;
ires[i+0].l = edTab3[r][i+0][ires[i].B[0]].l;
// Apply XORs again, now on T3 results
// Copy results back to state
op8xor(ires[i+0], ires[i+1], edXTab[r][i/4][3], ires[i+0]); // 1 xor 2
op8xor(ires[i+2], ires[i+3], edXTab[r][i/4][4], ires[i+2]); // 3 xor 4
op8xor(ires[i+0], ires[i+2], edXTab[r][i/4][5], ires[i+0]); // (1 xor 2) xor (3 xor 4) - next XOR stage
}
//
// Copy results back to state
// ires[i] now contains 32bit XOR result
// We have to copy result to column...
for(i=0; i<N_BYTES; i+=4){
state.B[i/4+ 0] = ires[i].B[0];
state.B[i/4+ 4] = ires[i].B[1];
state.B[i/4+ 8] = ires[i].B[2];
state.B[i/4+12] = ires[i].B[3];
}
}
#ifdef AES_BGE_ATTACK
// If we are performing attack, we modified output bijection for 1 byte from 2 concatenated 4x4 bijections to one 8x8
for(i=0; i<N_BYTES; i+=4){
state.B[i/4+ 0] = edOutputBijection[r][i/4+ 0][state.B[i/4+ 0]];
state.B[i/4+ 4] = edOutputBijection[r][i/4+ 4][state.B[i/4+ 4]];
state.B[i/4+ 8] = edOutputBijection[r][i/4+ 8][state.B[i/4+ 8]];
state.B[i/4+12] = edOutputBijection[r][i/4+12][state.B[i/4+12]];
}
#endif
}
void BGEAttack::recoverPsi(Sset_t & S){
Rmap_t R;
int e = 1;
// copy function map - writable copy (removable); fction map is hash -> idx
fctionMap_t Stmp = S.fmap;
// R = {'id', ['00']}; psi[id] = 0
// R is fIdx -> beta
R.insert(Rmap_elem_t(0,0));
S.psi[0] = 0;
// remove identity function from set
Stmp.erase(S.fctions[0].hash);
// start finding vector base & psi
while(R.size() < GF256 && Stmp.size() > 0){
// S <- S \ {f} // pick f from S and remove from S
fctionMap_t::iterator it1 = Stmp.begin();
BYTE fIdx = it1->second;
Stmp.erase(it1);
// if is already generated by some base, skip it
if (R.count(fIdx)>0) continue;
S.psi[fIdx] = e;
//cout << "Taking fIdx="<<CHEX(fIdx)<<" as new base element e_i="<<CHEX(e)<<endl;
Rmap_t Rcopy = R;
for(Rmap_t::const_iterator it=Rcopy.begin(); it != Rcopy.end(); ++it){
// Now compute elements (f \ocirc g, [e] ^ [n])
// Functions should form vector space thus composition two of them should
// result in another function from vector space. Thus compute hash of composition.
// DEBUG
//cout << " fIdx hash = " << S.fctions[fIdx].hash << endl;
//cout << " firsthash = " << S.fctions[it->first].hash << endl;
std::string nhash = composeFunction(S.fctions[fIdx].f, S.fctions[it->first].f);
// hash should be contained in Stmp
if (S.fmap.count(nhash)==0){
cerr << "nhash["<<nhash<<"] was not found in VectorSpace; composition f \\ocirc g = " << CHEX(fIdx) << " o " << CHEX(it->first)
<< "; betarepr: e="<<CHEX(e)<<"; ni="<<CHEX(it->second)<< endl;
assert(S.fmap.count(nhash)>0);
}
BYTE nIdx = S.fmap[nhash];
R.insert(Rmap_elem_t(nIdx, e ^ it->second));
S.psi[nIdx] = e ^ it->second;
}
e *= 0x2; // base move
}
if (R.size() < GF256 && Stmp.size() == 0){
cerr << "Something bad happened, S is empty, R does not span whole vector space. size=" << R.size() << endl;
}
}
int BGEAttack::deriveBset(Bset & bset, GenericAES & aes, bool permissive){
struct coef_t {
GF2E gfCoef;
BYTE intCoef;
GF2E gfCoefInv;
BYTE intCoefInv;
short int count; // number of occurences in one column in mixcol matrix
};
int dIdxs=0; // number of distincs indexes in one column in mixcol
struct coef_t coefs[4];
boost::unordered_map<BYTE, int> coefsMap; // simple map: index -> array of indexes
// Determine coefficients used in MixCol in current AES used, compute inverses
for(int i=0; i<4; i++){
GF2E gfCoef = aes.mixColMat[i][0];
BYTE curCoef = (BYTE) getLong(gfCoef);
if(coefsMap.count(curCoef)==0){
coefs[dIdxs].gfCoef = gfCoef;
coefs[dIdxs].intCoef = curCoef;
inv(coefs[dIdxs].gfCoefInv, gfCoef);
coefs[dIdxs].intCoefInv = (BYTE) getLong(coefs[dIdxs].gfCoefInv);
coefs[dIdxs].count=1;
coefsMap.insert(std::pair<BYTE,int>(curCoef, dIdxs++));
} else {
coefs[coefsMap[curCoef]].count++;
}
}
// just use MixCol matrix rows - more strict variant
if (permissive==false){
for(int i=0; i<4; i++){
int a = coefsMap[(BYTE)getLong(aes.mixColMat[i][0])];
int c = coefsMap[(BYTE)getLong(aes.mixColMat[i][1])];
for(int j=0; j<4; j++){
if (i==j) continue;
int d = coefsMap[(BYTE)getLong(aes.mixColMat[j][0])];
int b = coefsMap[(BYTE)getLong(aes.mixColMat[j][1])];
GF2E beta = (coefs[a].gfCoef * coefs[b].gfCoef) * (coefs[c].gfCoefInv * coefs[d].gfCoefInv);
BYTE intBeta = (BYTE) getLong(beta);
if (doCout) cout << "i="<<i<<"; Beta=["<<CHEX(intBeta)
<<"]; a="<<CHEX(coefs[a].intCoef)
<<"; b="<<CHEX(coefs[b].intCoef)
<<"; c="<<CHEX(coefs[c].intCoef) << ", inv="<<CHEX(coefs[c].intCoefInv)
<<"; d="<<CHEX(coefs[d].intCoef) << ", inv="<<CHEX(coefs[d].intCoefInv)<<endl;
if (bset.count(intBeta)==0) bset.insert(intBeta);
}
}
} else {
// Now generate combinations, 4*4*4*4 possibilities, I want to avoid 4 nested for loops, so with just one
for(int i=0; i<GF256; i++){
int a = i & 0x3; // index
int b = (i >> 2) & 0x3;
int c = (i >> 4) & 0x3; // c is from same col as a, c is inverse
int d = (i >> 6) & 0x3; // d is from same col as b, d is inverse
if (a>=dIdxs || b>=dIdxs || c>=dIdxs || d>=dIdxs) continue; // in case there are some coefs with count>1
if (a==c && coefs[a].count==1) continue; // they are from same col, can have same value only if count is bigger than 1
if (b==d && coefs[b].count==1) continue; // they are from same col, can have same value only if count is bigger than 1
if (a==d && coefs[a].count==1) continue; // they are from same row, can have same value only if count is bigger than 1
if (b==c && coefs[b].count==1) continue; // they are from same row, can have same value only if count is bigger than 1
if (a==d && b==c) continue; // not 2 rows same
GF2E beta = (coefs[a].gfCoef * coefs[b].gfCoef) * (coefs[c].gfCoefInv * coefs[d].gfCoefInv);
BYTE intBeta = (BYTE) getLong(beta);
if (doCout) cout << "i="<<i<<"; Beta=["<<CHEX(intBeta)
<<"]; a="<<CHEX(coefs[a].intCoef)
<<"; b="<<CHEX(coefs[b].intCoef)
<<"; c="<<CHEX(coefs[c].intCoef) << ", inv="<<CHEX(coefs[c].intCoefInv)
<<"; d="<<CHEX(coefs[d].intCoef) << ", inv="<<CHEX(coefs[d].intCoefInv)<<endl;
if (bset.count(intBeta)==0) bset.insert(intBeta);
}
}
return 0;
}
NTL::GF2X BGEAttack::characteristicPolynomial(mat_GF2X_t & m){
// This is recursive function, so if size is 2, return result directly
if (m.n==1){
return m.x[0][0]; // should never reach this point, but lets be defensive
} else if (m.n==2){
return (m.x[0][0] * m.x[1][1]) + (m.x[0][1] * m.x[1][0]);
}
NTL::GF2X poly = GF2XFromLong(0, 9);
// Recursive expansion by rows
mat_GF2X_t nm;
nm.n = m.n-1;
for(int k=0; k<m.n; k++){
// optimization, multiplication by zero - save recursion steps
if (m.x[0][k]==GF2X::zero()) continue;
// create submatrix, we expand every time by first row
for(int i=1; i<m.n; i++){
for(int j=0,col=0; j<m.n; j++){
if (j==k) continue;
nm.x[i-1][col++] = m.x[i][j];
}
}
poly = poly + m.x[0][k] * characteristicPolynomial(nm);
}
return poly;
}
NTL::GF2X BGEAttack::characteristicPolynomial(mat_GF2 & m){
mat_GF2X_t subMatrix;
int n = m.NumRows();
subMatrix.n=n;
// Transform to GF2X matrix with variable on main diagonal
NTL::GF2X var = GF2XFromLong(2, 9);
assert(m.NumCols()==n); // we can do this only for square matrix
if (n==1) return (m[0][0] + var); // such a degenerate case
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
NTL::GF2X cur = GF2XFromLong(m[i][j] == NTL::GF2::zero() ? 0:1, 9);
subMatrix.x[i][j] = i==j ? (cur+var) : cur;
}
}
return characteristicPolynomial(subMatrix);
}
int BGEAttack::proposition1(affineEquiv_t & ret, int r, int col, int syi, int syj, int sx){
GF256_func_t yi, yj, yj_inv; // pre-computed functions
W128b state;
for(int x=0; x<=0xff; x++){
memset(&state, 0, sizeof(state)); // put 0 everywhere
state.B[0+4*sx]=x; state.B[1+4*sx]=x; // init with x values for y_0 in each column
state.B[2+4*sx]=x; state.B[3+4*sx]=x; // recall that state array is indexed by rows.
this->Rbox(state, true, r, true); // perform R box computation on input & output values
yi[x] = state.B[col + 4*syi]; //yi_inv[yi[x]] = x;
yj[x] = state.B[col + 4*syj];
yj_inv[yj[x]] = x;
}
// We are looking for relation in a form:
// yi(x, 00, 00, 00) ^ c = L(yj(x, 00, 00, 00))
//
//
// Thus we are iterating by affine constant
int c;
for(c=0; c<=0xff; c++){
// We are looking for linear relation between yi+c and yj. Thus just get values for L(e1), ..., L(e8)
affineEquiv_t L;
L.c = c;
L.L.SetDims(8,8); // mat_GF2 must be initialized to certain size before use
L.Linv.SetDims(8,8); // mat_GF2 must be initialized to certain size before use
L.Lm[0] = 0; // must always hold for linear mapping
// Problem is to find L:
// yi(x, 00, 00, 00) ^ c = L(yj(x, 00, 00, 00))
// It is easy to see that L is already defined if we have values for yi, yj, we just
// have to:
// 1. determine transformation for base vectors e1,...,e8
// 2. test whether these transformation holds linearity property for whole space spanned by these base vectors
//
// Observe x is same for yi, yj, thus: a.) determine inverse for yj[x] = e_i; b.) L[ei] = yi[x] + c
for(int i=0; i<8; i++){
int lei = yi[yj_inv[1<<i]] ^ c;
L.Lm[1<<i] = lei;
L.Lminv[lei] = 1<<i;
// build transformation matrix
colVectorT(lei, L.L, i);
}
// If transformation L is linear, then it has to have proper matrix inverse and determinant!=0
GF2 determinant;
NTL::inv(determinant, L.Linv, L.L);
if (determinant==GF2::zero()){
continue; // matrix is not invertible -> not linear
}
// Now check whether already determined mapping is linear for whole space, just check.
bool works = true;
for(int x=0; x<=0xff; x++){
BYTE ix = yj[x];
BYTE iy = yi[x] ^ c;
mat_GF2 mx = colVector(ix); // mx for L * mx
mat_GF2 my = colVector(iy); // my for my =? L * mx
if ((L.L * mx) != my){
works=false;
break;
}
L.Lm[ix] = iy;
L.Lminv[iy] = ix;
}
// mapping is ok, return it
if (works){
ret = L;
return 1;
}
}
return 0; // not found
}
int BGEAttack::proposition2(mat_GF2 & L, baseVectors_t & out, mat_GF2 beta){
// We have matrix L and matrix Beta, following equation holds from proposition 2:
//
// L * A~ = A~ * beta = R
//
// A~ is 8x8 matrix, has 64 elements. We take every such element as variable and
// we are going to construct 64 equations with 64 unknowns and to solve this system
// to obtain nontrivial solution, that will be returned as A~.
//
// Matrix multiplication gives us those equations. I will show this on first element of R matrix
//
// r_{00} = l_{00}*a_{00} + l_{01}*a_{10} + ... + l_{07}*a_{70} = a_{00}*b_{00} + a_{01}*b_{10} + ... + a_{07}*b_{70}
// r_{ij} = \Sum_{k} l_{ik} * a_{kj} = \Sum_{k} a_{ik} * b_{kj}
mat_GF2 eqSystem(INIT_SIZE, 64, 64);
// Iterate over all 64 elements of R matrix and generate new equation in each iteration.
int row=0;
for(int i=0; i<8; i++){
for(int j=0; j<8; j++, row++){
for(int k=0; k<64; k++) eqSystem[row][k] = GF2::zero();
// 1. do first summation (L*A~) and simultaneously second summation (A~ * beta)
for(int k=0; k<8; k++){
// Implemented by adding. Under some conditions both following lines will update
// the same a variable a. If right side is 0, nothing happens (matrix is
// initialized by default to 0.
eqSystem[row][8*k + j] += L[i][k];
eqSystem[row][8*i + k] += beta[k][j];
}
}
}
// Transform to row echelon form - we will need this if system is singular
int rank = gauss(eqSystem);
// Here we have system of 64 equations with 64 unknowns, we will solve it now.
vec_GF2 b(INIT_SIZE, 64);
vec_GF2 x(INIT_SIZE, 64);
GF2 determinant;
solve(determinant, x, eqSystem, b);
if (determinant == GF2::zero()){
int freeVariables = 64 - rank;
// Return set of orthogonal vectors that solve this homogenous equation in case of singular system of
// equations. Subspace generated by aforementioned vectors then solves equation.
//
// We have <freeVariables> free variables. Thus dimension of subspace that solves given system
// has dimension = freeVaraibles.
//
// Return set of orthogonal vectors that span space that solves system. Each vector in this set
// has only one free variable set to 1, others are set to zero. One vector has 64 elements.
// If freeVariables=8 then we will return 8 vectors with 64 elements.
//
// Find orthogonal subspace that solves system
for(int k=0; k<freeVariables; k++){
vec_GF2 curV(INIT_SIZE, 64); // current vector
// Exactly one free variable will be turned to 1 in base
for(int i=0; i<freeVariables; i++){
curV.put(63-i, i==k ? 1 : 0);
}
// Express other elements having assigned values by free variables
for(int i=63-freeVariables; i>=0; i--){
GF2 curVe = GF2::zero();
// Express current element in current vector by lower vectors
for(int j=i+1; j<64; j++){
curVe += eqSystem[i][j] * curV[j];
}
curV.put(i, curVe);
}
// do self-test, this vector should solve system
mat_GF2 outM(INIT_SIZE,8,8);
for(int i=0; i<64; i++){
outM.put(i/8, i%8, curV[i]);
}
// Final verification of given solution - is equation on the top correct now?
mat_GF2 lhs = L * outM;
mat_GF2 rhs = outM * beta;
if(lhs != rhs){
if (doCout) cout << "Something wrong with the result, equation does not hold in self-test..." << endl;
if (doCout) cout << "Dimension of solution="<<freeVariables<<"; Faulty vector k="<<k<<"; Vector: " << endl;
dumpMatrix(outM);
return -4;
}
out.push_back(curV);
}
return 1;
}
// Vector X should contain resulting values for variables a_{00} .. a_{77}
// We have only 1 solution here (can be trivial - homogenous system)
bool trivialSolution=true;
mat_GF2 outM(INIT_SIZE,8,8);
for(int i=0; i<64; i++){
outM.put(i/8, i%8, x[i]);
if (x[i] != GF2::zero()) trivialSolution = false;
}
if (trivialSolution){
return -1;
}
// Final verification of given solution - is equation on the top correct now?
mat_GF2 lhs = L * outM;
mat_GF2 rhs = outM * beta;
if(lhs != rhs){
if (doCout) cout << "Something wrong with the result, equation does not hold..." << endl;
return -2;
}
out.push_back(x);
return 0;
}
int BGEAttack::proposition3(prop3struct_t * out, GenericAES & aes, int r, int col, int row, baseVectors_t & Atild, long int vectorIdx){
// Solving of this problem is based on iterating over 2 variables in GF(2^8) and checking
// if resulting mapping is affine.
//
// Now prepare A~^{-1} from proposition 2 result. Just take first vector in Atild,
// make matrix, take inverse, build lookup table
if (Atild.size()==0) return -1;
NTL::GF2 determinant;
NTL::mat_GF2 AtildMat(INIT_SIZE, 8, 8);
NTL::mat_GF2 AtildMatInv(INIT_SIZE, 8, 8);
// Very defensive approach here, if Atild is composed of set of orthogonal vectors, try each from subspace
int vectSpaceDim = Atild.size();
long int vIdxMax = (long int) pow(2.0,vectSpaceDim);
for(long int vIdx = 1; vIdx < vIdxMax ; vIdx++){
// Reset matrix
for(int x=0; x<64; x++){
AtildMat.put(x/8, x%8, 0);
}
// Construct vector from subspace of solutions
for(int d=0; d<vectSpaceDim; d++){
if ((vIdx & (1<<d)) == 0) continue; // vIdx does not permit to use Atild[d] vector
for(int x=0; x<64; x++){
AtildMat.put(x/8, x%8, Atild[d].get(x));
}
}
// Check if this matrix is OK
NTL::inv(determinant, AtildMatInv, AtildMat); // construct inverse - thats what we are looking for
if (determinant==GF2::zero()){
if (doCout) cout << "One Atild vector is not invertible but it should be: " << vIdx << endl;
if (vectorIdx==vIdx) return -5;
}
if (determinant!=GF2::zero() && vectorIdx==vIdx){
break;
}
}
// No solution form invertible matrix
if (determinant==GF2::zero()){
if (doCout) cout << "There was problem with finding Atild inversion from given set of base vectors, dim=" << vectSpaceDim << endl;
return -2;
}
// We determined Atild which to use, so continue with original proposition3
return proposition3(out, aes, r, col, row, AtildMatInv);
}
int BGEAttack::proposition3(prop3struct_t * out, GenericAES & aes, int r, int col, int row, mat_GF2 AtildMatInv){
// Build lookup table for Atild
GF256_func_t AtildInvLoT;
for(int x=0; x<=0xff; x++){
mat_GF2 xMat = colVector(x);
mat_GF2 res = AtildMatInv * xMat;
GF2X resGF = colVector_GF2X(res, 0);
AtildInvLoT[x] = getLong(resGF);
}
//
// Construct those mappings y_row. This can be similar to prop1, but
// here we are iterating over 2 variables and CHECKING if resulting mapping is affine.
//
int PiOK=0;
for(int p=0; p<4; p++){
GF256_func_t y_row; // pre-computed functions
W128b state;
for(int x=0; x<=0xff; x++){
memset(&state, 0, sizeof(state)); // put 0 everywhere
state.B[col + 4*p] = x; // In each iteration P_i, we set X to different position, namely x0,x1,x2,x3
this->Rbox(state, true, r, true); // perform R box computation on input & output values
y_row[x] = state.B[col + 4*row];
}
// It is important to set dimensions to mat_GF2 before starting working with it, otherwise --> segfault
out->P[p].L.SetDims(8,8);
out->P[p].Linv.SetDims(8,8);
out->P[p].valid=false;
// Now iterate over 2 variables in GF(256), construct mapping and check affinity
bool foundAffine=false;
for(int delta=1; delta<=0xff && foundAffine==false; delta++){
// multiplication matrix
mat_GF2 deltMultM = aes.makeMultAMatrix(delta);
// multiplication lookup table
GF256_func_t deltMultLoT;
for(int x=0; x<=0xff; x++){
mat_GF2 xMat = colVector(x);
mat_GF2 res = deltMultM * xMat;
GF2X resGF = colVector_GF2X(res, 0);
deltMultLoT[x] = getLong(resGF);
}
// Iterate over c constant \in GF(2^8)
for(int c=0; c<=0xff && foundAffine==false; c++){
out->P[p].delta = delta;
out->P[p].c = c;
// Constructing Pi mapping
// P0(x) = (SboxInv * deltMult_0 * AtildInv)(y_row( x, 00, 00, 00) + c0)
// P1(x) = (SboxInv * deltMult_1 * AtildInv)(y_row(00, x, 00, 00) + c1)
// P2(x) = (SboxInv * deltMult_2 * AtildInv)(y_row(00, 00, x, 00) + c2)
// P3(x) = (SboxInv * deltMult_3 * AtildInv)(y_row(00, 00, 00, x) + c3)
GF256_func_t linPart; // Linear part of above equations - to test for linearity later
for(int x=0; x<=0xff; x++){
out->P[p].affineMap[x] = aes.sboxAffineInv[deltMultLoT[AtildInvLoT[y_row[x] ^ c]]];
linPart[x] = x==0 ? 0 : out->P[p].affineMap[x] ^ out->P[p].affineMap[0];
}
// Now check, if constructed mapping is affine. Store affine constant for later = Af(0)
out->P[p].affineConst = out->P[p].affineMap[0];
// Check, if given linear transformation works
// in the same way on each element in space, using transformation results on canon. base
bool isTestOK=true;
for(int x=0; x<=0xff; x++){
int shouldBe = linPart[x];
int realResult = 0;
for(int d=0; d<8; d++){
realResult ^= ((x & (1<<d)) > 0 ? linPart[1<<d] : 0);
}
if (shouldBe != realResult){
isTestOK=false;
break;
}
}
if (isTestOK==false){
continue;
}
// Verify linearity of linPart. Easy procedure: 1. construct matrix representation by
// applying transformation on canon. base, 2. test invertibility
for(int x=0; x<64; x++){
out->P[p].L.put(x/8, x%8, 0);
out->P[p].Linv.put(x/8, x%8, 0);
}
for(int x=0; x<8; x++){
colVectorT(linPart[1<<x], out->P[p].L, x);
}
NTL::GF2 determinant;
NTL::inv(determinant, out->P[p].Linv, out->P[p].L);
if (determinant == GF2::zero()){
if (doCout) cout << "Strange situation, determinant=0, but transformation worked on space... p= "<<p<<";Delta="<<delta<<"; c="<<c<<endl;
continue;
}
out->P[p].valid = true;
foundAffine = true;
break;
}
}
PiOK |= foundAffine ? 1<<p : 0;
}
// Finally, compute c4 = y_row(00,00,00,00) for q_row = c0 ^ c1 ^ c2 ^ c3 ^ c4
W128b state;
memset(&state, 0, sizeof(state)); // put 0 everywhere
this->Rbox(state, true, r, true); // perform R box computation on input & output values
out->c4 = state.B[4*row + col]; // In order to make sense, compute y_row(00,00,00,00)
// Additional stuff - derive gamma and mix column coefficients
// delta^{-1}_i = gamma * alfa_{0,i}
// There are some values twice -> 01 (because 01 is also twice in each row in MC).
if(PiOK==0xf){
int idxTwice=-1; // index that has 01 as MC coefficient
for(int d1=0;d1<4;d1++){
for(int d2=0;d2<4;d2++){
if (d1!=d2 && out->P[d1].delta == out->P[d2].delta){ idxTwice = d1; break; }
}
}
if (idxTwice==-1){
if (doCout) cout << "Weird thing happened, there should be 2 deltas with same value, is MC as it should be?" << endl;
return PiOK;
}
// Now we are able to derive gamma, delta^{-1}_{idxTwice} = gamma * 01 = gamma
// alfa = delta^{-1} * gamma^{-1}
GF2E gammaInvGF = GF2EFromLong(out->P[idxTwice].delta, 8);
GF2E gammaGF = NTL::inv(gammaInvGF);
out->gamma = (BYTE) getLong(gammaGF);
for(int d=0; d<4; d++){
if (out->P[d].valid==false) continue;
GF2E deltaCurGF = GF2EFromLong(out->P[d].delta, 8);
GF2E deltaCurInvGF = NTL::inv(deltaCurGF);
GF2E alfaGF = gammaInvGF * deltaCurInvGF;
out->P[d].alfa_0 = (BYTE) getLong(alfaGF);
}
}
return PiOK;
}
int BGEAttack::recoverQj(GenericAES & aes, int r, int col, int row, const mat_GF2 A0, BYTE alfa00, BYTE alfa_row_0, mat_GF2 & Aj, BYTE * qj){
assert(r>=0 && r<N_ROUNDS);
assert(col>=0 && col<=3);
assert(row>=1 && row<=3);
// From the Proposition 1, if we know already linear part A0 of Q0, we can this way determine
// Aj linear part of Qj for other mappings
//
// Proposition 1 solves:
// y_i(x0,00,00,00) = L(y_j(x0,00,00,00)) + c while L and c is returned
// L = A_i * (\alfa_{i,0} * \alfa_{j,0}^{-1}) * A_j^{-1} while we know L, A_i, alfa...
// A_j = L^{-1} * A_i * (\alfa_{i,0} * \alfa_{j,0}^{-1})
affineEquiv_t L;
int prop1result = proposition1(L, r, col, 0, row, 0);
if (prop1result==0) {
if (doCout) cout << "recoverAj fail: Proposition1 failed for r="<<r<<"; col="<<col<<"; (y0, y"<<row<<") " << endl;
return -1;
}
// Here we need inverse of alfa_row_0
GF2E alfa00GF = GF2EFromLong(alfa00, 8);
GF2E alfaRowGF = GF2EFromLong(alfa_row_0, 8);
GF2E alfaRowInvGF = NTL::inv(alfaRowGF);
GF2E alfaGF = alfa00GF * alfaRowInvGF;
BYTE alfa = (BYTE) getLong(alfaGF);
mat_GF2 alfaMatrix = aes.makeMultAMatrix(alfa);
// compute linear part from L
Aj = L.Linv * A0 * alfaMatrix;
// Part 2 - constant part extraction
// If we put known Aj linear part to proposition 3 we don't have to bother with A~_j and gamma.
// Then delta_i^{-1} = afa_j,i
mat_GF2 AjInv;
GF2 determinant;
NTL::inv(determinant, AjInv, Aj);
if (determinant == GF2::zero()){
if (doCout) cout << "Cannot compute inverse - should never happen!!" << endl;
return -2;
}
prop3struct_t * prop3 = new prop3struct_t;
int prop3result = proposition3(prop3, aes, r, col, row, AjInv);
if (prop3result != 0xf) {
delete prop3;
if (doCout) cout << "some problem with proposition 3 in recover Qj occurred. result="<<prop3result<<endl;
return -3;
}
// We don't really care about delta, important is, that Aj should be correct, so we
// can directly recover qj - see end of section 3.3
(*qj) = prop3->c4
^ prop3->P[0].c
^ prop3->P[1].c
^ prop3->P[2].c
^ prop3->P[3].c;
// Here we can do another test to verify that we are doing well - just visually, not checking against MC
// delta_i^{-1} = afa_j,i
for(int x=0; x<4; x++){
GF2E deltaGF = GF2EFromLong(prop3->P[x].delta, 8);
GF2E deltaInvGF = NTL::inv(deltaGF);
BYTE deltaInv = getLong(deltaInvGF);
if (doCout) cout
<< " recoverQj self-test; r="<<r<<"; col="<<col<<"; (y0, y"<<row<<"); P["<<x
<<"].deltaInv="<<CHEX(deltaInv)
<<"; alfa_{"<<row<<","<<x<<"}="<< CHEX(prop3->P[x].alfa_0) << endl;
}
if (doCout) cout << " recoverQj; q = " << CHEX(*qj) << "; gamma=" << CHEX(prop3->gamma) << "; " << endl;
delete prop3;
return 0;
}
int BGEAttack::recoverCipherKey(GenericAES & aes, BYTE roundKeys[2][16], vec_GF2E& encKey){
encKey.SetLength(16);
// At first determine correct round and Rcon constant
// Verify that given round key is OK
// w9 = w8 + w5
// w10 = w9 + w6
// w11 = w10 + w7
for(int col=1; col<4; col++){
for(int row=1; row<4; row++){
if (roundKeys[1][4*row+col] != (roundKeys[1][4*row+col-1] ^ roundKeys[0][4*row+col])){
if (doCout) cout << "Error in round key verification, you passed invalid round keys; col="<<col<<"; row="<<row << endl;
return -1;
}
}
}
//
// Keys are probably OK, now recover RCON constant and round to which key belongs
//
vec_GF2E gw7(INIT_SIZE, 4);
vec_GF2E w7(INIT_SIZE, 4);
for(int i=0; i<4; i++) w7[i] = GF2EFromLong(roundKeys[0][4*i+3], 8);
for(int i=0; i<4; i++) gw7[i] = GF2EFromLong(roundKeys[1][4*i] ^ roundKeys[0][4*i], 8); // w8 = g(w7) + w4
int rconIdx = -1;
for(int rc=0; rc<16; rc++){
vec_GF2E gw7_copy(INIT_SIZE, 4);
for(int i=0; i<4; i++) gw7_copy[i] = gw7[i];
// Revert RC[rc] application on first element
gw7_copy[0] = GF2EFromLong(getLong(gw7[0] + aes.RC[rc]),8);
// Inverse Sbox application
for(int i=0; i<4; i++) gw7_copy[i] = GF2EFromLong(aes.sboxAffineInv[getLong(gw7_copy[i])], 8);
// Inverse left shift -> shift to the right, respectively test it with taking shift into account
bool correctRcon=true;
for(int i=0; i<4; i++){
if (w7[(i+1) % 4] != gw7_copy[i]) {
correctRcon=false;
break;
}
}
if(correctRcon){
rconIdx = rc;
if (doCout) cout << "We have correct Rcon! rconIdx="<<rc<<endl;
break;
}
}
if (rconIdx==-1) return -3;
// now perform reverse key schedule to get cipher key
mat_GF2E w(INIT_SIZE, 4, 4);
for(int i=0; i<16; i++) w[i/4][i%4] = GF2EFromLong(roundKeys[0][i], 8);
for(int rc=rconIdx-1; rc>=0; rc--){
mat_GF2E wp(INIT_SIZE, 4, 4); // previous
// we can simply derive w1, w2, w3
for(int col=1; col<4; col++){
for(int row=0; row<4; row++){
wp[row][col] = GF2EFromLong(getLong(w[row][col] + w[row][col-1]), 8);
}
}
// w0 = w4 + g(w3), g(w3) we already have, so compute g(w3)
// 1. copy w3 to w0
// 2. apply g to w0
// 3. add w4 to w0
for(int i=0; i<4; i++){
wp[i][0] = GF2EFromLong(aes.sboxAffine[getLong(wp[(i+1) % 4][3])], 8); // take shift into account + apply sbox
}
// Apply RCON
wp[0][0] = GF2EFromLong(getLong(wp[0][0] + aes.RC[rc]), 8);
// Add w4 and we have complete w0
for(int i=0; i<4; i++) wp[i][0] = GF2EFromLong(getLong(wp[i][0] + w[i][0]), 8);
// copy back
for(int i=0; i<16; i++) w[i/4][i%4] = GF2EFromLong(getLong(wp[i/4][i%4]), 8);
if (doCout) cout << "RC=" << rc << "; previousKey: "<<endl;
dumpMatrix(w);
}
for(int i=0; i<16; i++) encKey[i] = GF2EFromLong(getLong(w[i%4][i/4]), 8);
return 0;
}
int BGEAttack::run(BYTE * key, keySize keyLen) {
GenericAES defAES;
defAES.init(0x11B, 0x03);
#ifndef AES_BGE_ATTACK
cerr << "Cannot proceed with attack if \"AES_BGE_ATTACK\" is not defined, we are missing required additions"<<endl;
exit(1);
#endif
WBAESGenerator generator;
if (doCout) cout << "Generating AES..." << endl;
generator.useDualAESARelationsIdentity=false;
generator.useDualAESIdentity=false;
generator.useDualAESSimpeAlternate=false;
generator.useIO04x04Identity=false;
generator.useIO08x08Identity=false;
generator.useMB08x08Identity=false;
generator.useMB32x32Identity=false;
this->wbaes = new WBAES;
this->coding = new ExtEncoding;
generator.generateExtEncoding(this->coding, WBAESGEN_EXTGEN_ID);
generator.generateTables(key ? key : GenericAES::testVect128_key, keyLen,
this->wbaes, this->coding, true); if (doCout) cout << "AES ENC generated" << endl;
generator.generateTables(key ? key : GenericAES::testVect128_key, keyLen,
this->wbaes, this->coding, false); if (doCout) cout << "AES DEC generated" << endl;
// WBAES changed to state with affine matching bijections at round boundaries.
if (doCout) cout << "Going to test WBAES before modifying tables" << endl;
generator.testComputedVectors(true, this->wbaes, this->coding);
if (doCout) cout << "Starting the BGE attack" << endl;
int toReturn = this->attack();
delete this->wbaes;
delete this->coding;
this->wbaes = NULL;
this->coding = NULL;
return toReturn;
}
int BGEAttack::attack(void) {
// The aim of this attack is to extract round keys, so generate them here to be able to compare results
GenericAES defAES;
defAES.init(0x11B, 0x03);
bool encrypt = true;
WBAESGenerator generator;
W128b state;
assert(this->wbaes!=NULL);
vec_GF2E defaultKey; // key for default AES in GF2E representation
vec_GF2E expandedKey; // expanded key for default AES
const int * nextTbox = shiftT2; // attack is not yet implemented for decryption
generator.BYTEArr_to_vec_GF2E(GenericAES::testVect128_key, KEY_SIZE_16, defaultKey); // convert BYTE key to GF2E key
defAES.expandKey(expandedKey, defaultKey, KEY_SIZE_16); // key schedule for default AES
if (doCout) cout << "Expanded key: " << endl;
if (doCout) dumpVector(expandedKey);