Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

852 lines
25 KiB

  1. // test.cpp - written and placed in the public domain by Wei Dai
  2. #define _CRT_SECURE_NO_DEPRECATE
  3. #define CRYPTOPP_DEFAULT_NO_DLL
  4. #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
  5. #include "dll.h"
  6. #include "md5.h"
  7. #include "ripemd.h"
  8. #include "rng.h"
  9. #include "gzip.h"
  10. #include "default.h"
  11. #include "randpool.h"
  12. #include "ida.h"
  13. #include "base64.h"
  14. #include "socketft.h"
  15. #include "wait.h"
  16. #include "factory.h"
  17. #include "whrlpool.h"
  18. #include "tiger.h"
  19. #include "validate.h"
  20. #include "bench.h"
  21. #include <iostream>
  22. #include <time.h>
  23. #ifdef CRYPTOPP_WIN32_AVAILABLE
  24. #include <windows.h>
  25. #endif
  26. #if defined(USE_BERKELEY_STYLE_SOCKETS) && !defined(macintosh)
  27. #include <netinet/in.h>
  28. #include <netinet/tcp.h>
  29. #endif
  30. #if (_MSC_VER >= 1000)
  31. #include <crtdbg.h> // for the debug heap
  32. #endif
  33. #if defined(__MWERKS__) && defined(macintosh)
  34. #include <console.h>
  35. #endif
  36. #ifdef __BORLANDC__
  37. #pragma comment(lib, "cryptlib_bds.lib")
  38. #pragma comment(lib, "ws2_32.lib")
  39. #endif
  40. USING_NAMESPACE(CryptoPP)
  41. USING_NAMESPACE(std)
  42. const int MAX_PHRASE_LENGTH=250;
  43. void RegisterFactories();
  44. void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed);
  45. string RSAEncryptString(const char *pubFilename, const char *seed, const char *message);
  46. string RSADecryptString(const char *privFilename, const char *ciphertext);
  47. void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename);
  48. bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename);
  49. void DigestFile(const char *file);
  50. void HmacFile(const char *hexKey, const char *file);
  51. void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile);
  52. string EncryptString(const char *plaintext, const char *passPhrase);
  53. string DecryptString(const char *ciphertext, const char *passPhrase);
  54. void EncryptFile(const char *in, const char *out, const char *passPhrase);
  55. void DecryptFile(const char *in, const char *out, const char *passPhrase);
  56. void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed);
  57. void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames);
  58. void InformationDisperseFile(int threshold, int nShares, const char *filename);
  59. void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames);
  60. void GzipFile(const char *in, const char *out, int deflate_level);
  61. void GunzipFile(const char *in, const char *out);
  62. void Base64Encode(const char *infile, const char *outfile);
  63. void Base64Decode(const char *infile, const char *outfile);
  64. void HexEncode(const char *infile, const char *outfile);
  65. void HexDecode(const char *infile, const char *outfile);
  66. void ForwardTcpPort(const char *sourcePort, const char *destinationHost, const char *destinationPort);
  67. void FIPS140_SampleApplication();
  68. void FIPS140_GenerateRandomFiles();
  69. bool Validate(int, bool, const char *);
  70. int (*AdhocTest)(int argc, char *argv[]) = NULL;
  71. static OFB_Mode<AES>::Encryption s_globalRNG;
  72. RandomNumberGenerator & GlobalRNG()
  73. {
  74. return s_globalRNG;
  75. }
  76. int CRYPTOPP_API main(int argc, char *argv[])
  77. {
  78. #ifdef _CRTDBG_LEAK_CHECK_DF
  79. // Turn on leak-checking
  80. int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
  81. tempflag |= _CRTDBG_LEAK_CHECK_DF;
  82. _CrtSetDbgFlag( tempflag );
  83. #endif
  84. #if defined(__MWERKS__) && defined(macintosh)
  85. argc = ccommand(&argv);
  86. #endif
  87. try
  88. {
  89. RegisterFactories();
  90. std::string seed = IntToString(time(NULL));
  91. seed.resize(16);
  92. s_globalRNG.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data());
  93. std::string command, executableName, macFilename;
  94. if (argc < 2)
  95. command = 'h';
  96. else
  97. command = argv[1];
  98. if (command == "g")
  99. {
  100. char seed[1024], privFilename[128], pubFilename[128];
  101. unsigned int keyLength;
  102. cout << "Key length in bits: ";
  103. cin >> keyLength;
  104. cout << "\nSave private key to file: ";
  105. cin >> privFilename;
  106. cout << "\nSave public key to file: ";
  107. cin >> pubFilename;
  108. cout << "\nRandom Seed: ";
  109. ws(cin);
  110. cin.getline(seed, 1024);
  111. GenerateRSAKey(keyLength, privFilename, pubFilename, seed);
  112. }
  113. else if (command == "rs")
  114. RSASignFile(argv[2], argv[3], argv[4]);
  115. else if (command == "rv")
  116. {
  117. bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]);
  118. cout << (verified ? "valid signature" : "invalid signature") << endl;
  119. }
  120. else if (command == "r")
  121. {
  122. char privFilename[128], pubFilename[128];
  123. char seed[1024], message[1024];
  124. cout << "Private key file: ";
  125. cin >> privFilename;
  126. cout << "\nPublic key file: ";
  127. cin >> pubFilename;
  128. cout << "\nRandom Seed: ";
  129. ws(cin);
  130. cin.getline(seed, 1024);
  131. cout << "\nMessage: ";
  132. cin.getline(message, 1024);
  133. string ciphertext = RSAEncryptString(pubFilename, seed, message);
  134. cout << "\nCiphertext: " << ciphertext << endl;
  135. string decrypted = RSADecryptString(privFilename, ciphertext.c_str());
  136. cout << "\nDecrypted: " << decrypted << endl;
  137. }
  138. else if (command == "mt")
  139. {
  140. MaurerRandomnessTest mt;
  141. FileStore fs(argv[2]);
  142. fs.TransferAllTo(mt);
  143. cout << "Maurer Test Value: " << mt.GetTestValue() << endl;
  144. }
  145. else if (command == "mac_dll")
  146. {
  147. // sanity check on file size
  148. std::fstream dllFile(argv[2], ios::in | ios::out | ios::binary);
  149. std::ifstream::pos_type fileEnd = dllFile.seekg(0, std::ios_base::end).tellg();
  150. if (fileEnd > 20*1000*1000)
  151. {
  152. cerr << "Input file too large (more than 20 MB).\n";
  153. return 1;
  154. }
  155. // read file into memory
  156. unsigned int fileSize = (unsigned int)fileEnd;
  157. SecByteBlock buf(fileSize);
  158. dllFile.seekg(0, std::ios_base::beg);
  159. dllFile.read((char *)buf.begin(), fileSize);
  160. // find positions of relevant sections in the file, based on version 8 of documentation from http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
  161. word32 coffPos = *(word16 *)(buf+0x3c);
  162. word32 optionalHeaderPos = coffPos + 24;
  163. word16 optionalHeaderMagic = *(word16 *)(buf+optionalHeaderPos);
  164. if (optionalHeaderMagic != 0x10b && optionalHeaderMagic != 0x20b)
  165. {
  166. cerr << "Target file is not a PE32 or PE32+ image.\n";
  167. return 3;
  168. }
  169. word32 checksumPos = optionalHeaderPos + 64;
  170. word32 certificateTableDirectoryPos = optionalHeaderPos + (optionalHeaderMagic == 0x10b ? 128 : 144);
  171. word32 certificateTablePos = *(word32 *)(buf+certificateTableDirectoryPos);
  172. word32 certificateTableSize = *(word32 *)(buf+certificateTableDirectoryPos+4);
  173. if (certificateTableSize != 0)
  174. cerr << "Warning: certificate table (IMAGE_DIRECTORY_ENTRY_SECURITY) of target image is not empty.\n";
  175. // find where to place computed MAC
  176. byte mac[] = CRYPTOPP_DUMMY_DLL_MAC;
  177. byte *found = std::search(buf.begin(), buf.end(), mac+0, mac+sizeof(mac));
  178. if (found == buf.end())
  179. {
  180. cerr << "MAC placeholder not found. Possibly the actual MAC was already placed.\n";
  181. return 2;
  182. }
  183. word32 macPos = (unsigned int)(found-buf.begin());
  184. // compute MAC
  185. member_ptr<MessageAuthenticationCode> pMac(NewIntegrityCheckingMAC());
  186. assert(pMac->DigestSize() == sizeof(mac));
  187. MeterFilter f(new HashFilter(*pMac, new ArraySink(mac, sizeof(mac))));
  188. f.AddRangeToSkip(0, checksumPos, 4);
  189. f.AddRangeToSkip(0, certificateTableDirectoryPos, 8);
  190. f.AddRangeToSkip(0, macPos, sizeof(mac));
  191. f.AddRangeToSkip(0, certificateTablePos, certificateTableSize);
  192. f.PutMessageEnd(buf.begin(), buf.size());
  193. // place MAC
  194. cout << "Placing MAC in file " << argv[2] << ", location " << macPos << ".\n";
  195. dllFile.seekg(macPos, std::ios_base::beg);
  196. dllFile.write((char *)mac, sizeof(mac));
  197. }
  198. else if (command == "m")
  199. DigestFile(argv[2]);
  200. else if (command == "tv")
  201. {
  202. std::string fname = argv[2];
  203. if (fname.find(".txt") == std::string::npos)
  204. fname = "TestVectors/" + fname + ".txt";
  205. return !RunTestDataFile(fname.c_str());
  206. }
  207. else if (command == "t")
  208. {
  209. // VC60 workaround: use char array instead of std::string to workaround MSVC's getline bug
  210. char passPhrase[MAX_PHRASE_LENGTH], plaintext[1024];
  211. cout << "Passphrase: ";
  212. cin.getline(passPhrase, MAX_PHRASE_LENGTH);
  213. cout << "\nPlaintext: ";
  214. cin.getline(plaintext, 1024);
  215. string ciphertext = EncryptString(plaintext, passPhrase);
  216. cout << "\nCiphertext: " << ciphertext << endl;
  217. string decrypted = DecryptString(ciphertext.c_str(), passPhrase);
  218. cout << "\nDecrypted: " << decrypted << endl;
  219. return 0;
  220. }
  221. else if (command == "e64")
  222. Base64Encode(argv[2], argv[3]);
  223. else if (command == "d64")
  224. Base64Decode(argv[2], argv[3]);
  225. else if (command == "e16")
  226. HexEncode(argv[2], argv[3]);
  227. else if (command == "d16")
  228. HexDecode(argv[2], argv[3]);
  229. else if (command == "e" || command == "d")
  230. {
  231. char passPhrase[MAX_PHRASE_LENGTH];
  232. cout << "Passphrase: ";
  233. cin.getline(passPhrase, MAX_PHRASE_LENGTH);
  234. if (command == "e")
  235. EncryptFile(argv[2], argv[3], passPhrase);
  236. else
  237. DecryptFile(argv[2], argv[3], passPhrase);
  238. }
  239. else if (command == "ss")
  240. {
  241. char seed[1024];
  242. cout << "\nRandom Seed: ";
  243. ws(cin);
  244. cin.getline(seed, 1024);
  245. SecretShareFile(atoi(argv[2]), atoi(argv[3]), argv[4], seed);
  246. }
  247. else if (command == "sr")
  248. SecretRecoverFile(argc-3, argv[2], argv+3);
  249. else if (command == "id")
  250. InformationDisperseFile(atoi(argv[2]), atoi(argv[3]), argv[4]);
  251. else if (command == "ir")
  252. InformationRecoverFile(argc-3, argv[2], argv+3);
  253. else if (command == "v" || command == "vv")
  254. return !Validate(argc>2 ? atoi(argv[2]) : 0, argv[1][1] == 'v', argc>3 ? argv[3] : NULL);
  255. else if (command == "b")
  256. BenchmarkAll(argc<3 ? 1 : atof(argv[2]), argc<4 ? 0 : atof(argv[3])*1e9);
  257. else if (command == "b2")
  258. BenchmarkAll2(argc<3 ? 1 : atof(argv[2]), argc<4 ? 0 : atof(argv[3])*1e9);
  259. else if (command == "z")
  260. GzipFile(argv[3], argv[4], argv[2][0]-'0');
  261. else if (command == "u")
  262. GunzipFile(argv[2], argv[3]);
  263. else if (command == "fips")
  264. FIPS140_SampleApplication();
  265. else if (command == "fips-rand")
  266. FIPS140_GenerateRandomFiles();
  267. else if (command == "ft")
  268. ForwardTcpPort(argv[2], argv[3], argv[4]);
  269. else if (command == "a")
  270. {
  271. if (AdhocTest)
  272. return (*AdhocTest)(argc, argv);
  273. else
  274. {
  275. cerr << "AdhocTest not defined.\n";
  276. return 1;
  277. }
  278. }
  279. else if (command == "hmac")
  280. HmacFile(argv[2], argv[3]);
  281. else if (command == "ae")
  282. AES_CTR_Encrypt(argv[2], argv[3], argv[4], argv[5]);
  283. else if (command == "h")
  284. {
  285. FileSource usage("TestData/usage.dat", true, new FileSink(cout));
  286. return 1;
  287. }
  288. else if (command == "V")
  289. {
  290. cout << CRYPTOPP_VERSION / 100 << '.' << (CRYPTOPP_VERSION % 100) / 10 << '.' << CRYPTOPP_VERSION % 10 << endl;
  291. }
  292. else
  293. {
  294. cerr << "Unrecognized command. Run \"cryptest h\" to obtain usage information.\n";
  295. return 1;
  296. }
  297. return 0;
  298. }
  299. catch(CryptoPP::Exception &e)
  300. {
  301. cout << "\nCryptoPP::Exception caught: " << e.what() << endl;
  302. return -1;
  303. }
  304. catch(std::exception &e)
  305. {
  306. cout << "\nstd::exception caught: " << e.what() << endl;
  307. return -2;
  308. }
  309. }
  310. void FIPS140_GenerateRandomFiles()
  311. {
  312. #ifdef OS_RNG_AVAILABLE
  313. DefaultAutoSeededRNG rng;
  314. RandomNumberStore store(rng, ULONG_MAX);
  315. for (unsigned int i=0; i<100000; i++)
  316. store.TransferTo(FileSink((IntToString(i) + ".rnd").c_str()).Ref(), 20000);
  317. #else
  318. cout << "OS provided RNG not available.\n";
  319. exit(-1);
  320. #endif
  321. }
  322. SecByteBlock HexDecodeString(const char *hex)
  323. {
  324. StringSource ss(hex, true, new HexDecoder);
  325. SecByteBlock result((size_t)ss.MaxRetrievable());
  326. ss.Get(result, result.size());
  327. return result;
  328. }
  329. void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed)
  330. {
  331. RandomPool randPool;
  332. randPool.IncorporateEntropy((byte *)seed, strlen(seed));
  333. RSAES_OAEP_SHA_Decryptor priv(randPool, keyLength);
  334. HexEncoder privFile(new FileSink(privFilename));
  335. priv.DEREncode(privFile);
  336. privFile.MessageEnd();
  337. RSAES_OAEP_SHA_Encryptor pub(priv);
  338. HexEncoder pubFile(new FileSink(pubFilename));
  339. pub.DEREncode(pubFile);
  340. pubFile.MessageEnd();
  341. }
  342. string RSAEncryptString(const char *pubFilename, const char *seed, const char *message)
  343. {
  344. FileSource pubFile(pubFilename, true, new HexDecoder);
  345. RSAES_OAEP_SHA_Encryptor pub(pubFile);
  346. RandomPool randPool;
  347. randPool.IncorporateEntropy((byte *)seed, strlen(seed));
  348. string result;
  349. StringSource(message, true, new PK_EncryptorFilter(randPool, pub, new HexEncoder(new StringSink(result))));
  350. return result;
  351. }
  352. string RSADecryptString(const char *privFilename, const char *ciphertext)
  353. {
  354. FileSource privFile(privFilename, true, new HexDecoder);
  355. RSAES_OAEP_SHA_Decryptor priv(privFile);
  356. string result;
  357. StringSource(ciphertext, true, new HexDecoder(new PK_DecryptorFilter(GlobalRNG(), priv, new StringSink(result))));
  358. return result;
  359. }
  360. void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename)
  361. {
  362. FileSource privFile(privFilename, true, new HexDecoder);
  363. RSASS<PKCS1v15, SHA>::Signer priv(privFile);
  364. FileSource f(messageFilename, true, new SignerFilter(GlobalRNG(), priv, new HexEncoder(new FileSink(signatureFilename))));
  365. }
  366. bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename)
  367. {
  368. FileSource pubFile(pubFilename, true, new HexDecoder);
  369. RSASS<PKCS1v15, SHA>::Verifier pub(pubFile);
  370. FileSource signatureFile(signatureFilename, true, new HexDecoder);
  371. if (signatureFile.MaxRetrievable() != pub.SignatureLength())
  372. return false;
  373. SecByteBlock signature(pub.SignatureLength());
  374. signatureFile.Get(signature, signature.size());
  375. VerifierFilter *verifierFilter = new VerifierFilter(pub);
  376. verifierFilter->Put(signature, pub.SignatureLength());
  377. FileSource f(messageFilename, true, verifierFilter);
  378. return verifierFilter->GetLastResult();
  379. }
  380. void DigestFile(const char *filename)
  381. {
  382. SHA1 sha;
  383. RIPEMD160 ripemd;
  384. SHA256 sha256;
  385. Tiger tiger;
  386. SHA512 sha512;
  387. Whirlpool whirlpool;
  388. vector_member_ptrs<HashFilter> filters(6);
  389. filters[0].reset(new HashFilter(sha));
  390. filters[1].reset(new HashFilter(ripemd));
  391. filters[2].reset(new HashFilter(tiger));
  392. filters[3].reset(new HashFilter(sha256));
  393. filters[4].reset(new HashFilter(sha512));
  394. filters[5].reset(new HashFilter(whirlpool));
  395. auto_ptr<ChannelSwitch> channelSwitch(new ChannelSwitch);
  396. size_t i;
  397. for (i=0; i<filters.size(); i++)
  398. channelSwitch->AddDefaultRoute(*filters[i]);
  399. FileSource(filename, true, channelSwitch.release());
  400. HexEncoder encoder(new FileSink(cout), false);
  401. for (i=0; i<filters.size(); i++)
  402. {
  403. cout << filters[i]->AlgorithmName() << ": ";
  404. filters[i]->TransferTo(encoder);
  405. cout << "\n";
  406. }
  407. }
  408. void HmacFile(const char *hexKey, const char *file)
  409. {
  410. member_ptr<MessageAuthenticationCode> mac;
  411. if (strcmp(hexKey, "selftest") == 0)
  412. {
  413. cerr << "Computing HMAC/SHA1 value for self test.\n";
  414. mac.reset(NewIntegrityCheckingMAC());
  415. }
  416. else
  417. {
  418. std::string decodedKey;
  419. StringSource(hexKey, true, new HexDecoder(new StringSink(decodedKey)));
  420. mac.reset(new HMAC<SHA1>((const byte *)decodedKey.data(), decodedKey.size()));
  421. }
  422. FileSource(file, true, new HashFilter(*mac, new HexEncoder(new FileSink(cout))));
  423. }
  424. void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile)
  425. {
  426. SecByteBlock key = HexDecodeString(hexKey);
  427. SecByteBlock iv = HexDecodeString(hexIV);
  428. CTR_Mode<AES>::Encryption aes(key, key.size(), iv);
  429. FileSource(infile, true, new StreamTransformationFilter(aes, new FileSink(outfile)));
  430. }
  431. string EncryptString(const char *instr, const char *passPhrase)
  432. {
  433. string outstr;
  434. DefaultEncryptorWithMAC encryptor(passPhrase, new HexEncoder(new StringSink(outstr)));
  435. encryptor.Put((byte *)instr, strlen(instr));
  436. encryptor.MessageEnd();
  437. return outstr;
  438. }
  439. string DecryptString(const char *instr, const char *passPhrase)
  440. {
  441. string outstr;
  442. HexDecoder decryptor(new DefaultDecryptorWithMAC(passPhrase, new StringSink(outstr)));
  443. decryptor.Put((byte *)instr, strlen(instr));
  444. decryptor.MessageEnd();
  445. return outstr;
  446. }
  447. void EncryptFile(const char *in, const char *out, const char *passPhrase)
  448. {
  449. FileSource f(in, true, new DefaultEncryptorWithMAC(passPhrase, new FileSink(out)));
  450. }
  451. void DecryptFile(const char *in, const char *out, const char *passPhrase)
  452. {
  453. FileSource f(in, true, new DefaultDecryptorWithMAC(passPhrase, new FileSink(out)));
  454. }
  455. void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed)
  456. {
  457. assert(nShares<=1000);
  458. RandomPool rng;
  459. rng.IncorporateEntropy((byte *)seed, strlen(seed));
  460. ChannelSwitch *channelSwitch;
  461. FileSource source(filename, false, new SecretSharing(rng, threshold, nShares, channelSwitch = new ChannelSwitch));
  462. vector_member_ptrs<FileSink> fileSinks(nShares);
  463. string channel;
  464. for (int i=0; i<nShares; i++)
  465. {
  466. char extension[5] = ".000";
  467. extension[1]='0'+byte(i/100);
  468. extension[2]='0'+byte((i/10)%10);
  469. extension[3]='0'+byte(i%10);
  470. fileSinks[i].reset(new FileSink((string(filename)+extension).c_str()));
  471. channel = WordToString<word32>(i);
  472. fileSinks[i]->Put((byte *)channel.data(), 4);
  473. channelSwitch->AddRoute(channel, *fileSinks[i], DEFAULT_CHANNEL);
  474. }
  475. source.PumpAll();
  476. }
  477. void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames)
  478. {
  479. assert(threshold<=1000);
  480. SecretRecovery recovery(threshold, new FileSink(outFilename));
  481. vector_member_ptrs<FileSource> fileSources(threshold);
  482. SecByteBlock channel(4);
  483. int i;
  484. for (i=0; i<threshold; i++)
  485. {
  486. fileSources[i].reset(new FileSource(inFilenames[i], false));
  487. fileSources[i]->Pump(4);
  488. fileSources[i]->Get(channel, 4);
  489. fileSources[i]->Attach(new ChannelSwitch(recovery, string((char *)channel.begin(), 4)));
  490. }
  491. while (fileSources[0]->Pump(256))
  492. for (i=1; i<threshold; i++)
  493. fileSources[i]->Pump(256);
  494. for (i=0; i<threshold; i++)
  495. fileSources[i]->PumpAll();
  496. }
  497. void InformationDisperseFile(int threshold, int nShares, const char *filename)
  498. {
  499. assert(nShares<=1000);
  500. ChannelSwitch *channelSwitch;
  501. FileSource source(filename, false, new InformationDispersal(threshold, nShares, channelSwitch = new ChannelSwitch));
  502. vector_member_ptrs<FileSink> fileSinks(nShares);
  503. string channel;
  504. for (int i=0; i<nShares; i++)
  505. {
  506. char extension[5] = ".000";
  507. extension[1]='0'+byte(i/100);
  508. extension[2]='0'+byte((i/10)%10);
  509. extension[3]='0'+byte(i%10);
  510. fileSinks[i].reset(new FileSink((string(filename)+extension).c_str()));
  511. channel = WordToString<word32>(i);
  512. fileSinks[i]->Put((byte *)channel.data(), 4);
  513. channelSwitch->AddRoute(channel, *fileSinks[i], DEFAULT_CHANNEL);
  514. }
  515. source.PumpAll();
  516. }
  517. void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames)
  518. {
  519. assert(threshold<=1000);
  520. InformationRecovery recovery(threshold, new FileSink(outFilename));
  521. vector_member_ptrs<FileSource> fileSources(threshold);
  522. SecByteBlock channel(4);
  523. int i;
  524. for (i=0; i<threshold; i++)
  525. {
  526. fileSources[i].reset(new FileSource(inFilenames[i], false));
  527. fileSources[i]->Pump(4);
  528. fileSources[i]->Get(channel, 4);
  529. fileSources[i]->Attach(new ChannelSwitch(recovery, string((char *)channel.begin(), 4)));
  530. }
  531. while (fileSources[0]->Pump(256))
  532. for (i=1; i<threshold; i++)
  533. fileSources[i]->Pump(256);
  534. for (i=0; i<threshold; i++)
  535. fileSources[i]->PumpAll();
  536. }
  537. void GzipFile(const char *in, const char *out, int deflate_level)
  538. {
  539. // FileSource(in, true, new Gzip(new FileSink(out), deflate_level));
  540. // use a filter graph to compare decompressed data with original
  541. //
  542. // Source ----> Gzip ------> Sink
  543. // \ |
  544. // \ Gunzip
  545. // \ |
  546. // \ v
  547. // > ComparisonFilter
  548. EqualityComparisonFilter comparison;
  549. Gunzip gunzip(new ChannelSwitch(comparison, "0"));
  550. gunzip.SetAutoSignalPropagation(0);
  551. FileSink sink(out);
  552. ChannelSwitch *cs;
  553. Gzip gzip(cs = new ChannelSwitch(sink), deflate_level);
  554. cs->AddDefaultRoute(gunzip);
  555. cs = new ChannelSwitch(gzip);
  556. cs->AddDefaultRoute(comparison, "1");
  557. FileSource source(in, true, cs);
  558. comparison.ChannelMessageSeriesEnd("0");
  559. comparison.ChannelMessageSeriesEnd("1");
  560. }
  561. void GunzipFile(const char *in, const char *out)
  562. {
  563. FileSource(in, true, new Gunzip(new FileSink(out)));
  564. }
  565. void Base64Encode(const char *in, const char *out)
  566. {
  567. FileSource(in, true, new Base64Encoder(new FileSink(out)));
  568. }
  569. void Base64Decode(const char *in, const char *out)
  570. {
  571. FileSource(in, true, new Base64Decoder(new FileSink(out)));
  572. }
  573. void HexEncode(const char *in, const char *out)
  574. {
  575. FileSource(in, true, new HexEncoder(new FileSink(out)));
  576. }
  577. void HexDecode(const char *in, const char *out)
  578. {
  579. FileSource(in, true, new HexDecoder(new FileSink(out)));
  580. }
  581. void ForwardTcpPort(const char *sourcePortName, const char *destinationHost, const char *destinationPortName)
  582. {
  583. #ifdef SOCKETS_AVAILABLE
  584. SocketsInitializer sockInit;
  585. Socket sockListen, sockSource, sockDestination;
  586. int sourcePort = Socket::PortNameToNumber(sourcePortName);
  587. int destinationPort = Socket::PortNameToNumber(destinationPortName);
  588. sockListen.Create();
  589. sockListen.Bind(sourcePort);
  590. setsockopt(sockListen, IPPROTO_TCP, TCP_NODELAY, "\x01", 1);
  591. cout << "Listing on port " << sourcePort << ".\n";
  592. sockListen.Listen();
  593. sockListen.Accept(sockSource);
  594. cout << "Connection accepted on port " << sourcePort << ".\n";
  595. sockListen.CloseSocket();
  596. cout << "Making connection to " << destinationHost << ", port " << destinationPort << ".\n";
  597. sockDestination.Create();
  598. sockDestination.Connect(destinationHost, destinationPort);
  599. cout << "Connection made to " << destinationHost << ", starting to forward.\n";
  600. SocketSource out(sockSource, false, new SocketSink(sockDestination));
  601. SocketSource in(sockDestination, false, new SocketSink(sockSource));
  602. WaitObjectContainer waitObjects;
  603. while (!(in.SourceExhausted() && out.SourceExhausted()))
  604. {
  605. waitObjects.Clear();
  606. out.GetWaitObjects(waitObjects, CallStack("ForwardTcpPort - out", NULL));
  607. in.GetWaitObjects(waitObjects, CallStack("ForwardTcpPort - in", NULL));
  608. waitObjects.Wait(INFINITE_TIME);
  609. if (!out.SourceExhausted())
  610. {
  611. cout << "o" << flush;
  612. out.PumpAll2(false);
  613. if (out.SourceExhausted())
  614. cout << "EOF received on source socket.\n";
  615. }
  616. if (!in.SourceExhausted())
  617. {
  618. cout << "i" << flush;
  619. in.PumpAll2(false);
  620. if (in.SourceExhausted())
  621. cout << "EOF received on destination socket.\n";
  622. }
  623. }
  624. #else
  625. cout << "Socket support was not enabled at compile time.\n";
  626. exit(-1);
  627. #endif
  628. }
  629. bool Validate(int alg, bool thorough, const char *seedInput)
  630. {
  631. bool result;
  632. std::string seed = seedInput ? std::string(seedInput) : IntToString(time(NULL));
  633. seed.resize(16);
  634. cout << "Using seed: " << seed << endl << endl;
  635. s_globalRNG.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data());
  636. switch (alg)
  637. {
  638. case 0: result = ValidateAll(thorough); break;
  639. case 1: result = TestSettings(); break;
  640. case 2: result = TestOS_RNG(); break;
  641. case 3: result = ValidateMD5(); break;
  642. case 4: result = ValidateSHA(); break;
  643. case 5: result = ValidateDES(); break;
  644. case 6: result = ValidateIDEA(); break;
  645. case 7: result = ValidateARC4(); break;
  646. case 8: result = ValidateRC5(); break;
  647. case 9: result = ValidateBlowfish(); break;
  648. // case 10: result = ValidateDiamond2(); break;
  649. case 11: result = ValidateThreeWay(); break;
  650. case 12: result = ValidateBBS(); break;
  651. case 13: result = ValidateDH(); break;
  652. case 14: result = ValidateRSA(); break;
  653. case 15: result = ValidateElGamal(); break;
  654. case 16: result = ValidateDSA(thorough); break;
  655. // case 17: result = ValidateHAVAL(); break;
  656. case 18: result = ValidateSAFER(); break;
  657. case 19: result = ValidateLUC(); break;
  658. case 20: result = ValidateRabin(); break;
  659. // case 21: result = ValidateBlumGoldwasser(); break;
  660. case 22: result = ValidateECP(); break;
  661. case 23: result = ValidateEC2N(); break;
  662. // case 24: result = ValidateMD5MAC(); break;
  663. case 25: result = ValidateGOST(); break;
  664. case 26: result = ValidateTiger(); break;
  665. case 27: result = ValidateRIPEMD(); break;
  666. case 28: result = ValidateHMAC(); break;
  667. // case 29: result = ValidateXMACC(); break;
  668. case 30: result = ValidateSHARK(); break;
  669. case 32: result = ValidateLUC_DH(); break;
  670. case 33: result = ValidateLUC_DL(); break;
  671. case 34: result = ValidateSEAL(); break;
  672. case 35: result = ValidateCAST(); break;
  673. case 36: result = ValidateSquare(); break;
  674. case 37: result = ValidateRC2(); break;
  675. case 38: result = ValidateRC6(); break;
  676. case 39: result = ValidateMARS(); break;
  677. case 40: result = ValidateRW(); break;
  678. case 41: result = ValidateMD2(); break;
  679. case 42: result = ValidateNR(); break;
  680. case 43: result = ValidateMQV(); break;
  681. case 44: result = ValidateRijndael(); break;
  682. case 45: result = ValidateTwofish(); break;
  683. case 46: result = ValidateSerpent(); break;
  684. case 47: result = ValidateCipherModes(); break;
  685. case 48: result = ValidateCRC32(); break;
  686. case 49: result = ValidateECDSA(); break;
  687. case 50: result = ValidateXTR_DH(); break;
  688. case 51: result = ValidateSKIPJACK(); break;
  689. case 52: result = ValidateSHA2(); break;
  690. case 53: result = ValidatePanama(); break;
  691. case 54: result = ValidateAdler32(); break;
  692. case 55: result = ValidateMD4(); break;
  693. case 56: result = ValidatePBKDF(); break;
  694. case 57: result = ValidateESIGN(); break;
  695. case 58: result = ValidateDLIES(); break;
  696. case 59: result = ValidateBaseCode(); break;
  697. case 60: result = ValidateSHACAL2(); break;
  698. case 61: result = ValidateCamellia(); break;
  699. case 62: result = ValidateWhirlpool(); break;
  700. case 63: result = ValidateTTMAC(); break;
  701. case 64: result = ValidateSalsa(); break;
  702. case 65: result = ValidateSosemanuk(); break;
  703. case 66: result = ValidateVMAC(); break;
  704. case 67: result = ValidateCCM(); break;
  705. case 68: result = ValidateGCM(); break;
  706. case 69: result = ValidateCMAC(); break;
  707. default: return false;
  708. }
  709. time_t endTime = time(NULL);
  710. cout << "\nTest ended at " << asctime(localtime(&endTime));
  711. cout << "Seed used was: " << seed << endl;
  712. return result;
  713. }