-
Notifications
You must be signed in to change notification settings - Fork 0
/
Approximation.cpp
2071 lines (1759 loc) · 83.4 KB
/
Approximation.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
/*
* File: Approximation.cpp
* Author: ph4r05
*
* Created on May 16, 2014, 10:21 AM
* TODO: multithreaded!!!
* TODO: MPI???
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include <NTL/mat_GF2.h>
#include <boost/unordered_map.hpp>
#include <thread>
#include "Approximation.h"
#include "CombinatiorialGenerator.h"
#include "ProgressMonitor.h"
#include "NTLUtils.h"
#include <boost/archive/tmpdir.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/list.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/assume_abstract.hpp>
// Signal blocking
#include <sys/types.h>
#include <signal.h>
#include <stdlib.h>
NTL_CLIENT
using namespace std;
using namespace NTL;
Approximation::Approximation(uint orderLimit) : cip(NULL), dumpCoefsToFile(false),
outputWidthUlong(0), inputWidthUlong(0),
threadCount(1), keybitsToZero(0),
poly2take(NULL), numPolyActive(0),
verboseLvl(1) {
this->orderLimit = orderLimit;
}
Approximation::~Approximation() {
if (poly2take!=NULL){
delete[] poly2take;
poly2take = NULL;
}
}
void Approximation::setCipher(ICipher* cip) {
this->cip = cip;
this->byteWidth = cip->getInputBlockSize() + cip->getKeyBlockSize();
this->logBitInputWidth = ceil(log2(this->byteWidth*8));
this->outputWidthUlong = OWN_CEIL((double)cip->getOutputBlockSize() / (double)SIZEOF_ULONG);
this->inputWidthUlong = OWN_CEIL((double)byteWidth / (double)SIZEOF_ULONG);
}
void Approximation::init() {
assert(cip!=NULL);
assert(outputWidthUlong>0 && inputWidthUlong>0);
assert(orderLimit>=0 && orderLimit<MAX_ORDER);
assert(SIZEOF_ULONG == sizeof(ULONG));
// Init combinatorial indexer.
combIndexer.init(8*byteWidth, orderLimit);
// Init FGb helper
fgb.init(byteWidth, orderLimit, cip->getOutputBlockSize()*8);
// Init polynomial-to-take bitmap.
poly2take = new ULONG[outputWidthUlong];
numPolyActive = 8*cip->getOutputBlockSize();
memset(poly2take, 0xff, SIZEOF_ULONG * outputWidthUlong);
// Initialize signal blocking.
sigemptyset(&pendingSignals);
sigemptyset(&blockingMask);
sigaddset(&blockingMask, SIGHUP);
sigaddset(&blockingMask, SIGTERM);
sigaddset(&blockingMask, SIGQUIT);
sigaddset(&blockingMask, SIGINT); // CTRL+C
sigaddset(&blockingMask, SIGABRT);
sigaddset(&blockingMask, SIGUSR1);
sigaddset(&blockingMask, SIGUSR2);
}
bool Approximation::isPoly2Take(uint polyIdx) const {
return (poly2take[polyIdx / (8*SIZEOF_ULONG)] & (ULONG1 << (polyIdx % (8*SIZEOF_ULONG)))) > 0;
}
void Approximation::setPoly2Take(const std::vector<std::string> & map) {
// Set by default to zero.
memset(poly2take, 0x0, SIZEOF_ULONG * outputWidthUlong);
// And iterate over enabled functions.
numPolyActive=0;
for (std::vector<std::string>::const_iterator it = map.begin() ; it != map.end(); ++it){
const std::string cur = *it;
const int idx = std::stoi(cur);
// Possible duplicates.
if (poly2take[idx / (8*SIZEOF_ULONG)] & ULONG1 << (idx % (8*SIZEOF_ULONG))) continue;
// Set to map & update counter.
poly2take[idx / (8*SIZEOF_ULONG)] |= ULONG1 << (idx % (8*SIZEOF_ULONG));
numPolyActive+=1;
}
}
uint Approximation::getNumVariables() const {
return cip->getKeyBlockSize()*8-keybitsToZero;
}
void Approximation::computeCoefficients(std::vector<ULONG> * coefficients) {
ULONG * ulongOut = new ULONG[outputWidthUlong];
ULONG * ulongInp = new ULONG[inputWidthUlong];
uchar * finput = new uchar[byteWidth];
uchar * output = new uchar[cip->getOutputBlockSize()];
CombinatiorialGenerator ** cgenerators = new CombinatiorialGenerator * [orderLimit+1];
ULONG * tmpCombination = new ULONG[orderLimit+1];
// Allocating space for the coefficients.
for(unsigned int order = 0; order<=orderLimit; order++){
ULONG vecSize = CombinatiorialGenerator::binomial(8*byteWidth, order) * outputWidthUlong;
cout << " Allocating coefficient storage for order " << order << "; Bytes=" << vecSize * sizeof(ULONG) << endl;
coefficients[order].assign(vecSize, (ULONG) 0);
}
// TODO: for order 3 and higher use multiple threads to parallelize the computation!
// TODO: regarding the progress bar, only thread num 0 shows it. Does not mind
// since each thread has space to search of the same size, progress should be
// approximately the same for each thread.
// Find polynomial terms coefficient for order 1..orderLimit.
for(uint order=0; order<=orderLimit; order++){
CombinatiorialGenerator cg(byteWidth*8, order);
// Combinatorial generators for computing XOR indices.
for(uint i=0; i < order; i++){
cgenerators[i] = new CombinatiorialGenerator(order, i);
}
cout << "Starting with order: "
<< order
<< "; combinations: " << cg.getTotalNum()
<< "; number of bytes to store coefficients: "
<< (8 * cip->getOutputBlockSize() * cg.getTotalNum() / 8)
<< endl << " ";
// Here is the point for parallelization.
// Each thread/computing node can compute x-th combination from the generator
// effectively partitioning combination space.
// Synchronization barrier is needed after finishing particular order
// because in order to compute order N we need to have coefficients of
// terms of order N-1 and less.
ULONG combCtr=0;
ProgressMonitor pm(0.01);
for(; cg.next(); combCtr++){
const uchar * input = cg.getCurCombination();
// Evaluate cipher on current combination.
cip->evaluate(input, input + cip->getInputBlockSize(), output);
// Transform output to the ULONG array
// For better memory handling and XORing in an one big register.
readUcharToUlong(output, cip->getOutputBlockSize(), ulongOut);
// Evaluate coefficients for each polynomial in the cipher
// for the given term specified by the state of the combinatorial generator.
//
// Current term value: all previous terms including enabled bits XOR ciphertext.
// For example, term to determine: x1x6x9:
// constant XOR
// x1 XOR x6 XOR x9 XOR
// x1x6 XOR x1x9 XOR x6x9
//
// XOR all constant, linear, quadratic, cubic, etc.. terms if applicable.
// In order to determine current term coefficient all lower terms
// that can be obtained from this one has to be taken into account.
// and XORed into the result.
for(uint xorOrder=0; xorOrder<order && order<=orderLimit; xorOrder++){
// Obtain a shortcut reference to the combinatorial generator
// for this xorOrder. This generator is used to generate
// combinations of variables from to original term to construct
// a lower term.
CombinatiorialGenerator * const xorOrderGen = cgenerators[xorOrder];
// Iterate over all possible variable combinations to the new
// resulting term of a lower order.
for(xorOrderGen->reset(); xorOrderGen->next(); ){
// Construct xorOrder term representation for term
// index computation.
for(uint tmpCombCtr = 0; tmpCombCtr<xorOrder; tmpCombCtr++){
tmpCombination[tmpCombCtr] = cg.getCurState()[xorOrderGen->getCurState()[tmpCombCtr]];
}
// Term index computation.
ULONG idx = combIndexer.getCombinationIdx(xorOrder, tmpCombination);
// XOR current result register with coefficient register.
// If low order term is present in the approximation function,
// it has to be taken into account.
for(uint ulongCtr=0; ulongCtr<outputWidthUlong; ulongCtr++){
ulongOut[ulongCtr] ^= coefficients[xorOrder][outputWidthUlong*idx + ulongCtr];
}
}
}
// Store value of the current coefficient on his place in the coef. vector.
for(uint ulongCtr=0; ulongCtr<outputWidthUlong; ulongCtr++){
coefficients[order][outputWidthUlong*cg.getCounter() + ulongCtr] = ulongOut[ulongCtr];
}
// Progress monitoring.
double cProg = (double)cg.getCounter() / (double)cg.getTotalNum();
pm.setCur(cProg);
}
pm.setCur(1.0);
cout << endl;
// Combinatorial generators destruction.
for(uint i=0; i < order; i++){
delete cgenerators[i];
}
}
delete[] tmpCombination;
delete[] ulongInp;
delete[] ulongOut;
delete[] output;
delete[] finput;
delete[] cgenerators;
}
int Approximation::selftestApproximation(unsigned long numSamples) const {
// Allocate input & key buffers
uchar * outputCip = new uchar[cip->getOutputBlockSize()];
uchar * outputPol = new uchar[cip->getOutputBlockSize()];
uchar * input = new uchar[byteWidth];
ULONG * hits = new ULONG[8*cip->getOutputBlockSize()];
ULONG * iBuff = new ULONG[this->inputWidthUlong]; // Input ULONG buffer
ULONG * variablesValueMask = new ULONG[this->inputWidthUlong];
ULONG * ulongOut = new ULONG[outputWidthUlong];
ULONG * ulongInp = new ULONG[inputWidthUlong];
const ULONG genLimit = numSamples;
uint matchErrors=0;
// Seed (primitive).
srand((unsigned)time(0));
memset(hits, 0, sizeof(ULONG)*8*cip->getOutputBlockSize());
memset(variablesValueMask, 0xff, sizeof(ULONG)*this->inputWidthUlong);
// Generate messages and keys, evaluate it both on cipher and polynomials.
ProgressMonitor pm(0.01);
for(unsigned long i=0; i<genLimit; i++){
// Generate cipher input at random.
memset(input, 0, sizeof(uchar) * byteWidth);
// Generate input block randomly with hamming weight smaller than maximal
// precomputed order.
uint randOrder = 1 + (rand() % orderLimit);
for(uint k=0; k<randOrder; k++){
const uint randIdx = rand() % (8*byteWidth);
input[(randIdx/8)] |= ULONG1 << (randIdx%8);
}
readUcharToUlong(input, byteWidth, iBuff);
// Evaluate cipher.
cip->evaluate(input, input + cip->getInputBlockSize(), outputCip);
// Evaluate polynomial.
this->evaluateCoefficients(this->coefficients, input, outputPol, ulongInp, ulongOut);
// Compute statistics - number of hits for individual polynomial.
for(uint p=0; p<8*cip->getOutputBlockSize(); p++){
hits[p] += (outputCip[p/8] & (ULONG1 << (p%8))) == (outputPol[p/8] & (ULONG1 << (p%8)));
}
// Test partial evaluation for correctness, has to be in match with full evaluation.
std::vector<ULONG> coeffEval[MAX_ORDER];
coeffEval[0].assign(this->inputWidthUlong, 0ul);
this->partialEvaluation(this->coefficients, this->byteWidth*8, variablesValueMask, iBuff, coeffEval);
// Check result of partial evaluation w.r.t. full evaluation. Has to match!
bool partEvalError=false;
for(uint x = 0; x < cip->getOutputBlockSize()*8; x++){
const bool bitFullEval = ((outputPol[x/8] & (ULONG1 << (x%8))) > 0);
const bool bitPartEval = (((coeffEval[0][x/(8*SIZEOF_ULONG)]) & (ULONG1 << (x % (8*SIZEOF_ULONG)))) > 0);
if (bitFullEval != bitPartEval){
partEvalError=true;
}
}
if (partEvalError){
matchErrors+=1;
//cout << " Error in evaluation!" << endl;
//dumpBin(cout, coeffEval[0], this->outputWidthUlong);
//dumpBin(cout, outputPol, cip->getOutputBlockSize());
}
// Progress monitoring.
double cProg = (double)i / (double)genLimit;
pm.setCur(cProg);
}
pm.setCur(1.0);
// Determine test success
bool success=true;
for(uint p=0; p<8*cip->getOutputBlockSize(); p++){
if (hits[p]!=genLimit){
success=false;
break;
}
}
cout << endl << "Self test finished: ";
if (success){
cout << " [ OK ]" << endl;
} else {
cout << " [ FAIL ]" << endl << "Frequencies: " << endl;
for(uint p=0; p<8*cip->getOutputBlockSize(); p++){
cout << dec << " f_" << setw(4) << setfill('0') << right << p << " = ";
cout << ((double)hits[p] / (double)genLimit) << endl;
}
}
cout << "Matching test: ";
if (matchErrors==0){
cout << " [ OK ]" << endl;
} else {
cout << " [ FAIL ] numFails=" << matchErrors << endl;
}
// Free the memory.
delete[] hits;
delete[] outputCip;
delete[] outputPol;
delete[] input;
delete[] iBuff;
delete[] variablesValueMask;
delete[] ulongInp;
delete[] ulongOut;
return success;
}
int Approximation::testPolynomialApproximation(unsigned long numSamples) const {
// Allocate input & key buffers
uchar * outputCip = new uchar[cip->getOutputBlockSize()];
uchar * outputPol = new uchar[cip->getOutputBlockSize()];
uchar * input = new uchar[byteWidth];
ULONG * hits = new ULONG[8*cip->getOutputBlockSize()];
ULONG * ulongOut = new ULONG[outputWidthUlong];
ULONG * ulongInp = new ULONG[inputWidthUlong];
// Seed (primitive).
srand((unsigned)time(0));
memset(hits, 0, sizeof(ULONG)*8*cip->getOutputBlockSize());
// Generate 2^20 random messages and keys, evaluate it
// both on cipher and polynomials.
ProgressMonitor pm(0.01);
for(unsigned long i=0; i<numSamples; i++){
// Generate cipher input at random.
randomBuffer(input, byteWidth);
// Evaluate cipher.
cip->evaluate(input, input + cip->getInputBlockSize(), outputCip);
// Evaluate polynomial.
this->evaluateCoefficients(this->coefficients, input, outputPol, ulongInp, ulongOut);
//cout << "final: " << endl;
//dumpUcharHex(cout, outputCip, 16);
//dumpUcharHex(cout, outputPol, 16);
// Compute statistics - number of hits for individual polynomial.
for(uint p=0; p<8*cip->getOutputBlockSize(); p++){
hits[p] += (outputCip[p/8] & (ULONG1 << (p%8))) == (outputPol[p/8] & (ULONG1 << (p%8)));
}
// Progress monitoring.
double cProg = (double)i / (double)numSamples;
pm.setCur(cProg);
}
pm.setCur(1.0);
cout << endl << "Approximation quality test finished." << endl;
for(uint p=0; p<8*cip->getOutputBlockSize(); p++){
cout << dec << " f_" << setw(4) << setfill('0') << right << p << " = ";
cout << ((double)hits[p] / (double)numSamples) << endl;
}
// Free the memory.
delete[] hits;
delete[] outputCip;
delete[] outputPol;
delete[] input;
delete[] ulongInp;
delete[] ulongOut;
return 1;
}
int Approximation::evaluateCoefficients(const std::vector<ULONG> * coefficients,
const unsigned char* input, unsigned char* output, ULONG * iBuff, ULONG * oBuff) const {
// We can assume that approximate half of the coefficients are enabled/present
// in the resulting polynomial, thus evaluation is based on the iteration of
// the combinatorial generator and reading coefficient by coefficient.
const uint bitWidth = 8*byteWidth;
// Reset output buffer, only ones will be set here, has to be set to zero
// and copy to bigger buffer for better manipulation & speed.
readUcharToUlong(input, byteWidth, iBuff);
// Evaluation on ULONGs.
for(uint ulongCtr=0; ulongCtr<outputWidthUlong; ulongCtr++){
// Evaluate SIZEOF_ULONG polynomials simultaneously.
// 1. Use constant term for initialization.
oBuff[ulongCtr] = coefficients[0][ulongCtr];
}
// 2. linear, quadratic and cubic terms, quartic and higher if applicable.
for(uint order=1; order<=orderLimit; order++){
CombinatiorialGenerator cgen(bitWidth, order);
for(; cgen.next(); ){
const ULONG ctr = cgen.getCounter();
// Now term being evaluated is fixed, defined by the state
// of the combinatorial generator.
//
// Get bit-mask with those bits enabled corresponding to variables in
// the particular term determined by cgen.
const ULONG * comb = cgen.getCurUlongCombination();
//
// Evaluate particular term on the input.
//
// Some elements of the array can be zero, but this does not mean
// the term itself is zero, it just can be defined on the end of the
// array.
//
// For example x_127 in 64-bit architecture would be comb[0]=0, comb[1]=highest bit.
//
bool termEval=true;
for(uint uctr2=0; uctr2<inputWidthUlong; uctr2++){
termEval &= (comb[uctr2]==0) ? 1 : (comb[uctr2] & iBuff[uctr2]) == comb[uctr2];
}
// If term is null, nothing to do here, go evaluate next one.
if (!termEval){
continue;
}
// Term is evaluated to 1, thus XOR it to the result - where it is present.
for(uint uctr2=0; uctr2<outputWidthUlong; uctr2++){
oBuff[uctr2] ^= coefficients[order][outputWidthUlong*ctr + uctr2];
}
}
}
// Transform ULONG to output.
readUlongToUchar(output, cip->getOutputBlockSize(), oBuff);
return 0;
}
void Approximation::genMessages() {
const unsigned byteWidth = cip->getInputBlockSize() + cip->getKeyBlockSize();
// Allocate input & key buffers
uchar * output = new uchar[cip->getOutputBlockSize()];
uchar * finput = new uchar[byteWidth];
uchar * key = new uchar[cip->getKeyBlockSize()];
// Seed (primitive).
srand((unsigned)time(0));
ofstream cip3("cip_msgs.txt");
// Generate key at random.
randomBuffer(key, cip->getKeyBlockSize());
dumpUchar(cip3, key, cip->getKeyBlockSize());
// Generate tons of random messages.
for(unsigned long i=0; i<16777216ul; i++){
// Generate message at random.
randomBuffer(finput, cip->getInputBlockSize());
cip->evaluate(finput, key, output);
// Dump
dumpUchar(cip3, output, cip->getOutputBlockSize());
}
delete[] finput;
delete[] key;
delete[] output;
}
ULONG Approximation::numberOfTerms(ULONG variables, ULONG maxOrder) const {
ULONG res = 0;
for(ULONG ord=0; ord<=maxOrder; ord++){
res += CombinatiorialGenerator::binomial(variables, ord);
}
return res;
}
int Approximation::selftestIndexing() const {
const uint bitWidth = 8*this->byteWidth;
// Test quadratic indexing equations.
cout << "Testing quadratic indexing." << endl;
CombinatiorialGenerator cg2(bitWidth, 2);
for(; cg2.next(); ){
const ULONG ctr = cg2.getCounter();
const ULONG * state = cg2.getCurState();
const ULONG ctrComputed = CombinatiorialGenerator::getQuadIdx(bitWidth, state[0], state[1]);
if (ctrComputed != ctr){
dumpUlongHex(cerr, state, 2);
cerr << "Invalid index for order 2 ctr="<<ctr<<"; computed: " << ctrComputed << endl;
}
}
// Test cubic indexing equations.
cout << "Testing cubic indexing." << endl << " ";
CombinatiorialGenerator cg3(bitWidth, 3);
ProgressMonitor pm3(0.01);
for(; cg3.next(); ){
const ULONG ctr = cg3.getCounter();
const ULONG * state = cg3.getCurState();
const ULONG ctrComputed1 = CombinatiorialGenerator::getCubeIdx(bitWidth, state[0], state[1], state[2]);
if (ctrComputed1 != ctr){
dumpUlongHex(cerr, state, 3);
cerr << "Invalid index for order 3 ctr="<<ctr<<"; computed1: " << ctrComputed1 << endl;
}
// Progress monitoring.
double cProg = (double)ctr / (double)cg3.getTotalNum();
pm3.setCur(cProg);
}
pm3.setCur(1.0);
cout << endl;
// Test general indexing.
cout << "Testing general indexing." << endl;
for(uint order=0; order<=orderLimit; order++){
cout << " Testing order " << order << endl << " ";
CombinatiorialGenerator cg(bitWidth, order);
ProgressMonitor pm(0.01);
const ULONG total = cg.getTotalNum();
ULONG outerCtr = 0;
for(; cg.next(); outerCtr++){
const ULONG ctr = cg.getCounter();
const ULONG * state = cg.getCurState();
const ULONG ctrComputed = combIndexer.getCombinationIdx(order, state);
if (ctrComputed != ctr){
dumpUlongHex(cerr, state, order);
cerr << "Invalid index for order " << order << " ctr=" << ctr << "; computed1: " << ctrComputed << endl;
}
// Progress monitoring.
double cProg = (double)ctr / (double)total;
pm.setCur(cProg);
}
if (outerCtr != total){
cerr << "Invalid number of iterations for configuration (" << bitWidth << ", " << order << ")!" << endl;
}
pm.setCur(1.0);
cout << endl;
}
// Randomized test of the combination indexing inversion.
const uint testTarget = 10000;
cout << "Testing indexing inversion" << endl << " ";
ProgressMonitor pm(0.01);
for(uint x=0; x<testTarget; x++){
// Randomize order selection
uint order2test = (rand() % orderLimit) + 1;
ULONG comb[MAX_ORDER];
ULONG combx[MAX_ORDER];
comb[0] = rand() % (bitWidth-order2test);
for(uint i=1; i<order2test; i++){
const int mod = bitWidth-order2test-comb[i-1]-1;
if (mod==0){
comb[i] = comb[i-1]+1;
} else {
comb[i] = comb[i-1]+1+(rand() % mod);
}
}
ULONG idx = combIndexer.getCombinationIdx(order2test, comb);
combIndexer.getCombinationFromIdx(order2test, combx, idx);
ULONG idx2 = combIndexer.getCombinationIdx(order2test, combx);
if (idx!=idx2){
cout << " Problem in combination order=" << order2test << "; idx=" << idx << endl;
dumpHex(cout, comb, order2test);
dumpHex(cout, combx, order2test);
}
// Test Ulong inversion
idx = combIndexer.getCombinationULong(order2test, comb);
combIndexer.getCombinationFromULong(combx, idx);
idx2 = combIndexer.getCombinationULong(order2test, combx);
if (idx!=idx2){
cout << " Problem in combination order=" << order2test << "; uidx=" << idx << endl;
dumpHex(cout, comb, order2test);
dumpHex(cout, combx, order2test);
}
pm.setCur((double)x / (double)testTarget);
}
pm.setCur(1.0);
cout << endl << "Test completed" << endl;
return 0;
}
void Approximation::solveKeyGrobner(uint samples, bool dumpInputBase, bool selfTest, int basisReduction) const {
// Allocate input & key buffers
uchar * outputCip = new uchar[cip->getOutputBlockSize()];
uchar * input = new uchar[byteWidth];
uchar * key = new uchar[cip->getKeyBlockSize()];
uchar * keySol = new uchar[cip->getKeyBlockSize()];
const uint numPolynomials = numPolyActive;
const uint numVariables = this->getNumVariables();
// Seed (primitive).
srand((unsigned)time(0));
// Bit-mask of variables for which we have a valid value.
ULONG * variablesValueMask = new ULONG[this->inputWidthUlong];
memset(variablesValueMask, 0x0, sizeof(ULONG) * inputWidthUlong);
// Set plaintext bits to 1 --> they will be evaluated.
for(uint i=0; i<8*cip->getInputBlockSize(); i++){
variablesValueMask[i/(8*SIZEOF_ULONG)] |= ULONG1 << (i % (8*SIZEOF_ULONG));
}
// Zero key bits are known to us, thus evaluate them with zero during partial evaluation.
for(uint i=0; i<keybitsToZero; i++){
const uint idx = 8*cip->getInputBlockSize() + i;
variablesValueMask[idx/(8*SIZEOF_ULONG)] |= ULONG1 << (idx % (8*SIZEOF_ULONG));
}
// Input ULONG buffer
ULONG * iBuff = new ULONG[this->inputWidthUlong];
ULONG * iTmpBuff = new ULONG[this->inputWidthUlong];
ULONG * oTmpBuff = new ULONG[this->outputWidthUlong];
// FGb polynomials. We have here specific number of polynomials.
Dpol * inputBasis1 = new Dpol[samples*numPolynomials];
Dpol * inputBasis2 = new Dpol[samples*numPolynomials];
Dpol * inputBasis = inputBasis1;
Dpol * outputBasis = new Dpol[FGb_MAXI_BASE];
memset(inputBasis1, 0, sizeof(Dpol_INT) * samples * numPolynomials);
memset(inputBasis2, 0, sizeof(Dpol_INT) * samples * numPolynomials);
// Generate key at random, once for the cipher.
// From now it will behave as a black-box and we assume key is unknown to us.
memset(key, 0, sizeof(uchar) * cip->getKeyBlockSize());
for(uint i=keybitsToZero; i<8*cip->getKeyBlockSize(); i++){
key[i/8] |= (rand() % 2) ? (1u << i%8) : 0;
}
// Copy key to the input field for selftest.
memset(input, 0, byteWidth);
for(uint i=0; i<cip->getKeyBlockSize(); i++){
input[i+cip->getInputBlockSize()] = key[i];
}
cout << "Generated secret key: " << endl;
dumpHex(cout, key, cip->getKeyBlockSize());
dumpBin(cout, key, cip->getKeyBlockSize());
// Dump how polynomial-take-map looks like.
cout << " NumVariables=" << numVariables << "; zeroKeyBits=" << keybitsToZero << endl;
cout << " NumPoly="<<numPolynomials<<"; Polymap: ";
dumpHex(cout, poly2take, outputWidthUlong);
cout << " Expected basis size=" << dec << (samples*numPolynomials) << endl;
cout << " Variables to evaluate mask=";
dumpHex(cout, variablesValueMask, this->inputWidthUlong);
if (selfTest){
cout << " Self-testing of the solveGb()" << endl;
}
// Whether to show some information during sample computation or not...
bool interSampleOutput = samples < 4;
// Polynomial hashes
boost::unordered_map<ULONG, uint> polynomialHashes;
// Input basis size.
uint inputBasisSize=0;
// Generate tons of random messages.
ProgressMonitor pmSample(0.01);
for(ulong sample=0; sample<samples; sample++){
if (interSampleOutput){
cout << endl << " [+] Starting with sample="<<sample<<endl;
}
// Generate message at random.
// Fix plaintext variables to the generated ones.
// Now we obtain system of equations with key variables.
// 128 equations with (128-keybitsToZero) unknown bits.
for(uint i=0; samples > 1 && i<cip->getInputBlockSize(); i++){
input[i] = (rand() % 0x100);
}
// Input variables, only masked are taken into consideration during partial evaluation.
readUcharToUlong(input, cip->getInputBlockSize(), iBuff);
readUcharToUlong(key, cip->getKeyBlockSize(), iBuff + OWN_CEIL((double)cip->getInputBlockSize() / (double)SIZEOF_ULONG));
// Evaluation.
if (selfTest){
// If we are using self test, evaluate this on the approximation function.
this->evaluateCoefficients(this->coefficients, input, outputCip, iTmpBuff, oTmpBuff);
} else {
// Evaluate cipher.
cip->evaluate(input, key, outputCip);
}
// New function is stored in another coefficient array.
// Allocate space for the coefficients.
std::vector<ULONG> coeffEval[MAX_ORDER];
for(unsigned int order = 0; order<=orderLimit; order++){
ULONG vecSize = CombinatiorialGenerator::binomial(numVariables, order) * outputWidthUlong;
if (interSampleOutput){
cout << " Allocating pEval function, order=" << dec << order << "; vecSize=" << vecSize << endl;
}
coeffEval[order].assign(vecSize, (ULONG) 0);
}
// Partial evaluation = reduces terms with evaluated variables.
if (interSampleOutput){
cout << " Going to partially evaluate approximating function." << endl;
}
partialEvaluation(this->coefficients, numVariables, variablesValueMask, iBuff, coeffEval);
// Add ciphertext values to the polynomials to obtain system of equations.
// For particular input message.
for(uint x=0; x<cip->getOutputBlockSize(); x++){
coeffEval[0][x/SIZEOF_ULONG] ^= ((ULONG)outputCip[x])<<(8 * (x % SIZEOF_ULONG));
}
// Proceed polynomial per polynomial, build input basis for FGb.
if (interSampleOutput){
cout << " Generating input basis." << endl << " ";
}
ProgressMonitor pmBasis(0.01);
ULONG numTermsSum=0;
uint polyCtr=0;
for(uint poly=0; poly<numPolynomials; poly++){
// If this polynomial is not selected, do not add it in the input base.
if (isPoly2Take(poly)==false){
continue;
}
// Convert out internal polynomial representation to FGb representation.
ULONG numTerms = 0;
ULONG hash = 0;
uint curPolyIdx = sample*numPolynomials + polyCtr;
inputBasis1[curPolyIdx] = fgb.polynomial2FGb(numVariables, coeffEval, orderLimit, poly, &numTerms, &hash);
numTermsSum += numTerms;
// If zero terms, it is null, do not add it to the base since
// it does not increase basis dimension.
if (numTerms==0 || fgb.isPoly1(inputBasis1[curPolyIdx], numVariables)){
continue;
}
// Polynomial duplicity check, do not add duplicates to the input base.
// Since it does not increase basis dimension.
if (polynomialHashes.count(hash)>0){
//cout << "Polynomial with idx=" << (curPolyIdx) << " is already present in the basis, idx=" << polynomialHashes[hash] << "; hash=" << hex << hash << endl;
continue;
} else {
polynomialHashes.insert(std::pair<ULONG,uint>(hash, curPolyIdx));
}
// Polynomial is unique. Add to the basis.
if (interSampleOutput){
//cout << setw(4) << right << curPolyIdx << " is f_" << poly << endl;
pmBasis.setCur((double)poly / double(numPolynomials));
}
polyCtr+=1;
}
// Update complete basis size.
inputBasisSize+=polyCtr;
// If verbose mode, finish progress bar & write average number of terms in polynomials.
if (interSampleOutput){
pmBasis.setCur(1.0);
cout << "; Number of terms on average: " << ((double)numTermsSum / (double)numPolynomials) << endl;
} else {
// If there is no intersample output, show a general progress bar.
pmSample.setCur((double)sample / (double)samples);
}
}
// Hack: we don't want over-determined system for now, take last
// numVariables equations to the input base.
if (basisReduction > 0 && inputBasisSize > numVariables){
for(uint i=0; i<numVariables; i++){
inputBasis2[i] = inputBasis1[inputBasisSize-1-i];
}
cout << " Number of equations reduced to " << numVariables << endl;
if (dumpInputBase){
cout << " Original basis, size=" << inputBasisSize << endl;
fgb.dumpBasis(numVariables, inputBasis1, inputBasisSize);
}
inputBasisSize = numVariables;
inputBasis = inputBasis2;
}
// Only if general progressbar is shown.
if (!interSampleOutput){
pmSample.setCur(1.0);
cout << endl;
}
// Print out input basis
if (dumpInputBase){
cout << " Input basis, size=" << inputBasisSize << endl;
fgb.dumpBasis(numVariables, inputBasis, inputBasisSize);
}
// Compute Gb.
cout << " [+] Going to compute GB, n_input="<<dec<<inputBasisSize<<endl;
double t0 = 0.0;
int nb = fgb.computeFGb(inputBasisSize, inputBasis, outputBasis, &t0);
// For now just print out the Grobner basis.
fgb.dumpBasis(numVariables, outputBasis, nb);
cout << "Input basis dimension=" << inputBasisSize << endl;
cout << "Basis dimension=" << nb << endl;
cout << "Number of variables=" << numVariables << endl;
cout << "Stats: cpu=" << t0 << endl;
// TODO: use linearization trick.
// TODO: use http://icm.mcs.kent.edu/reports/1995/gb.pdf to solve the system.
cout << " [+] Going to solve GB" << endl;
int haveSol = solveGb(numVariables, outputBasis, nb, keySol);
if (haveSol >= 0){
double hits = 0.0;
double hitRatio;
for(uint i=0; i<numVariables; i++){
// If number of variables is reduced, take this into account
// for precise key bit hit ratio (real key is shifted).
const uint keyIdx = 8*cip->getKeyBlockSize() - numVariables + i;
hits += ((key[keyIdx/8] & (1u << (keyIdx%8))) > 0) == ((keySol[i/8] & (1u << (i%8))) > 0);
}
hitRatio = hits / (double)numVariables;
cout << "Key bit-hit ratio: " << hitRatio << endl;
}
delete[] key;
delete[] keySol;
delete[] input;
delete[] outputCip;
delete[] variablesValueMask;
delete[] iBuff;
delete[] iTmpBuff;
delete[] oTmpBuff;
delete[] inputBasis1;
delete[] inputBasis2;
delete[] outputBasis;
}
int Approximation::solveGb(uint numVariables, Dpol* basis, uint numPoly, uchar * solvedKey) const {
// Detect if system has no solution.
// This happens if Gb = <1>.
if (numPoly==1){
if (fgb.isPoly1(basis[0], numVariables)){
cout << " System generates ideal=<1> what means there is no solution. NumVariables=" << numVariables << endl;
return -2;
}
cout << " System has only 1 equation. Cannot solve such under-determined system. NumVariables=" << numVariables << endl;
return -3;
}
// If system is too under-determined, do not solve it.
if (numVariables > (numPoly+4)){
cout << " Cannot solve (under-determined) system with " << numVariables << " and " << numPoly << " equations right now right now" << endl;
return -1;
}
// TODO: Use linearization trick, now do not use it.
// In order to solve the system, we need to separate constant terms from the
// system of equation to a side vector b
vec_GF2 b(INIT_SIZE, numPoly);
// TODO: in linearization trick, it is needed to substitute complex terms
// with a new linear variable. We have to count the nonspecific terms
// and assign an unique linear representation to each of them.
// Thus size of the matrix is known only AFTER this process of linearization.
mat_GF2 systm(INIT_SIZE, numPoly, numVariables);
// Add polynomial to the systm matrix, constant term to the b vector.
for(uint polyIdx = 0; polyIdx < numPoly; polyIdx++){
const I32 nb_mons = fgb.getNumberOfTerms(basis[polyIdx]); // Number of Monomials.
I32* Mons = new I32[numVariables * nb_mons]; // Exponents for variables in terms.
I32* Cfs = new I32[nb_mons]; // Coefficients for terms.
I32 j;
fgb.exportPolynomial(numVariables, nb_mons, Mons, Cfs, basis[polyIdx]);
for (j = 0; j < nb_mons; j++) {
UI32 k, is_one = 1;
I32* ei = Mons + j*numVariables;
// In GF(2) all non-zero coefficients are 1.
// But check for null anyway.
if (Cfs[j]==0) {
continue;
}
for (k = 0; k < numVariables; k++){
// Exponent of the variable k in the term j.
if (ei[k]==0) continue;
// Coping with the exponents that should not be here - XOR
if (IsZero(systm.get(polyIdx, k))){
systm.put(polyIdx, k, 1ul);
} else {
systm.put(polyIdx, k, 0ul);
}
is_one = 0;
}
// Constant term, should be only 1 in the polynomial.
if (is_one) {
b.put(polyIdx, 1ul);
}
}
delete[] Mons;
delete[] Cfs;
}
//dumpVector(b);
//dumpMatrix(systm);
if (numVariables > systm.NumRows()){
cout << " System is under-determined, rows=" << (systm.NumRows()) << endl;
return -8;
}
// Try to solve the system
mat_GF2 gaussed;
long rank = gaussPh4r05(gaussed, systm, b, numVariables);
if (rank < numVariables){
cout << " Determinant is zero, cannot solve this system. Rank=" << rank << endl;
return -4;
}
// We have solution, convert it to the uchar array and dump in hexa and in the binary.
const uint solByteSize = (uint)ceil(numVariables/8.0);
memset(solvedKey, 0x0, solByteSize);
for(uint i=0; i<numVariables; i++){
if (IsOne(gaussed.get(i, numVariables))){
solvedKey[i/8] |= 1u << (i%8);
}
}
cout << " We have the solution:" << endl;
dumpHex(cout, solvedKey, solByteSize);
dumpBin(cout, solvedKey, solByteSize);
return 1;
}
int Approximation::partialEvaluation(const std::vector<ULONG> * coefficients,
uint numVariables, ULONG * variablesValueMask, ULONG * iBuff, std::vector<ULONG> * coeffEval) const{