├── tests ├── mt_test_ints.txt ├── ruby_test_ints.txt ├── php-mt_rand_ints.txt ├── ruby_test_bounded_ints.txt ├── glibc_test_ints.txt ├── java_test_ints.txt ├── README.md ├── TestJava.h ├── TestRuby.h ├── TestMt19937.h ├── Test_PHP_mt19937.h ├── TestPRNGFactory.h ├── TestUntwister.h ├── TestMt19937.cpp ├── runner.cpp ├── Test_PHP_mt19937.cpp ├── TestJava.cpp ├── TestRuby.cpp ├── TestPRNGFactory.cpp └── TestUntwister.cpp ├── .gitignore ├── prngs ├── LSBState.h ├── LSBStatePHP5_rand.h ├── PRNGFactory.h ├── LSBState.cpp ├── LSBStatePHP5_rand.cpp ├── Mt19937.h ├── Java.h ├── Ruby.h ├── PRNGFactory.cpp ├── GlibcRand.h ├── PHP5_rand.h ├── PHP_mt19937.h ├── PRNG.h ├── Mt19937.cpp ├── Java.cpp ├── DotNetSystemRandom.h ├── Ruby.cpp ├── PHP_mt19937.cpp ├── DotNetSystemRandom.cpp ├── GlibcRand.cpp └── PHP5_rand.cpp ├── AddingNewPRNG.txt ├── ConsoleColors.h ├── Untwister.h ├── README.md ├── Makefile ├── py-untwister.cpp ├── Untwister.cpp ├── main.cpp └── LICENSE /tests/mt_test_ints.txt: -------------------------------------------------------------------------------- 1 | 3486555978 2 | 3110953661 3 | 1886093297 4 | 3798442133 5 | 4240579641 6 | 1803353025 7 | 3808769883 8 | 4070703956 9 | 2713382732 10 | 918155256 11 | -------------------------------------------------------------------------------- /tests/ruby_test_ints.txt: -------------------------------------------------------------------------------- 1 | 3486555978 2 | 3110953661 3 | 1886093297 4 | 3798442133 5 | 4240579641 6 | 1803353025 7 | 3808769883 8 | 4070703956 9 | 2713382732 10 | 918155256 11 | -------------------------------------------------------------------------------- /tests/php-mt_rand_ints.txt: -------------------------------------------------------------------------------- 1 | 590238509 2 | 418805881 3 | 83861629 4 | 1458649864 5 | 1538554408 6 | 1501063109 7 | 1789221162 8 | 1608203025 9 | 1356521264 10 | 132047015 11 | 36783685 12 | 753030032 13 | 281142779 14 | 54541460 15 | 1796858210 16 | 867678492 17 | 470082455 18 | 1616526932 19 | 1486592084 20 | -------------------------------------------------------------------------------- /tests/ruby_test_bounded_ints.txt: -------------------------------------------------------------------------------- 1 | #bounds [100-999] 2 | 251 3 | 289 4 | 960 5 | 332 6 | 267 7 | 573 8 | 779 9 | 446 10 | 982 11 | 182 12 | 184 13 | #172 This number intentionally removed to test that it doesn't need to be sequantial 14 | 365 15 | 490 16 | 538 17 | 446 18 | 123 19 | 764 20 | 229 21 | 895 22 | -------------------------------------------------------------------------------- /tests/glibc_test_ints.txt: -------------------------------------------------------------------------------- 1 | 292616681 2 | 1638893262 3 | 255706927 4 | 995816787 5 | 588263094 6 | 1540293802 7 | 343418821 8 | 903681492 9 | 898530248 10 | 1459533395 11 | 276971287 12 | 2009154155 13 | 53369804 14 | 1490425251 15 | 552672860 16 | 21619323 17 | 1699833725 18 | 664174788 19 | 790840026 20 | 1896536826 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Object files 2 | *.o 3 | *.ko 4 | 5 | # Libraries 6 | *.lib 7 | *.a 8 | *.d 9 | # Shared objects (inc. Windows DLLs) 10 | *.dll 11 | *.so 12 | *.so.* 13 | *.dylib 14 | 15 | # Executables 16 | *.exe 17 | *.out 18 | *.app 19 | *.py 20 | *.pyc 21 | # Deleted files 22 | *~ 23 | 24 | # clang dirs 25 | untwister.dSYM/ 26 | untwister.dSYM/* 27 | 28 | #Program executables 29 | untwister 30 | untwister_tests 31 | 32 | #git files 33 | *.orig 34 | -------------------------------------------------------------------------------- /tests/java_test_ints.txt: -------------------------------------------------------------------------------- 1 | #Seed of 1337 2 | #NOTE: These have been casted into unsigned 32 bit ints. Java natively outputs signed ints. Plan accordingly. 3 | 2834376842 4 | 747279288 5 | 2960274719 6 | 3755296844 7 | 3793627218 8 | 4151553297 9 | 3859060607 10 | 3489606009 11 | 749770455 12 | 2753498935 13 | 4045668812 14 | 3956000846 15 | 635996137 16 | 90530340 17 | 1369061647 18 | 4236068861 19 | 3491862381 20 | 442009989 21 | 2734985908 22 | 3808181844 23 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | Unit Tests 2 | ============== 3 | 4 | These unit tests are written using [CPPUnit](http://cppunit.sourceforge.net/doc/cvs/), you will need it installed on your system to compile the tests. 5 | 6 | To execute the tests, from the project folder: 7 | 8 | ``` 9 | make tests 10 | ./untwister_tests 11 | ``` 12 | 13 | ### Ubuntu/Debian Linux 14 | 15 | ``` 16 | apt-get install libcppunit-dev 17 | ``` 18 | 19 | ### OSX 20 | 21 | ``` 22 | brew install cppunit 23 | ``` -------------------------------------------------------------------------------- /prngs/LSBState.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class LSBState 5 | { 6 | 7 | public: 8 | 9 | LSBState(); 10 | 11 | /* Other seeds that this one is XOR'd with */ 12 | std::vector m_xorWith; 13 | 14 | /* Other seeds that this one is XOR'd with */ 15 | std::vector m_orWith; 16 | 17 | /* Do we know for sure what this LSB is */ 18 | bool m_isKnown; 19 | 20 | /* If we know it, what is the LSB */ 21 | uint32_t m_LSB; 22 | }; 23 | -------------------------------------------------------------------------------- /prngs/LSBStatePHP5_rand.h: -------------------------------------------------------------------------------- 1 | /* 2 | Heavily based off LSBState.h (Copyright Bishop Fox, 2014) 3 | */ 4 | 5 | #include 6 | #include 7 | 8 | class LSBStatePHP5_rand 9 | { 10 | 11 | public: 12 | 13 | LSBStatePHP5_rand(); 14 | 15 | /* Other seeds that this one is XOR'd with */ 16 | std::vector m_xorWith; 17 | 18 | /* Other seeds that this one is XOR'd with */ 19 | std::vector m_orWith; 20 | 21 | /* Do we know for sure what this LSB is */ 22 | bool m_isKnown; 23 | 24 | /* If we know it, what is the LSB */ 25 | uint32_t m_LSB; 26 | }; 27 | -------------------------------------------------------------------------------- /tests/TestJava.h: -------------------------------------------------------------------------------- 1 | #ifndef TESTJAVA_H_ 2 | #define TESTJAVA_H_ 3 | 4 | #include 5 | #include 6 | #include "../prngs/Java.h" 7 | 8 | class TestJava: public CPPUNIT_NS::TestFixture 9 | { 10 | CPPUNIT_TEST_SUITE(TestJava); 11 | CPPUNIT_TEST(initalizationTest); 12 | CPPUNIT_TEST(seedTest); 13 | CPPUNIT_TEST(randomTest); 14 | CPPUNIT_TEST_SUITE_END(); 15 | 16 | public: 17 | void setUp(void); 18 | void tearDown(void); 19 | 20 | protected: 21 | void initalizationTest(); 22 | void seedTest(); 23 | void randomTest(); 24 | 25 | private: 26 | 27 | }; 28 | 29 | #endif /* TESTJAVA_H_ */ 30 | -------------------------------------------------------------------------------- /tests/TestRuby.h: -------------------------------------------------------------------------------- 1 | #ifndef TESTRUBY_H_ 2 | #define TESTRUBY_H_ 3 | 4 | #include 5 | #include 6 | #include "../prngs/Ruby.h" 7 | 8 | class TestRuby: public CPPUNIT_NS::TestFixture 9 | { 10 | CPPUNIT_TEST_SUITE(TestRuby); 11 | CPPUNIT_TEST(initalizationTest); 12 | CPPUNIT_TEST(seedTest); 13 | CPPUNIT_TEST(randomTest); 14 | CPPUNIT_TEST_SUITE_END(); 15 | 16 | public: 17 | void setUp(void); 18 | void tearDown(void); 19 | 20 | protected: 21 | void initalizationTest(); 22 | void seedTest(); 23 | void randomTest(); 24 | 25 | private: 26 | 27 | }; 28 | 29 | #endif /* TESTRUBY_H_ */ 30 | -------------------------------------------------------------------------------- /tests/TestMt19937.h: -------------------------------------------------------------------------------- 1 | #ifndef TESTMT19937_H_ 2 | #define TESTMT19937_H_ 3 | 4 | #include 5 | #include 6 | #include "../prngs/Mt19937.h" 7 | 8 | class TestMt19937: public CPPUNIT_NS::TestFixture 9 | { 10 | CPPUNIT_TEST_SUITE(TestMt19937); 11 | CPPUNIT_TEST(initalizationTest); 12 | CPPUNIT_TEST(seedTest); 13 | CPPUNIT_TEST(randomTest); 14 | CPPUNIT_TEST_SUITE_END(); 15 | 16 | public: 17 | void setUp(void); 18 | void tearDown(void); 19 | 20 | protected: 21 | void initalizationTest(); 22 | void seedTest(); 23 | void randomTest(); 24 | 25 | private: 26 | 27 | }; 28 | 29 | #endif /* TESTMT19937_H_ */ 30 | -------------------------------------------------------------------------------- /tests/Test_PHP_mt19937.h: -------------------------------------------------------------------------------- 1 | #ifndef TEST_PHP_MT_RAND_ 2 | #define TEST_PHP_MT_RAND_ 3 | 4 | #include 5 | #include 6 | #include "../prngs/PHP_mt19937.h" 7 | 8 | class Test_PHP_Mt19937: public CPPUNIT_NS::TestFixture 9 | { 10 | CPPUNIT_TEST_SUITE(Test_PHP_Mt19937); 11 | CPPUNIT_TEST(initalizationTest); 12 | CPPUNIT_TEST(seedTest); 13 | CPPUNIT_TEST(randomTest); 14 | CPPUNIT_TEST_SUITE_END(); 15 | 16 | public: 17 | void setUp(void); 18 | void tearDown(void); 19 | 20 | protected: 21 | void initalizationTest(); 22 | void seedTest(); 23 | void randomTest(); 24 | 25 | private: 26 | 27 | }; 28 | 29 | #endif /* TEST_PHP_MT_RAND_ */ 30 | -------------------------------------------------------------------------------- /tests/TestPRNGFactory.h: -------------------------------------------------------------------------------- 1 | #ifndef TESTPRNGFACTORY_H_ 2 | #define TESTPRNGFACTORY_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include "../prngs/PRNG.h" 8 | #include "../prngs/PRNGFactory.h" 9 | 10 | class TestPRNGFactory: public CPPUNIT_NS::TestFixture 11 | { 12 | CPPUNIT_TEST_SUITE(TestPRNGFactory); 13 | CPPUNIT_TEST(initalizationTest); 14 | CPPUNIT_TEST(getNamesTest); 15 | CPPUNIT_TEST(getInstanceTest); 16 | CPPUNIT_TEST_SUITE_END(); 17 | 18 | public: 19 | void setUp(void); 20 | void tearDown(void); 21 | 22 | protected: 23 | void initalizationTest(); 24 | void getNamesTest(); 25 | void getInstanceTest(); 26 | 27 | private: 28 | 29 | }; 30 | 31 | #endif /* TESTPRNGFACTORY_H_ */ 32 | -------------------------------------------------------------------------------- /prngs/PRNGFactory.h: -------------------------------------------------------------------------------- 1 | #ifndef PRNGFACTORY_H_ 2 | #define PRNGFACTORY_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include "Mt19937.h" 9 | #include "GlibcRand.h" 10 | #include "Ruby.h" 11 | #include "PHP5_rand.h" 12 | #include "PHP_mt19937.h" 13 | #include "Java.h" 14 | #include "DotNetSystemRandom.h" 15 | 16 | /* Template to bind constructor to mapped string */ 17 | template PRNG* create() { return new T; } 18 | typedef std::map PRNGLibrary; 19 | 20 | class PRNGFactory 21 | { 22 | public: 23 | PRNGFactory(); 24 | virtual ~PRNGFactory(); 25 | 26 | PRNG* getInstance(std::string); 27 | std::vector getNames(void); 28 | 29 | private: 30 | PRNGLibrary library; 31 | }; 32 | 33 | #endif /* PRNGFACTORY_H_ */ 34 | -------------------------------------------------------------------------------- /prngs/LSBState.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "LSBState.h" 19 | 20 | LSBState::LSBState() 21 | { 22 | m_LSB = 0; 23 | m_isKnown = false; 24 | } 25 | -------------------------------------------------------------------------------- /AddingNewPRNG.txt: -------------------------------------------------------------------------------- 1 | How to add a new PRNG to untwister: 2 | 3 | New files to create: 4 | prngs/yourPRNG.cpp 5 | prngs/yourPRNG.h 6 | 7 | Files to edit: 8 | Add header to PRNGFactory.h, like so: 9 | #include "yourPRNG.h" 10 | Add PRNG type to the PRNGFactory.cpp constructor's list, like so: 11 | library[YOUR_PRNG] = &create; 12 | (Where YOUR_PRNG is a macro to a std::string that is the command line arg for your PRNG. Defined in yourPRNG.h) 13 | Add your PRNG to the Makefile. Try following in the footsteps of an existing one, like Ruby. Should be easy. 14 | Add unit tests! 15 | tests/testYourPRNG.cpp / .h 16 | Follow an example from an existing test file. It's pretty straight forward 17 | Add to Runner.cpp in executeAllTests() 18 | runner.addTest(TestYourPRNG::suite()); 19 | and the header: 20 | #include "TestYourPRNG.h" 21 | -------------------------------------------------------------------------------- /prngs/LSBStatePHP5_rand.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This program is free software: you can redistribute it and/or modify 3 | it under the terms of the GNU General Public License as published by 4 | the Free Software Foundation, either version 3 of the License, or 5 | (at your option) any later version. 6 | 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | 12 | You should have received a copy of the GNU General Public License 13 | along with this program. If not, see . 14 | 15 | Heavily based off LSBState.cpp (Copyright Bishop Fox, 2014) 16 | */ 17 | 18 | #include "LSBStatePHP5_rand.h" 19 | 20 | LSBStatePHP5_rand::LSBStatePHP5_rand() 21 | { 22 | m_LSB = 0; 23 | m_isKnown = false; 24 | } 25 | -------------------------------------------------------------------------------- /prngs/Mt19937.h: -------------------------------------------------------------------------------- 1 | #ifndef MT19937_H_ 2 | #define MT19937_H_ 3 | 4 | #include 5 | #include "PRNG.h" 6 | 7 | static const std::string MT19937 = "mt19937"; 8 | static const uint32_t MT19937_STATE_SIZE = 624; 9 | 10 | class Mt19937: public PRNG 11 | { 12 | public: 13 | Mt19937(); 14 | virtual ~Mt19937(); 15 | 16 | const std::string getName(void); 17 | void seed(int64_t value); 18 | int64_t getSeed(void); 19 | uint32_t random(void); 20 | 21 | uint32_t getStateSize(void); 22 | void setState(std::vector); 23 | std::vector getState(void); 24 | 25 | void setEvidence(std::vector); 26 | 27 | std::vector predictForward(uint32_t); 28 | std::vector predictBackward(uint32_t); 29 | void tune(std::vector, std::vector); 30 | 31 | bool reverseToSeed(int64_t *, uint32_t); 32 | void setBounds(uint32_t, uint32_t); 33 | 34 | int64_t getMinSeed(); 35 | int64_t getMaxSeed(); 36 | 37 | private: 38 | uint32_t seedValue; 39 | std::mt19937 generator; 40 | }; 41 | 42 | #endif /* MT19937_H_ */ 43 | -------------------------------------------------------------------------------- /prngs/Java.h: -------------------------------------------------------------------------------- 1 | #ifndef JAVA_INT_H_ 2 | #define JAVA_INT_H_ 3 | 4 | #include 5 | #include "PRNG.h" 6 | 7 | static const std::string JAVA = "java"; 8 | static const uint32_t JAVA_STATE_SIZE = 1; 9 | 10 | class Java: public PRNG 11 | { 12 | public: 13 | Java(); 14 | virtual ~Java(); 15 | 16 | const std::string getName(void); 17 | void seed(int64_t value); 18 | int64_t getSeed(void); 19 | uint32_t random(void); 20 | 21 | uint32_t getStateSize(void); 22 | void setState(std::vector); 23 | std::vector getState(void); 24 | 25 | void setEvidence(std::vector); 26 | 27 | std::vector predictForward(uint32_t); 28 | std::vector predictBackward(uint32_t); 29 | void tune(std::vector, std::vector); 30 | 31 | bool reverseToSeed(int64_t *, uint32_t); 32 | void setBounds(uint32_t, uint32_t); 33 | 34 | int64_t getMinSeed(); 35 | int64_t getMaxSeed(); 36 | 37 | private: 38 | int32_t next(int32_t bits); 39 | int64_t m_seedValue; 40 | int64_t m_originalSeed; 41 | }; 42 | 43 | #endif /* JAVA_INT_H_ */ 44 | -------------------------------------------------------------------------------- /prngs/Ruby.h: -------------------------------------------------------------------------------- 1 | #ifndef RUBY_H_ 2 | #define RUBY_H_ 3 | 4 | #include 5 | #include "PRNG.h" 6 | 7 | static const std::string RUBY_RAND = "ruby-rand"; 8 | static const uint32_t RUBY_STATE_SIZE = 624; 9 | 10 | class Ruby: public PRNG 11 | { 12 | public: 13 | Ruby(); 14 | virtual ~Ruby(); 15 | 16 | const std::string getName(void); 17 | void seed(int64_t value); 18 | int64_t getSeed(void); 19 | uint32_t random(void); 20 | 21 | uint32_t getStateSize(void); 22 | void setState(std::vector); 23 | std::vector getState(void); 24 | 25 | void setEvidence(std::vector); 26 | 27 | std::vector predictForward(uint32_t); 28 | std::vector predictBackward(uint32_t); 29 | void tune(std::vector, std::vector); 30 | 31 | bool reverseToSeed(int64_t *, uint32_t); 32 | void setBounds(uint32_t, uint32_t); 33 | 34 | int64_t getMinSeed(); 35 | int64_t getMaxSeed(); 36 | 37 | private: 38 | void init_genrand(struct MT *mt, unsigned int s); 39 | void next_state(struct MT *mt); 40 | uint32_t genrand_int32(struct MT *mt); 41 | uint32_t make_mask(uint32_t x); 42 | 43 | MT *m_mt; 44 | uint32_t seedValue; 45 | }; 46 | 47 | #endif /* RUBY_H_ */ 48 | -------------------------------------------------------------------------------- /tests/TestUntwister.h: -------------------------------------------------------------------------------- 1 | #ifndef TESTUNTWISTER_H_ 2 | #define TESTUNTWISTER_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "../Untwister.h" 9 | 10 | static const unsigned int TEST_COUNT = 10; 11 | 12 | 13 | class TestUntwister: public CPPUNIT_NS::TestFixture 14 | { 15 | CPPUNIT_TEST_SUITE(TestUntwister); 16 | CPPUNIT_TEST(initalizationTest); 17 | CPPUNIT_TEST(setThreadsTest); 18 | CPPUNIT_TEST(setDepthTest); 19 | CPPUNIT_TEST(setMinConfidenceTest); 20 | CPPUNIT_TEST(setPRNGTest); 21 | CPPUNIT_TEST(mtBruteforceTest); 22 | CPPUNIT_TEST(glibcBruteforceTest); 23 | CPPUNIT_TEST(rubyBruteforceTest); 24 | CPPUNIT_TEST_SUITE_END(); 25 | 26 | public: 27 | void setUp(void); 28 | void tearDown(void); 29 | 30 | protected: 31 | void initalizationTest(); 32 | void setThreadsTest(); 33 | void setDepthTest(); 34 | void setMinConfidenceTest(); 35 | void setPRNGTest(); 36 | void mtBruteforceTest(); 37 | void glibcBruteforceTest(); 38 | void rubyBruteforceTest(); 39 | 40 | private: 41 | std::vector *m_mtTestInputs; 42 | std::vector *m_glibcTestInputs; 43 | std::vector *m_rubyTestInputs; 44 | void m_loadTestFile(std::string path, std::vector *testInputs); 45 | }; 46 | 47 | #endif /* TESTUNTWISTER_H_ */ 48 | -------------------------------------------------------------------------------- /prngs/PRNGFactory.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "PRNGFactory.h" 19 | 20 | PRNGFactory::PRNGFactory() 21 | { 22 | library[GLIBC_RAND] = &create; 23 | library[MT19937] = &create; 24 | library[RUBY_RAND] = &create; 25 | library[PHP_MT_RAND] = &create; 26 | library[PHP5_RAND] = &create; 27 | library[JAVA] = &create; 28 | library[DOTNET_SYSTEMRANDOM] = &create; 29 | } 30 | 31 | PRNGFactory::~PRNGFactory() {} 32 | 33 | PRNG* PRNGFactory::getInstance(std::string name) 34 | { 35 | std::transform(name.begin(), name.end(), name.begin(), ::tolower); 36 | return library[name](); 37 | } 38 | 39 | std::vector PRNGFactory::getNames() 40 | { 41 | std::vector names; 42 | for (PRNGLibrary::iterator iter = library.begin(); iter != library.end(); ++iter) 43 | { 44 | names.push_back(iter->first); 45 | } 46 | return names; 47 | } 48 | -------------------------------------------------------------------------------- /tests/TestMt19937.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "TestMt19937.h" 19 | 20 | void TestMt19937::setUp() 21 | { 22 | 23 | } 24 | 25 | void TestMt19937::tearDown() 26 | { 27 | 28 | } 29 | 30 | void TestMt19937::initalizationTest() 31 | { 32 | Mt19937 *mt = new Mt19937(); 33 | CPPUNIT_ASSERT(mt != NULL); 34 | delete mt; 35 | } 36 | 37 | void TestMt19937::seedTest() 38 | { 39 | Mt19937 *mt = new Mt19937(); 40 | mt->seed(31337); 41 | CPPUNIT_ASSERT(mt->getSeed() == 31337); 42 | delete mt; 43 | } 44 | 45 | void TestMt19937::randomTest() 46 | { 47 | Mt19937 *mt = new Mt19937(); 48 | mt->seed(31337); 49 | CPPUNIT_ASSERT(mt->random() == 3100331191); 50 | CPPUNIT_ASSERT(mt->random() == 3480951327); 51 | CPPUNIT_ASSERT(mt->random() == 4150831638); 52 | mt->seed(31337); 53 | CPPUNIT_ASSERT(mt->random() == 3100331191); 54 | CPPUNIT_ASSERT(mt->random() == 3480951327); 55 | CPPUNIT_ASSERT(mt->random() == 4150831638); 56 | delete mt; 57 | } 58 | -------------------------------------------------------------------------------- /prngs/GlibcRand.h: -------------------------------------------------------------------------------- 1 | #ifndef GLIBCRAND_H_ 2 | #define GLIBCRAND_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include "PRNG.h" 8 | #include "LSBState.h" 9 | 10 | static const std::string GLIBC_RAND = "glibc-rand"; 11 | static const uint32_t GLIBC_RAND_STATE_SIZE = 32; 12 | 13 | class GlibcRand: public PRNG 14 | { 15 | public: 16 | GlibcRand(); 17 | virtual ~GlibcRand(); 18 | 19 | const std::string getName(void); 20 | void seed(int64_t value); 21 | int64_t getSeed(void); 22 | uint32_t random(void); 23 | void setBounds(uint32_t, uint32_t); 24 | 25 | int64_t getMinSeed(); 26 | int64_t getMaxSeed(); 27 | 28 | private: 29 | uint32_t seedValue; 30 | uint32_t getStateSize(void); 31 | void setState(std::vector inState); 32 | std::vector getState(void); 33 | 34 | void setEvidence(std::vector); 35 | 36 | std::vector predictForward(uint32_t); 37 | std::vector predictBackward(uint32_t); 38 | 39 | bool setLSB(uint32_t index, uint32_t value); 40 | void setLSBxor(uint32_t index1, uint32_t index2); 41 | void setLSBor(uint32_t index1, uint32_t index2); 42 | bool handleRemainder(uint32_t index, std::vector); 43 | 44 | void tune(std::vector, std::vector); 45 | void tune_repeatedIncrements(); 46 | void tune_chainChecking(); 47 | 48 | bool isInitState(std::deque *); 49 | 50 | bool reverseToSeed(int64_t *, uint32_t); 51 | 52 | /* Keeps track of what LSBs are known */ 53 | std::vector m_LSBMap; 54 | int32_t m_glibcstate[32]; 55 | int32_t *m_fptr; 56 | int32_t *m_rptr; 57 | }; 58 | 59 | #endif /* GLIBCRAND_H_ */ 60 | -------------------------------------------------------------------------------- /tests/runner.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, moloch 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | 21 | #include "../ConsoleColors.h" 22 | #include "TestUntwister.h" 23 | #include "TestPRNGFactory.h" 24 | #include "TestMt19937.h" 25 | #include "TestRuby.h" 26 | #include "Test_PHP_mt19937.h" 27 | #include "TestJava.h" 28 | 29 | bool executeAllTests() 30 | { 31 | CppUnit::TextUi::TestRunner runner; 32 | runner.addTest(TestMt19937::suite()); 33 | runner.addTest(Test_PHP_Mt19937::suite()); 34 | runner.addTest(TestRuby::suite()); 35 | runner.addTest(TestJava::suite()); 36 | runner.addTest(TestPRNGFactory::suite()); 37 | runner.addTest(TestUntwister::suite()); 38 | return runner.run(); 39 | } 40 | 41 | int main(int argc, char *argv[]) 42 | { 43 | std::cout << INFO << "Executing all unit tests, please wait..."; 44 | std::cout.flush(); 45 | if (!executeAllTests()) 46 | { 47 | std::cout << WARN << "One or more tests failed!" << std::endl; 48 | } 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /tests/Test_PHP_mt19937.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "Test_PHP_mt19937.h" 19 | 20 | void Test_PHP_Mt19937::setUp() 21 | { 22 | 23 | } 24 | 25 | void Test_PHP_Mt19937::tearDown() 26 | { 27 | 28 | } 29 | 30 | void Test_PHP_Mt19937::initalizationTest() 31 | { 32 | PHP_mt19937 *mt = new PHP_mt19937(); 33 | CPPUNIT_ASSERT(mt != NULL); 34 | delete mt; 35 | } 36 | 37 | void Test_PHP_Mt19937::seedTest() 38 | { 39 | PHP_mt19937 *mt = new PHP_mt19937(); 40 | mt->seed(31337); 41 | CPPUNIT_ASSERT(mt->getSeed() == 31337); 42 | delete mt; 43 | } 44 | 45 | void Test_PHP_Mt19937::randomTest() 46 | { 47 | PHP_mt19937 *mt = new PHP_mt19937(); 48 | mt->seed(31337); 49 | CPPUNIT_ASSERT(mt->random() == 590238509); 50 | CPPUNIT_ASSERT(mt->random() == 418805881); 51 | CPPUNIT_ASSERT(mt->random() == 83861629); 52 | mt->seed(31337); 53 | CPPUNIT_ASSERT(mt->random() == 590238509); 54 | CPPUNIT_ASSERT(mt->random() == 418805881); 55 | CPPUNIT_ASSERT(mt->random() == 83861629); 56 | delete mt; 57 | } 58 | -------------------------------------------------------------------------------- /prngs/PHP5_rand.h: -------------------------------------------------------------------------------- 1 | /* 2 | Heavily based off GlibcRand.h (Copyright Bishop Fox 2014) 3 | */ 4 | 5 | #ifndef PHP5_RAND_H_ 6 | #define PHP5_RAND_H_ 7 | 8 | #include 9 | #include 10 | #include 11 | #include "PRNG.h" 12 | #include "LSBStatePHP5_rand.h" 13 | 14 | static const std::string PHP5_RAND = "php5-rand"; 15 | static const uint32_t PHP5_RAND_STATE_SIZE = 32; 16 | 17 | class PHP5_rand: public PRNG 18 | { 19 | public: 20 | PHP5_rand(); 21 | virtual ~PHP5_rand(); 22 | 23 | const std::string getName(void); 24 | void seed(int64_t value); 25 | int64_t getSeed(void); 26 | uint32_t random(void); 27 | void setBounds(uint32_t, uint32_t); 28 | 29 | int64_t getMinSeed(); 30 | int64_t getMaxSeed(); 31 | 32 | private: 33 | uint32_t seedValue; 34 | uint32_t getStateSize(void); 35 | void setState(std::vector inState); 36 | std::vector getState(void); 37 | 38 | void setEvidence(std::vector); 39 | 40 | std::vector predictForward(uint32_t); 41 | std::vector predictBackward(uint32_t); 42 | 43 | bool setLSB(uint32_t index, uint32_t value); 44 | void setLSBxor(uint32_t index1, uint32_t index2); 45 | void setLSBor(uint32_t index1, uint32_t index2); 46 | bool handleRemainder(uint32_t index, std::vector); 47 | 48 | void tune(std::vector, std::vector); 49 | void tune_repeatedIncrements(); 50 | void tune_chainChecking(); 51 | 52 | bool isInitState(std::deque *); 53 | 54 | bool reverseToSeed(int64_t *, uint32_t); 55 | 56 | /* Keeps track of what LSBs are known */ 57 | std::vector m_LSBMap; 58 | int32_t m_glibcstate[32]; 59 | int32_t *m_fptr; 60 | int32_t *m_rptr; 61 | }; 62 | 63 | #endif /* PHP5_RAND_H_ */ 64 | -------------------------------------------------------------------------------- /prngs/PHP_mt19937.h: -------------------------------------------------------------------------------- 1 | #ifndef PHP_MT19937_H_ 2 | #define PHP_MT19937_H_ 3 | 4 | #include 5 | #include "PRNG.h" 6 | 7 | static const std::string PHP_MT_RAND = "php-mt_rand"; 8 | static const uint32_t PHP_MT_RAND_STATE_SIZE = 624; 9 | 10 | #define hiBit(u) ((u) & 0x80000000U) /* mask all but highest bit of u */ 11 | #define loBit(u) ((u) & 0x00000001U) /* mask all but lowest bit of u */ 12 | #define loBits(u) ((u) & 0x7FFFFFFFU) /* mask the highest bit of u */ 13 | #define mixBits(u, v) (hiBit(u)|loBits(v)) /* move hi bit of u to hi bit of v */ 14 | #define php_twist(m,u,v) (m ^ (mixBits(u,v)>>1) ^ ((uint32_t)(-(int32_t)(loBit(u))) & 0x9908b0dfU)) 15 | 16 | class PHP_mt19937: public PRNG 17 | { 18 | public: 19 | PHP_mt19937(); 20 | virtual ~PHP_mt19937(); 21 | 22 | const std::string getName(void); 23 | void seed(int64_t value); 24 | int64_t getSeed(void); 25 | uint32_t random(void); 26 | 27 | uint32_t getStateSize(void); 28 | void setState(std::vector); 29 | std::vector getState(void); 30 | 31 | void setEvidence(std::vector); 32 | 33 | std::vector predictForward(uint32_t); 34 | std::vector predictBackward(uint32_t); 35 | void tune(std::vector, std::vector); 36 | 37 | bool reverseToSeed(int64_t *, uint32_t); 38 | void setBounds(uint32_t, uint32_t); 39 | 40 | int64_t getMinSeed(); 41 | int64_t getMaxSeed(); 42 | 43 | private: 44 | void php_mt_initialize(uint32_t s); 45 | void php_mt_reload(); 46 | uint32_t genrand_int32(struct MT *mt); 47 | 48 | MT *m_mt; 49 | uint32_t m_seedValue; 50 | 51 | /* rand.c */ 52 | uint32_t m_state[N+1]; /* state vector + 1 extra to not violate ANSI C */ 53 | uint32_t *m_next; /* next random value is computed from here */ 54 | int m_left; /* can *next++ this many times before reloading */ 55 | 56 | }; 57 | 58 | #endif /* PHP_MT19937_H_ */ 59 | -------------------------------------------------------------------------------- /prngs/PRNG.h: -------------------------------------------------------------------------------- 1 | /* 2 | * PRNG.h 3 | * 4 | * This is a blank pure virtual interface class 5 | * all the PRNGs implement this interface. 6 | */ 7 | 8 | #ifndef PRNG_H_ 9 | #define PRNG_H_ 10 | 11 | #include 12 | 13 | /* 14 | Common MT data structures and constants 15 | */ 16 | /* Period parameters */ 17 | #define N 624 18 | #define M 397 19 | #define MATRIX_A 0x9908b0dfU /* constant vector a */ 20 | #define UMASK 0x80000000U /* most significant w-r bits */ 21 | #define LMASK 0x7fffffffU /* least significant r bits */ 22 | #define MIXBITS(u,v) ( ((u) & UMASK) | ((v) & LMASK) ) 23 | #define TWIST(u,v) ((MIXBITS((u),(v)) >> 1) ^ ((v)&1U ? MATRIX_A : 0U)) 24 | 25 | enum {MT_MAX_STATE = N}; 26 | 27 | struct MT { 28 | /* assume int is enough to store 32bits */ 29 | unsigned int state[N]; /* the array for the state vector */ 30 | unsigned int *next; 31 | int left; 32 | }; 33 | 34 | class PRNG 35 | { 36 | public: 37 | 38 | virtual const std::string getName(void) = 0; 39 | virtual void seed(int64_t) = 0; 40 | virtual int64_t getSeed(void) = 0; 41 | virtual uint32_t random(void) = 0; 42 | virtual uint32_t getStateSize(void) = 0; 43 | virtual void setState(std::vector) = 0; 44 | virtual std::vector getState(void) = 0; 45 | virtual void setEvidence(std::vector) = 0; 46 | virtual std::vector predictForward(uint32_t) = 0; 47 | virtual std::vector predictBackward(uint32_t) = 0; 48 | virtual void tune(std::vector, std::vector) = 0; 49 | virtual bool reverseToSeed(int64_t *, uint32_t) = 0; 50 | virtual void setBounds(uint32_t, uint32_t) = 0; 51 | virtual int64_t getMinSeed() = 0; 52 | virtual int64_t getMaxSeed() = 0; 53 | 54 | virtual ~PRNG(){}; 55 | 56 | protected: 57 | std::vector m_state; 58 | std::vector m_evidence; 59 | uint32_t m_minBound; 60 | uint32_t m_maxBound; 61 | bool m_isBounded; 62 | }; 63 | 64 | #endif /* PRNG_H_ */ 65 | -------------------------------------------------------------------------------- /tests/TestJava.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "TestJava.h" 19 | 20 | void TestJava::setUp() 21 | { 22 | 23 | } 24 | 25 | void TestJava::tearDown() 26 | { 27 | 28 | } 29 | 30 | void TestJava::initalizationTest() 31 | { 32 | Java *java = new Java(); 33 | CPPUNIT_ASSERT(java != NULL); 34 | delete java; 35 | } 36 | 37 | void TestJava::seedTest() 38 | { 39 | Java java = Java(); 40 | java.seed(31337); 41 | CPPUNIT_ASSERT(java.getSeed() == 31337); 42 | } 43 | 44 | void TestJava::randomTest() 45 | { 46 | Java java = Java(); 47 | java.seed(1337); 48 | CPPUNIT_ASSERT(java.random() == 2834376842); 49 | CPPUNIT_ASSERT(java.random() == 747279288); 50 | CPPUNIT_ASSERT(java.random() == 2960274719); 51 | java.seed(1337); 52 | CPPUNIT_ASSERT(java.random() == 2834376842); 53 | CPPUNIT_ASSERT(java.random() == 747279288); 54 | CPPUNIT_ASSERT(java.random() == 2960274719); 55 | 56 | /* Bounded Java rand(int, int) calls */ 57 | java.setBounds(0, 99); 58 | java.seed(31337); 59 | CPPUNIT_ASSERT(java.random() == 9); 60 | CPPUNIT_ASSERT(java.random() == 73); 61 | CPPUNIT_ASSERT(java.random() == 49); 62 | java.setBounds(0, 99); 63 | java.seed(31337); 64 | CPPUNIT_ASSERT(java.random() == 9); 65 | CPPUNIT_ASSERT(java.random() == 73); 66 | CPPUNIT_ASSERT(java.random() == 49); 67 | } 68 | -------------------------------------------------------------------------------- /ConsoleColors.h: -------------------------------------------------------------------------------- 1 | #ifndef CONSOLECOLORS_H_ 2 | #define CONSOLECOLORS_H_ 3 | 4 | #include 5 | 6 | #ifndef __WIN32__ 7 | 8 | /* Updates */ 9 | static const std::string INFO = "\033[1m\033[36m[*]\033[0m "; 10 | static const std::string WARN = "\033[1m\033[31m[!]\033[0m "; 11 | static const std::string DEBUG = "\033[1m\033[35m[-]\033[0m "; 12 | static const std::string SUCCESS = "\033[1m\033[33m[$]\033[0m "; 13 | static const std::string PROMPT = "\033[1m\033[34m[?]\033[0m "; 14 | 15 | /* Colors */ 16 | static const std::string BLACK = "\033[30m"; 17 | static const std::string RED = "\033[31m"; 18 | static const std::string GREEN = "\033[32m"; 19 | static const std::string YELLOW = "\033[33m"; 20 | static const std::string BLUE = "\033[34m"; 21 | static const std::string PURPLE = "\033[35m"; 22 | static const std::string CYAN = "\033[36m"; 23 | static const std::string GRAY = "\033[37m"; 24 | 25 | /* Styles */ 26 | static const std::string BOLD = "\033[1m"; 27 | static const std::string UNDERLINE = "\033[4m"; 28 | static const std::string RESET = "\033[0m"; 29 | static const std::string CLEAR = "\r\x1b[2K"; 30 | 31 | #else 32 | 33 | /* Updates */ 34 | static const std::string INFO = "[*] "; 35 | static const std::string WARN = "[!] "; 36 | static const std::string DEBUG = "[-] "; 37 | static const std::string SUCCESS = "[$] "; 38 | static const std::string PROMPT = "[?] "; 39 | 40 | /* Windows Color Support is Terrible :( */ 41 | static const std::string BLACK = ""; 42 | static const std::string RED = ""; 43 | static const std::string GREEN = ""; 44 | static const std::string YELLOW = ""; 45 | static const std::string BLUE = ""; 46 | static const std::string PURPLE = ""; 47 | static const std::string CYAN = ""; 48 | static const std::string GRAY = ""; 49 | 50 | /* Styles Blank */ 51 | static const std::string BOLD = ""; 52 | static const std::string UNDERLINE = ""; 53 | static const std::string RESET = ""; 54 | static const std::string CLEAR = "\n"; 55 | 56 | #endif /* __WIN32__ */ 57 | 58 | #endif /* CONSOLECOLORS_H_ */ 59 | -------------------------------------------------------------------------------- /tests/TestRuby.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "TestRuby.h" 19 | 20 | void TestRuby::setUp() 21 | { 22 | 23 | } 24 | 25 | void TestRuby::tearDown() 26 | { 27 | 28 | } 29 | 30 | void TestRuby::initalizationTest() 31 | { 32 | Ruby *ruby = new Ruby(); 33 | CPPUNIT_ASSERT(ruby != NULL); 34 | delete ruby; 35 | } 36 | 37 | void TestRuby::seedTest() 38 | { 39 | Ruby *ruby = new Ruby(); 40 | ruby->seed(31337); 41 | CPPUNIT_ASSERT(ruby->getSeed() == 31337); 42 | delete ruby; 43 | } 44 | 45 | void TestRuby::randomTest() 46 | { 47 | Ruby *ruby = new Ruby(); 48 | ruby->seed(31337); 49 | CPPUNIT_ASSERT(ruby->random() == 3100331191); 50 | CPPUNIT_ASSERT(ruby->random() == 3480951327); 51 | CPPUNIT_ASSERT(ruby->random() == 4150831638); 52 | ruby->seed(31337); 53 | CPPUNIT_ASSERT(ruby->random() == 3100331191); 54 | CPPUNIT_ASSERT(ruby->random() == 3480951327); 55 | CPPUNIT_ASSERT(ruby->random() == 4150831638); 56 | 57 | /* Bounded Ruby rand(int, int) calls */ 58 | ruby->setBounds(1234, 9876); 59 | ruby->seed(6789); 60 | CPPUNIT_ASSERT(ruby->random() == 4081); 61 | CPPUNIT_ASSERT(ruby->random() == 2200); 62 | CPPUNIT_ASSERT(ruby->random() == 8047); 63 | ruby->setBounds(1234, 9876); 64 | ruby->seed(6789); 65 | CPPUNIT_ASSERT(ruby->random() == 4081); 66 | CPPUNIT_ASSERT(ruby->random() == 2200); 67 | CPPUNIT_ASSERT(ruby->random() == 8047); 68 | delete ruby; 69 | } 70 | -------------------------------------------------------------------------------- /tests/TestPRNGFactory.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "TestPRNGFactory.h" 19 | 20 | void TestPRNGFactory::setUp() 21 | { 22 | 23 | } 24 | 25 | void TestPRNGFactory::tearDown() 26 | { 27 | 28 | } 29 | 30 | void TestPRNGFactory::initalizationTest() 31 | { 32 | PRNGFactory *factory = new PRNGFactory(); 33 | CPPUNIT_ASSERT(factory != NULL); 34 | delete factory; 35 | } 36 | 37 | void TestPRNGFactory::getNamesTest() 38 | { 39 | PRNGFactory *factory = new PRNGFactory(); 40 | auto names = factory->getNames(); 41 | CPPUNIT_ASSERT(0 < names.size()); 42 | delete factory; 43 | } 44 | 45 | void TestPRNGFactory::getInstanceTest() 46 | { 47 | PRNGFactory *factory = new PRNGFactory(); 48 | 49 | PRNG *mt = factory->getInstance("mt19937"); 50 | CPPUNIT_ASSERT(mt->getName() == "mt19937"); 51 | mt->seed(31337); 52 | CPPUNIT_ASSERT(mt->random() == 3100331191); 53 | CPPUNIT_ASSERT(mt->random() == 3480951327); 54 | CPPUNIT_ASSERT(mt->random() == 4150831638); 55 | delete mt; 56 | 57 | PRNG *php_mt = factory->getInstance("php-mt_rand"); 58 | CPPUNIT_ASSERT(php_mt->getName() == "php-mt_rand"); 59 | php_mt->seed(31337); 60 | CPPUNIT_ASSERT(php_mt->random() == 590238509); 61 | CPPUNIT_ASSERT(php_mt->random() == 418805881); 62 | CPPUNIT_ASSERT(php_mt->random() == 83861629); 63 | delete php_mt; 64 | 65 | PRNG *ruby = factory->getInstance("ruby-rand"); 66 | CPPUNIT_ASSERT(ruby->getName() == "ruby-rand"); 67 | ruby->seed(31337); 68 | CPPUNIT_ASSERT(ruby->random() == 3100331191); 69 | CPPUNIT_ASSERT(ruby->random() == 3480951327); 70 | CPPUNIT_ASSERT(ruby->random() == 4150831638); 71 | delete ruby; 72 | 73 | PRNG *glibc = factory->getInstance("glibc-rand"); 74 | CPPUNIT_ASSERT(glibc->getName() == "glibc-rand"); 75 | glibc->seed(31337); 76 | CPPUNIT_ASSERT(glibc->random() == 53418360); 77 | CPPUNIT_ASSERT(glibc->random() == 66988840); 78 | CPPUNIT_ASSERT(glibc->random() == 1189565692); 79 | delete glibc; 80 | 81 | delete factory; 82 | } 83 | -------------------------------------------------------------------------------- /prngs/Mt19937.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "Mt19937.h" 19 | #include "../ConsoleColors.h" 20 | #include 21 | 22 | Mt19937::Mt19937() 23 | { 24 | seedValue = generator.default_seed; 25 | } 26 | 27 | Mt19937::~Mt19937() {} 28 | 29 | const std::string Mt19937::getName() 30 | { 31 | return MT19937; 32 | } 33 | 34 | void Mt19937::seed(int64_t value) 35 | { 36 | seedValue = (uint32_t)value; 37 | this->generator.seed(seedValue); 38 | } 39 | 40 | int64_t Mt19937::getSeed() 41 | { 42 | return seedValue; 43 | } 44 | 45 | uint32_t Mt19937::random(void) 46 | { 47 | return this->generator(); 48 | } 49 | 50 | uint32_t Mt19937::getStateSize(void) 51 | { 52 | return MT19937_STATE_SIZE; 53 | } 54 | 55 | void Mt19937::setState(std::vector inState) 56 | { 57 | m_state = inState; 58 | m_state.resize(MT19937_STATE_SIZE, 0); 59 | } 60 | 61 | std::vector Mt19937::getState(void) 62 | { 63 | return m_state; 64 | } 65 | 66 | std::vector Mt19937::predictForward(uint32_t) 67 | { 68 | std::vector ret; 69 | //TODO 70 | return ret; 71 | } 72 | 73 | std::vector Mt19937::predictBackward(uint32_t) 74 | { 75 | std::vector ret; 76 | //TODO 77 | return ret; 78 | } 79 | 80 | 81 | bool Mt19937::reverseToSeed(int64_t *outSeed, uint32_t depth) 82 | { 83 | //TODO 84 | return false; 85 | } 86 | 87 | void Mt19937::tune(std::vector evidenceForward, std::vector evidenceBackward) 88 | { 89 | //TODO 90 | } 91 | 92 | void Mt19937::setEvidence(std::vector) 93 | { 94 | 95 | } 96 | 97 | void Mt19937::setBounds(uint32_t min, uint32_t max) 98 | { 99 | //Setting bounds is unsupported in C++ rand, so do nothing here. In fact, this should not get called. 100 | } 101 | 102 | int64_t Mt19937::getMinSeed() 103 | { 104 | return 0; 105 | } 106 | 107 | int64_t Mt19937::getMaxSeed() 108 | { 109 | return UINT_MAX; 110 | } 111 | -------------------------------------------------------------------------------- /Untwister.h: -------------------------------------------------------------------------------- 1 | #ifndef UNTWISTER_H_ 2 | #define UNTWISTER_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "ConsoleColors.h" 13 | #include "prngs/PRNGFactory.h" 14 | #include "prngs/PRNG.h" 15 | 16 | // Pair of 17 | typedef std::pair Seed; 18 | typedef std::pair, double> State; 19 | 20 | static const uint32_t DEFAULT_DEPTH = 1000; 21 | static const double DEFAULT_MIN_CONFIDENCE = 100.0; 22 | 23 | class Untwister 24 | { 25 | 26 | public: 27 | Untwister(); 28 | Untwister(unsigned int observationSize); 29 | virtual ~Untwister(); 30 | 31 | std::vector bruteforce(int64_t lowerBoundSeed, int64_t upperBoundSeed); 32 | 33 | bool canInferState(); 34 | State inferState(); 35 | uint32_t getStateSize(); 36 | 37 | /* Gets the min and max possible seed, for the given PRNG type */ 38 | int64_t getMinSeed(); 39 | int64_t getMaxSeed(); 40 | 41 | std::vector getSupportedPRNGs(); 42 | void setPRNG(std::string prng); 43 | void setPRNG(char *prng); 44 | std::string getPRNG(); 45 | bool isSupportedPRNG(std::string prng); 46 | bool isSupportedPRNG(char* prng); 47 | 48 | void setMinConfidence(double minConfidence); 49 | double getMinConfidence(); 50 | void setDepth(uint32_t depth); 51 | uint32_t getDepth(); 52 | void setThreads(unsigned int threads); 53 | unsigned int getThreads(); 54 | void addObservedOutput(uint32_t observedOutput); 55 | std::vector* getObservedOutputs(); 56 | 57 | /* Returns NULL if there is no status to get. Such as if the bruteforce thread hasn't started */ 58 | std::vector* getStatus(); 59 | std::atomic* getIsCompleted(); 60 | std::atomic* getIsRunning(); 61 | std::atomic* getIsStarting(); 62 | 63 | void setBounds(uint32_t, uint32_t); 64 | bool isBounded(); 65 | 66 | void generateSampleFromSeed(uint32_t depth, int64_t seed); 67 | 68 | private: 69 | unsigned int m_threads; 70 | double m_minConfidence; 71 | uint32_t m_depth; 72 | std::string m_prng; 73 | std::atomic *m_isStarting; 74 | std::atomic *m_isRunning; 75 | std::atomic *m_isCompleted; 76 | std::vector *m_status; 77 | std::vector* > *m_answers; 78 | std::vector *m_observedOutputs; 79 | 80 | std::atomic *m_isBounded; 81 | uint32_t m_minBound; 82 | uint32_t m_maxBound; 83 | 84 | void m_worker(unsigned int id, uint32_t startingSeed, uint32_t endingSeed); 85 | std::vector m_divisionOfLabor(uint64_t sizeOfWork); 86 | 87 | }; 88 | 89 | #endif /* UNTWISTER_H_ */ 90 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Untwister 2 | ========= 3 | 4 | Multi-threaded seed recovery tool for common PRNGs. 5 | 6 | 7 | Supported PRNGs 8 | ================= 9 | * .NET System.Random Next() 10 | * Glibc's rand() 11 | * Mersenne Twister (MT19937) 12 | * PHP's MT-variant (php-mt_rand) 13 | * PHP 5's glibc rand (php5-rand) 14 | * Ruby's MT-variant DEFAULT::rand() 15 | * Java's Random() class 16 | 17 | Usage 18 | ======== 19 | ``` 20 | Untwister - Recover PRNG seeds from observed values. 21 | -i [-d ] [-r ] [-g ] [-t ] 22 | 23 | -i 24 | Path to file input file containing observed results of your RNG. The contents 25 | are expected to be newline separated 32-bit integers. See test_input.txt for 26 | an example. 27 | -d 28 | The depth (default 1000) to inspect for each seed value when brute forcing. 29 | Choosing a higher depth value will make brute forcing take longer (linearly), 30 | but is required for cases where the generator has been used many times already. 31 | Also controls how deep to generate random numbers given the -g option 32 | -r 33 | The RNG algorithm to use. Supported RNG algorithms: 34 | dotnet-systemrandom 35 | glibc-rand (default) 36 | mt19937 37 | php-mt_rand 38 | php5-rand 39 | ruby-rand 40 | java 41 | -u 42 | Use bruteforce, but only for unix timestamp values within a range of +/- 1 43 | year from the current time. 44 | -b 45 | Always bruteforce, even if state inference attack is successful 46 | -g 47 | Generate a test set of random numbers from the given seed 48 | -D 49 | The quantity of random numbers to generate when using the -g flag (default 20) 50 | -c 51 | Set the minimum confidence percentage to report 52 | -t 53 | Spawn this many threads (default is your number of CPUs) 54 | -m 55 | Set the minimum bound (inclusive), for a bounded PRNG function 56 | -M 57 | Set the maximum bound (inclusive), for a bounded PRNG function 58 | -s 59 | Set the minimum seed (inclusive), for brute forcing (a 64 bit signed integer) 60 | -S 61 | Set the maxmimum seed (inclusive), for brute forcing (a 64 bit signed integer) 62 | 63 | Examples: 64 | Cracking a list of random numbers in test_ints.txt 65 | ./untwister -i test_ints.txt 66 | 67 | Generating 70 random numbers from seed 1234, using glibc-rand 68 | ./untwister -d 70 -g 1234 -r glibc-rand 69 | 70 | Generating 90 random numbers from state file saved in state.txt 71 | ./untwister -d 90 -g -i state.txt 72 | ``` 73 | 74 | 75 | Python Bindings 76 | ================= 77 | * Python 2.7 78 | * Requires Boost C++ Python library 79 | 80 | ### Ubuntu/Debian Linux 81 | 82 | ``` 83 | sudo apt-get install python-dev libboost-python-dev libcppunit-dev 84 | make python 85 | ``` 86 | 87 | ### OSX 88 | 89 | ``` 90 | brew install boost --with-python 91 | make python 92 | ``` 93 | 94 | 95 | Example script: 96 | 97 | ``` 98 | #!/usr/bin/env python 99 | import untwister 100 | 101 | with open('observed_ints.txt') as fp: 102 | sample = [int(line) for line in fp.readlines()] 103 | results = untwister.bruteforce(untwister.MT19937, sample, threads=4) 104 | print results # We get back a list of tuples 105 | ``` 106 | -------------------------------------------------------------------------------- /prngs/Java.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "Java.h" 19 | #include "../ConsoleColors.h" 20 | #include 21 | 22 | Java::Java() 23 | { 24 | m_seedValue = 0; 25 | m_originalSeed = 0; 26 | } 27 | 28 | Java::~Java() {} 29 | 30 | const std::string Java::getName() 31 | { 32 | return JAVA; 33 | } 34 | 35 | void Java::seed(int64_t value) 36 | { 37 | m_originalSeed = value; 38 | m_seedValue = (value ^ 0x5DEECE66DL) & ((1L << 48) - 1); 39 | } 40 | 41 | int32_t Java::next(int32_t bits) 42 | { 43 | /* Update the seed */ 44 | m_seedValue = (m_seedValue * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1); 45 | /* Return bits of the seed, masked out. */ 46 | return (int32_t)(m_seedValue >> (48 - bits)); 47 | } 48 | 49 | int64_t Java::getSeed() 50 | { 51 | return m_originalSeed; 52 | } 53 | 54 | uint32_t Java::random(void) 55 | { 56 | if(m_isBounded) 57 | { 58 | /* Java expects the upper bound to be exclusive, but untwister is inclusive. 59 | So we need to add one to the bound here to compensate. */ 60 | uint32_t bound = m_maxBound - m_minBound + 1; 61 | 62 | if ((bound & -bound) == bound) // i.e., bound is a power of 2 63 | { 64 | return (int32_t)((bound * (int64_t)next(31)) >> 31); 65 | } 66 | 67 | int32_t bits, val; 68 | do { 69 | bits = next(31); 70 | val = bits % bound; 71 | } while (bits - val + (bound-1) < 0); 72 | return val + m_minBound; 73 | } 74 | else 75 | { 76 | return next(32); 77 | } 78 | } 79 | 80 | uint32_t Java::getStateSize(void) 81 | { 82 | return JAVA_STATE_SIZE; 83 | } 84 | 85 | void Java::setState(std::vector inState) 86 | { 87 | m_state = inState; 88 | m_state.resize(JAVA_STATE_SIZE, 0); 89 | } 90 | 91 | std::vector Java::getState(void) 92 | { 93 | return m_state; 94 | } 95 | 96 | std::vector Java::predictForward(uint32_t) 97 | { 98 | std::vector ret; 99 | //TODO 100 | return ret; 101 | } 102 | 103 | std::vector Java::predictBackward(uint32_t) 104 | { 105 | std::vector ret; 106 | //TODO 107 | return ret; 108 | } 109 | 110 | bool Java::reverseToSeed(int64_t *outSeed, uint32_t depth) 111 | { 112 | //TODO 113 | return false; 114 | } 115 | 116 | void Java::tune(std::vector evidenceForward, std::vector evidenceBackward) 117 | { 118 | //TODO 119 | } 120 | 121 | void Java::setEvidence(std::vector) 122 | { 123 | 124 | } 125 | 126 | void Java::setBounds(uint32_t min, uint32_t max) 127 | { 128 | m_minBound = min; 129 | m_maxBound = max; 130 | m_isBounded = true; 131 | } 132 | 133 | int64_t Java::getMinSeed() 134 | { 135 | return LLONG_MIN; 136 | } 137 | 138 | int64_t Java::getMaxSeed() 139 | { 140 | return LLONG_MAX; 141 | } 142 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Standard flags 2 | CPPFLAGS = -std=gnu++11 -O3 -g3 -Wall -c -fmessage-length=0 -MMD -fPIC 3 | PYTHON = /usr/include/python2.7 4 | BOOST = /usr/include 5 | OBJS = ./prngs/LSBState.o ./prngs/GlibcRand.o ./prngs/PHP_mt19937.o ./prngs/Mt19937.o ./prngs/Ruby.o ./prngs/Java.o ./prngs/PRNGFactory.o ./prngs/DotNetSystemRandom.o ./prngs/LSBStatePHP5_rand.o ./prngs/PHP5_rand.o ./Untwister.o 6 | TEST_OBJS = ./tests/runner.o ./tests/TestRuby.o ./tests/TestJava.o ./tests/TestMt19937.o ./tests/TestPRNGFactory.o ./tests/Test_PHP_mt19937.o ./tests/TestUntwister.o 7 | CC = g++ 8 | 9 | all: GlibcRand Mt19937 PHP_mt19937 Ruby Java LSBState PRNGFactory DotNetSystemRandom LSBStatePHP5_rand PHP5_rand Untwister 10 | $(CC) $(CPPFLAGS) -pthread -MF"main.d" -MT"main.d" -o "main.o" "./main.cpp" 11 | $(CC) -std=gnu++11 -O3 -pthread $(OBJS) main.o -o untwister 12 | 13 | python: GlibcRand Mt19937 PHP_mt19937 Ruby Java LSBState PRNGFactory Untwister 14 | $(CC) $(CPPFLAGS) -I$(PYTHON) -I$(BOOST) py-untwister.cpp -o py-untwister.o 15 | $(CC) -std=c++11 -shared -fPIC -O3 $(OBJS) py-untwister.o -lboost_python -lpython2.7 -o untwister.so 16 | 17 | tests: GlibcRand Mt19937 PHP_mt19937 Ruby Java LSBState PRNGFactory Untwister 18 | $(CC) $(CPPFLAGS) -MF"./tests/TestRuby.d" -MT"./tests/TestRuby.d" -o "./tests/TestRuby.o" "./tests/TestRuby.cpp" 19 | $(CC) $(CPPFLAGS) -MF"./tests/TestJava.d" -MT"./tests/TestJava.d" -o "./tests/TestJava.o" "./tests/TestJava.cpp" 20 | $(CC) $(CPPFLAGS) -MF"./tests/TestMt19937.d" -MT"./tests/TestMt19937.d" -o "./tests/TestMt19937.o" "./tests/TestMt19937.cpp" 21 | $(CC) $(CPPFLAGS) -MF"./tests/Test_PHP_mt19937.d" -MT"./tests/Test_PHP_mt19937.d" -o "./tests/Test_PHP_mt19937.o" "./tests/Test_PHP_mt19937.cpp" 22 | $(CC) $(CPPFLAGS) -MF"./tests/TestPRNGFactory.d" -MT"./tests/TestPRNGFactory.d" -o "./tests/TestPRNGFactory.o" "./tests/TestPRNGFactory.cpp" 23 | $(CC) $(CPPFLAGS) -MF"./tests/TestUntwister.d" -MT"./tests/TestUntwister.d" -o "./tests/TestUntwister.o" "./tests/TestUntwister.cpp" 24 | $(CC) $(CPPFLAGS) -MF"./tests/runner.d" -MT"./tests/runner.d" -o "./tests/runner.o" "./tests/runner.cpp" 25 | $(CC) -std=gnu++11 -O3 -pthread $(OBJS) $(TEST_OBJS) -o untwister_tests -lcppunit 26 | 27 | GlibcRand: 28 | $(CC) $(CPPFLAGS) -MF"prngs/GlibcRand.d" -MT"prngs/GlibcRand.d" -o "prngs/GlibcRand.o" "./prngs/GlibcRand.cpp" 29 | 30 | Mt19937: 31 | $(CC) $(CPPFLAGS) -MF"prngs/Mt19937.d" -MT"prngs/Mt19937.d" -o "prngs/Mt19937.o" "./prngs/Mt19937.cpp" 32 | 33 | PHP_mt19937: 34 | $(CC) $(CPPFLAGS) -MF"prngs/PHP_mt19937.d" -MT"prngs/PHP_mt19937.d" -o "prngs/PHP_mt19937.o" "./prngs/PHP_mt19937.cpp" 35 | 36 | Ruby: 37 | $(CC) $(CPPFLAGS) -MF"prngs/Ruby.d" -MT"prngs/Ruby.d" -o "prngs/Ruby.o" "./prngs/Ruby.cpp" 38 | 39 | Java: 40 | $(CC) $(CPPFLAGS) -MF"prngs/Java.d" -MT"prngs/Java.d" -o "prngs/Java.o" "./prngs/Java.cpp" 41 | 42 | LSBState: 43 | $(CC) $(CPPFLAGS) -MF"prngs/LSBState.d" -MT"prngs/LSBState.d" -o "prngs/LSBState.o" "./prngs/LSBState.cpp" 44 | 45 | PRNGFactory: 46 | $(CC) $(CPPFLAGS) -MF"prngs/PRNGFactory.d" -MT"prngs/PRNGFactory.d" -o "prngs/PRNGFactory.o" "./prngs/PRNGFactory.cpp" 47 | 48 | DotNetSystemRandom: 49 | $(CC) $(CPPFLAGS) -MF"prngs/DotNetSystemRandom.d" -MT"prngs/DotNetSystemRandom.d" -o "prngs/DotNetSystemRandom.o" "./prngs/DotNetSystemRandom.cpp" 50 | 51 | LSBStatePHP5_rand: 52 | $(CC) $(CPPFLAGS) -MF"prngs/LSBStatePHP5_rand.d" -MT"prngs/LSBStatePHP5_rand.d" -o "prngs/LSBStatePHP5_rand.o" "./prngs/LSBStatePHP5_rand.cpp" 53 | 54 | PHP5_rand: 55 | $(CC) $(CPPFLAGS) -MF"prngs/PHP5_rand.d" -MT"prngs/PHP5_rand.d" -o "prngs/PHP5_rand.o" "./prngs/PHP5_rand.cpp" 56 | 57 | Untwister: 58 | $(CC) $(CPPFLAGS) -pthread -MF"Untwister.d" -MT"Untwister.d" -o "Untwister.o" "./Untwister.cpp" 59 | 60 | clean: 61 | rm -f ./prngs/*.o 62 | rm -f ./prngs/*.d 63 | rm -f ./tests/*.o 64 | rm -f ./tests/*.d 65 | rm -f *.o 66 | rm -f *.d 67 | rm -f untwister untwister_tests untwister.so 68 | -------------------------------------------------------------------------------- /prngs/DotNetSystemRandom.h: -------------------------------------------------------------------------------- 1 | /* 2 | This program is free software: you can redistribute it and/or modify 3 | it under the terms of the GNU General Public License as published by 4 | the Free Software Foundation, either version 3 of the License, or 5 | (at your option) any later version. 6 | 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | 12 | You should have received a copy of the GNU General Public License 13 | along with this program. If not, see . 14 | 15 | ----------------------------------------------------------------------------------------- 16 | Some code based off System.Random code located at: 17 | https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Random.cs 18 | 19 | Above System.random code licensed under MIT license: 20 | " 21 | The MIT License (MIT) 22 | 23 | Copyright (c) .NET Foundation and Contributors 24 | 25 | Permission is hereby granted, free of charge, to any person obtaining a copy 26 | of this software and associated documentation files (the "Software"), to deal 27 | in the Software without restriction, including without limitation the rights 28 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 29 | copies of the Software, and to permit persons to whom the Software is 30 | furnished to do so, subject to the following conditions: 31 | 32 | The above copyright notice and this permission notice shall be included in all 33 | copies or substantial portions of the Software. 34 | 35 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 36 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 37 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 38 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 39 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 40 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 41 | SOFTWARE. 42 | " 43 | ----------------------------------------------------------------------------------------- 44 | */ 45 | 46 | #ifndef DOTNETSYSTEMRANDOM_H_ 47 | #define DOTNETSYSTEMRANDOM_H_ 48 | 49 | #include 50 | #include 51 | #include 52 | #include "PRNG.h" 53 | 54 | static const std::string DOTNET_SYSTEMRANDOM = "dotnet-systemrandom"; 55 | static const uint32_t DOTNET_STATE_SIZE = 2147483647; // State inference attack not yet implemented. 56 | 57 | class DotNetSystemRandom: public PRNG { 58 | public: 59 | DotNetSystemRandom(); 60 | virtual ~DotNetSystemRandom(); 61 | 62 | const std::string getName(void); 63 | void seed(int64_t value); 64 | int64_t getSeed(void); 65 | uint32_t random(void); 66 | void setBounds(uint32_t, uint32_t); 67 | 68 | int64_t getMinSeed(); 69 | int64_t getMaxSeed(); 70 | 71 | private: 72 | uint32_t getStateSize(void); 73 | void setState(std::vector inState); 74 | std::vector getState(void); 75 | 76 | void setEvidence(std::vector); 77 | 78 | std::vector predictForward(uint32_t); 79 | std::vector predictBackward(uint32_t); 80 | 81 | void tune(std::vector, std::vector); 82 | 83 | bool reverseToSeed(int64_t *, uint32_t); 84 | 85 | // Specific System.Random methods. 86 | 87 | double Sample(void); 88 | int32_t InternalSample(void); 89 | double GetSampleForLargeRange(void); 90 | 91 | // Based off System.Random Private Constants 92 | 93 | static const int32_t MBIG = INT_MAX; // Int32.MaxValue, 0x7FFFFFFF 94 | static const int32_t MSEED = 161803398; 95 | static const int32_t MZ = 0; 96 | 97 | // Based off System.Random Member Variables 98 | 99 | uint32_t inext; 100 | uint32_t inextp; 101 | int32_t SeedArray[56]; 102 | }; 103 | 104 | #endif /* DOTNETSYSTEMRANDOM_H_ */ 105 | -------------------------------------------------------------------------------- /prngs/Ruby.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "Ruby.h" 19 | #include "../ConsoleColors.h" 20 | #include 21 | #include 22 | 23 | Ruby::Ruby() 24 | { 25 | m_isBounded = false; 26 | seedValue = 0; 27 | m_mt = new MT; 28 | init_genrand(m_mt, seedValue); 29 | } 30 | 31 | Ruby::~Ruby() 32 | { 33 | delete m_mt; 34 | m_mt = NULL; 35 | } 36 | 37 | const std::string Ruby::getName() 38 | { 39 | return RUBY_RAND; 40 | } 41 | 42 | void Ruby::seed(int64_t value) 43 | { 44 | delete m_mt; 45 | m_mt = new MT; 46 | seedValue = (uint32_t)value; 47 | init_genrand(m_mt, seedValue); 48 | } 49 | 50 | int64_t Ruby::getSeed() 51 | { 52 | return seedValue; 53 | } 54 | 55 | uint32_t Ruby::random() 56 | { 57 | if(m_isBounded) 58 | { 59 | /* generate a number between 0 and (max-min), then scale it back up */ 60 | uint32_t limit = m_maxBound - m_minBound; 61 | 62 | /* Ruby does an algorithm of retries within a power of two bound */ 63 | uint32_t mask = make_mask(limit); 64 | while(true) 65 | { 66 | uint32_t val = genrand_int32(m_mt); 67 | val &= mask; 68 | if(val < limit) 69 | { 70 | return val + m_minBound; 71 | } 72 | } 73 | } 74 | else 75 | { 76 | return genrand_int32(m_mt); 77 | } 78 | } 79 | 80 | void Ruby::init_genrand(struct MT* mt, unsigned int s) 81 | { 82 | int j; 83 | mt->state[0] = s & 0xffffffffU; 84 | for (j=1; jstate[j] = (1812433253U * (mt->state[j-1] ^ (mt->state[j-1] >> 30)) + j); 86 | /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ 87 | /* In the previous versions, MSBs of the seed affect */ 88 | /* only MSBs of the array state[]. */ 89 | /* 2002/01/09 modified by Makoto Matsumoto */ 90 | mt->state[j] &= 0xffffffff; /* for >32 bit machines */ 91 | } 92 | mt->left = 1; 93 | mt->next = mt->state + N; 94 | } 95 | 96 | void Ruby::next_state(struct MT *mt) 97 | { 98 | unsigned int *p = mt->state; 99 | int j; 100 | 101 | mt->left = N; 102 | mt->next = mt->state; 103 | 104 | for (j=N-M+1; --j; p++) 105 | *p = p[M] ^ TWIST(p[0], p[1]); 106 | 107 | for (j=M; --j; p++) 108 | *p = p[M-N] ^ TWIST(p[0], p[1]); 109 | 110 | *p = p[M-N] ^ TWIST(p[0], mt->state[0]); 111 | } 112 | 113 | uint32_t Ruby::genrand_int32(struct MT *mt) 114 | { 115 | /* mt must be initialized */ 116 | unsigned int y; 117 | 118 | if (--mt->left <= 0) next_state(mt); 119 | y = *mt->next++; 120 | 121 | /* Tempering */ 122 | y ^= (y >> 11); 123 | y ^= (y << 7) & 0x9d2c5680; 124 | y ^= (y << 15) & 0xefc60000; 125 | y ^= (y >> 18); 126 | 127 | return y; 128 | } 129 | 130 | uint32_t Ruby::getStateSize(void) 131 | { 132 | return RUBY_STATE_SIZE; 133 | } 134 | 135 | void Ruby::setState(std::vector inState) 136 | { 137 | m_state = inState; 138 | m_state.resize(RUBY_STATE_SIZE, 0); 139 | } 140 | 141 | std::vector Ruby::getState(void) 142 | { 143 | return m_state; 144 | } 145 | 146 | std::vector Ruby::predictForward(uint32_t) 147 | { 148 | std::vector ret; 149 | //TODO 150 | return ret; 151 | } 152 | 153 | std::vector Ruby::predictBackward(uint32_t) 154 | { 155 | std::vector ret; 156 | //TODO 157 | return ret; 158 | } 159 | 160 | bool Ruby::reverseToSeed(int64_t *outSeed, uint32_t depth) 161 | { 162 | return false; 163 | } 164 | 165 | void Ruby::tune(std::vector evidenceForward, std::vector evidenceBackward) 166 | { 167 | //TODO 168 | } 169 | 170 | void Ruby::setEvidence(std::vector) 171 | { 172 | 173 | } 174 | 175 | uint32_t Ruby::make_mask(uint32_t x) 176 | { 177 | x = x | x >> 1; 178 | x = x | x >> 2; 179 | x = x | x >> 4; 180 | x = x | x >> 8; 181 | x = x | x >> 16; 182 | return x; 183 | } 184 | 185 | void Ruby::setBounds(uint32_t min, uint32_t max) 186 | { 187 | m_minBound = min; 188 | m_maxBound = max; 189 | m_isBounded = true; 190 | } 191 | 192 | int64_t Ruby::getMinSeed() 193 | { 194 | return 0; 195 | } 196 | 197 | int64_t Ruby::getMaxSeed() 198 | { 199 | return UINT_MAX; 200 | } 201 | -------------------------------------------------------------------------------- /prngs/PHP_mt19937.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | 17 | */ 18 | 19 | #include "PHP_mt19937.h" 20 | #include "../ConsoleColors.h" 21 | #include 22 | 23 | PHP_mt19937::PHP_mt19937() 24 | { 25 | m_seedValue = 0; 26 | m_mt = NULL; 27 | } 28 | 29 | PHP_mt19937::~PHP_mt19937() 30 | { 31 | delete m_mt; 32 | m_mt = NULL; 33 | } 34 | 35 | const std::string PHP_mt19937::getName() 36 | { 37 | return PHP_MT_RAND; 38 | } 39 | 40 | void PHP_mt19937::seed(int64_t value) 41 | { 42 | delete m_mt; 43 | m_mt = new MT; 44 | m_seedValue = (int64_t)value; 45 | php_mt_initialize(m_seedValue); 46 | php_mt_reload(); 47 | } 48 | 49 | int64_t PHP_mt19937::getSeed() 50 | { 51 | return m_seedValue; 52 | } 53 | 54 | uint32_t PHP_mt19937::random() 55 | { 56 | int32_t result; 57 | 58 | result = genrand_int32(m_mt) >> 1; 59 | 60 | if (m_isBounded) { 61 | /* 62 | ----------------------------------------------------------------------------------------- 63 | Adapted from PHP code located at: 64 | https://github.com/php/php-src/blob/PHP-5.6.27/ext/standard/rand.c 65 | https://github.com/php/php-src/blob/PHP-5.6.27/ext/standard/php_rand.h 66 | 67 | Above PHP code licensed under version 3.01 of the PHP license (http://www.php.net/license/3_01.txt) 68 | ----------------------------------------------------------------------------------------- 69 | 70 | int mt_rand([int min, int max]) uses RAND_RANGE(): 71 | https://github.com/php/php-src/blob/PHP-5.6.27/ext/standard/rand.c#L340 72 | ... 73 | if (argc == 2) { 74 | RAND_RANGE(number, min, max, PHP_MT_RAND_MAX); 75 | } 76 | ... 77 | 78 | RAND_RANGE defined here: 79 | https://github.com/php/php-src/blob/PHP-5.6.27/ext/standard/php_rand.h#L44 80 | ... 81 | #define RAND_RANGE(__n, __min, __max, __tmax) \ 82 | (__n) = (__min) + (long) ((double) ( (double) (__max) - (__min) + 1.0) * ((__n) / ((__tmax) + 1.0))) 83 | ... 84 | 85 | */ 86 | result = (uint32_t)((m_minBound) + (int64_t) ((double) ( (double) (m_maxBound) - (m_minBound) + 1.0) * ((result) / ((2147483647) + 1.0)))); 87 | } 88 | 89 | return result; 90 | } 91 | 92 | void PHP_mt19937::php_mt_initialize(uint32_t seed) 93 | { 94 | register uint32_t *s = m_state; 95 | register uint32_t *r = m_state; 96 | register int i = 1; 97 | 98 | *s++ = seed & 0xffffffffU; 99 | for( ; i < N; ++i ) { 100 | *s++ = ( 1812433253U * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffU; 101 | r++; 102 | } 103 | } 104 | 105 | void PHP_mt19937::php_mt_reload() 106 | { 107 | register uint32_t *state = m_state; 108 | register uint32_t *p = state; 109 | register int i; 110 | 111 | for (i = N - M; i--; ++p) 112 | *p = php_twist(p[M], p[0], p[1]); 113 | for (i = M; --i; ++p) 114 | *p = php_twist(p[M-N], p[0], p[1]); 115 | *p = php_twist(p[M-N], p[0], state[0]); 116 | m_left = N; 117 | m_next = state; 118 | } 119 | 120 | uint32_t PHP_mt19937::genrand_int32(struct MT *mt) 121 | { 122 | /* Pull a 32-bit integer from the generator state 123 | Every other access function simply transforms the numbers extracted here */ 124 | 125 | register uint32_t s1; 126 | 127 | if (m_left == 0) { 128 | php_mt_reload(); 129 | } 130 | --m_left; 131 | 132 | s1 = *m_next++; 133 | s1 ^= (s1 >> 11); 134 | s1 ^= (s1 << 7) & 0x9d2c5680U; 135 | s1 ^= (s1 << 15) & 0xefc60000U; 136 | return ( s1 ^ (s1 >> 18) ); 137 | } 138 | 139 | uint32_t PHP_mt19937::getStateSize(void) 140 | { 141 | return PHP_MT_RAND_STATE_SIZE; 142 | } 143 | 144 | void PHP_mt19937::setState(std::vector inState) 145 | { 146 | std::copy(inState.begin(), inState.end(), m_state); 147 | } 148 | 149 | std::vector PHP_mt19937::getState(void) 150 | { 151 | std::vector out(std::begin(m_state), std::end(m_state)); 152 | return out; 153 | } 154 | 155 | std::vector PHP_mt19937::predictForward(uint32_t) 156 | { 157 | std::vector ret; 158 | //TODO 159 | return ret; 160 | } 161 | 162 | std::vector PHP_mt19937::predictBackward(uint32_t) 163 | { 164 | std::vector ret; 165 | //TODO 166 | return ret; 167 | } 168 | 169 | bool PHP_mt19937::reverseToSeed(int64_t *outSeed, uint32_t depth) 170 | { 171 | return false; 172 | } 173 | 174 | void PHP_mt19937::tune(std::vector evidenceForward, std::vector evidenceBackward) 175 | { 176 | //TODO 177 | } 178 | 179 | void PHP_mt19937::setEvidence(std::vector) 180 | { 181 | 182 | } 183 | 184 | void PHP_mt19937::setBounds(uint32_t min, uint32_t max){ 185 | m_minBound = min; 186 | m_maxBound = max; 187 | m_isBounded = true; 188 | } 189 | 190 | int64_t PHP_mt19937::getMinSeed() 191 | { 192 | return 0; 193 | } 194 | 195 | int64_t PHP_mt19937::getMaxSeed() 196 | { 197 | return UINT_MAX; 198 | } 199 | -------------------------------------------------------------------------------- /py-untwister.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | 17 | Notes: Requires Boost C++ libraries 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "Untwister.h" 27 | 28 | using namespace boost::python; 29 | 30 | static const unsigned int TRACE_SIZE = 10; 31 | 32 | /* Segfault handler - for debugging only */ 33 | void handler(int sig) 34 | { 35 | void *trace[TRACE_SIZE]; 36 | size_t size = backtrace(trace, TRACE_SIZE); 37 | std::cerr << "[!] SIGSEGV: " << sig << std::endl; 38 | backtrace_symbols_fd(trace, size, 2); 39 | exit(1); 40 | } 41 | 42 | /* Python __init__ function */ 43 | void PythonInit() 44 | { 45 | signal(SIGSEGV, handler); 46 | signal(SIGABRT, handler); 47 | if(!Py_IsInitialized()) 48 | { 49 | Py_Initialize(); 50 | PyEval_InitThreads(); 51 | } 52 | } 53 | 54 | /* Find a seed */ 55 | list BruteforceAttack(std::string prng, list observations, unsigned int threads, float minimumConfidence, 56 | uint32_t lowerBoundSeed, uint32_t upperBoundSeed, uint32_t depth) 57 | { 58 | Untwister *untwister = new Untwister(len(observations)); 59 | if(!untwister->isSupportedPRNG(prng)) 60 | { 61 | /* Raise Python Exception */ 62 | PyErr_SetString(PyExc_ValueError, "Unsupported PRNG"); 63 | throw error_already_set(); 64 | } 65 | untwister->setPRNG(prng); 66 | untwister->setThreads(threads); 67 | untwister->setDepth(depth); 68 | untwister->setMinConfidence(minimumConfidence); 69 | 70 | /* Convert Python list object to observedOutputs's std::vector */ 71 | for(int index = 0; index < len(observations); ++index) 72 | { 73 | uint32_t data = extract(observations[index]); 74 | untwister->getObservedOutputs()->at(index) = data; 75 | } 76 | 77 | /* Suspend Python's thread, so we can use native C++ threads */ 78 | PyThreadState *pyThreadState = PyEval_SaveThread(); 79 | auto results = untwister->bruteforce(lowerBoundSeed, upperBoundSeed); 80 | PyEval_RestoreThread(pyThreadState); 81 | 82 | /* Covert answers to python list of tuples */ 83 | list pyResults; 84 | for(unsigned int index = 0; index < results.size(); ++index) 85 | { 86 | tuple pySeed = make_tuple(results[index].first, results[index].second); 87 | pyResults.append(pySeed); 88 | } 89 | delete untwister; 90 | return pyResults; 91 | } 92 | 93 | 94 | tuple InferStateAttack(std::string prng, list observations, float minimumConfidence) 95 | { 96 | Untwister *untwister = new Untwister(len(observations)); 97 | if(!untwister->isSupportedPRNG(prng)) 98 | { 99 | /* Raise Python Exception */ 100 | PyErr_SetString(PyExc_ValueError, "Unsupported PRNG"); 101 | throw error_already_set(); 102 | } 103 | 104 | untwister->setPRNG(prng); 105 | 106 | if(untwister->getStateSize() < (uint32_t) len(observations)) 107 | { 108 | PyErr_SetString(PyExc_ValueError, "Cannot infer state, too few observations"); 109 | throw error_already_set(); 110 | } 111 | 112 | untwister->setMinConfidence(minimumConfidence); 113 | 114 | /* Convert Python list object to observedOutputs's std::vector */ 115 | for(int index = 0; index < len(observations); ++index) 116 | { 117 | uint32_t data = extract(observations[index]); 118 | untwister->getObservedOutputs()->at(index) = data; 119 | } 120 | 121 | auto state = untwister->inferState(); 122 | list pyState; 123 | for(unsigned int index = 0; index < state.first.size(); ++index) 124 | { 125 | pyState.append(state.first[index]); 126 | } 127 | delete untwister; 128 | 129 | return make_tuple(pyState, state.second); 130 | } 131 | 132 | /* List all supported PRNGs */ 133 | list Prngs() 134 | { 135 | Untwister *untwister = new Untwister(); 136 | std::vector names = untwister->getSupportedPRNGs(); 137 | 138 | list pyPRNGs; 139 | for(unsigned int index = 0; index < names.size(); ++index) 140 | { 141 | pyPRNGs.append(names[index]); 142 | } 143 | 144 | delete untwister; 145 | 146 | return pyPRNGs; 147 | } 148 | 149 | /* Python interface */ 150 | BOOST_PYTHON_MODULE(untwister) { 151 | 152 | def("untwister", PythonInit); 153 | 154 | scope current; 155 | current.attr("__doc__") = "Multi-threaded seed recovery tool for common PRNGs"; 156 | current.attr("MT19937") = "mt19937"; 157 | current.attr("GLIBC") = "glibc-rand"; 158 | current.attr("RUBY") = "ruby-rand"; 159 | unsigned int threads = std::thread::hardware_concurrency(); 160 | current.attr("THREADS") = threads; 161 | 162 | def("get_supported_prngs", Prngs, "\n Get a list of supported PRNGs"); 163 | 164 | def( 165 | "bruteforce", 166 | BruteforceAttack, 167 | (arg("prng"), arg("observations"), arg("threads") = threads, arg("confidence") = 100.0, \ 168 | arg("lower") = 0, arg("upper") = UINT_MAX, arg("depth") = 1000), 169 | "\nThis function attempts to recover a seed using bruteforce for any supported PRNG" 170 | ); 171 | 172 | def( 173 | "infer_state", 174 | InferStateAttack, 175 | (arg("prng"), arg("observations"), arg("confidence") = 100.0), 176 | "\nThis function attempts to infer the internal state of the PRNG" 177 | ); 178 | 179 | } 180 | -------------------------------------------------------------------------------- /tests/TestUntwister.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "TestUntwister.h" 19 | #include 20 | 21 | void TestUntwister::setUp() 22 | { 23 | m_mtTestInputs = new std::vector(); 24 | m_loadTestFile("tests/mt_test_ints.txt", m_mtTestInputs); 25 | 26 | m_glibcTestInputs = new std::vector(); 27 | m_loadTestFile("tests/glibc_test_ints.txt", m_glibcTestInputs); 28 | 29 | m_rubyTestInputs = new std::vector(); 30 | m_loadTestFile("tests/ruby_test_ints.txt", m_rubyTestInputs); 31 | } 32 | 33 | void TestUntwister::tearDown() 34 | { 35 | delete m_mtTestInputs; 36 | delete m_glibcTestInputs; 37 | delete m_rubyTestInputs; 38 | } 39 | 40 | void TestUntwister::m_loadTestFile(std::string path, std::vector *testInputs) 41 | { 42 | std::ifstream infile(path); 43 | if (!infile) 44 | { 45 | std::cerr << WARN << "ERROR: File \"" << path << "\" not found" << std::endl; 46 | } 47 | std::string line; 48 | while (std::getline(infile, line)) 49 | { 50 | uint32_t value = strtoul(line.c_str(), NULL, 0); 51 | testInputs->push_back(value); 52 | } 53 | } 54 | 55 | void TestUntwister::initalizationTest() 56 | { 57 | Untwister *untwister = new Untwister(); 58 | CPPUNIT_ASSERT(untwister != NULL); 59 | delete untwister; 60 | } 61 | 62 | void TestUntwister::setThreadsTest() 63 | { 64 | Untwister *untwister = new Untwister(); 65 | untwister->setThreads(1); 66 | CPPUNIT_ASSERT(untwister->getThreads() == 1); 67 | untwister->setThreads(2); 68 | CPPUNIT_ASSERT(untwister->getThreads() == 2); 69 | untwister->setThreads(3); 70 | CPPUNIT_ASSERT(untwister->getThreads() == 3); 71 | untwister->setThreads(4); 72 | CPPUNIT_ASSERT(untwister->getThreads() == 4); 73 | delete untwister; 74 | } 75 | 76 | void TestUntwister::setDepthTest() 77 | { 78 | Untwister *untwister = new Untwister(); 79 | untwister->setDepth(100); 80 | CPPUNIT_ASSERT(untwister->getDepth() == 100); 81 | untwister->setDepth(200); 82 | CPPUNIT_ASSERT(untwister->getDepth() == 200); 83 | untwister->setDepth(3000); 84 | CPPUNIT_ASSERT(untwister->getDepth() == 3000); 85 | untwister->setDepth(4000); 86 | CPPUNIT_ASSERT(untwister->getDepth() == 4000); 87 | delete untwister; 88 | } 89 | 90 | void TestUntwister::setMinConfidenceTest() 91 | { 92 | Untwister *untwister = new Untwister(); 93 | untwister->setMinConfidence(99.0); 94 | CPPUNIT_ASSERT(untwister->getMinConfidence() == 99.0); 95 | untwister->setMinConfidence(50.0); 96 | CPPUNIT_ASSERT(untwister->getMinConfidence() == 50.0); 97 | untwister->setMinConfidence(75.75); 98 | CPPUNIT_ASSERT(untwister->getMinConfidence() == 75.75); 99 | untwister->setMinConfidence(100.0); 100 | CPPUNIT_ASSERT(untwister->getMinConfidence() == 100.0); 101 | delete untwister; 102 | } 103 | 104 | void TestUntwister::setPRNGTest() 105 | { 106 | Untwister *untwister = new Untwister(); 107 | untwister->setPRNG(std::string("mt19937")); 108 | CPPUNIT_ASSERT(untwister->getPRNG() == "mt19937"); 109 | CPPUNIT_ASSERT_THROW(untwister->setPRNG(std::string("foobar")), std::runtime_error); 110 | delete untwister; 111 | } 112 | 113 | void TestUntwister::mtBruteforceTest() 114 | { 115 | Untwister *untwister = new Untwister(); 116 | for (unsigned int index = 0; index < m_mtTestInputs->size(); ++index) 117 | { 118 | untwister->addObservedOutput(m_mtTestInputs->at(index)); 119 | } 120 | CPPUNIT_ASSERT(0 < untwister->getObservedOutputs()->size()); 121 | untwister->setPRNG(std::string("mt19937")); 122 | 123 | for (unsigned int index = 0; index < TEST_COUNT; ++index) 124 | { 125 | uint32_t start = 100 * TEST_COUNT; 126 | auto results = untwister->bruteforce(start, 50000); 127 | 128 | CPPUNIT_ASSERT(0 < results.size()); 129 | if (0 < results.size()) 130 | { 131 | CPPUNIT_ASSERT(results[0].first == 31337); 132 | CPPUNIT_ASSERT(results[0].second == 100.0); 133 | } 134 | } 135 | 136 | auto results2 = untwister->bruteforce(50000, 100000); 137 | CPPUNIT_ASSERT(0 == results2.size()); 138 | 139 | delete untwister; 140 | } 141 | 142 | void TestUntwister::glibcBruteforceTest() 143 | { 144 | Untwister *untwister = new Untwister(); 145 | for (unsigned int index = 0; index < m_glibcTestInputs->size(); ++index) 146 | { 147 | untwister->addObservedOutput(m_glibcTestInputs->at(index)); 148 | } 149 | CPPUNIT_ASSERT(0 < untwister->getObservedOutputs()->size()); 150 | untwister->setPRNG(std::string("glibc-rand")); 151 | 152 | for (unsigned int index = 0; index < TEST_COUNT; ++index) 153 | { 154 | uint32_t start = 100 * TEST_COUNT; 155 | auto results = untwister->bruteforce(start, 50000); 156 | 157 | CPPUNIT_ASSERT(0 < results.size()); 158 | if (0 < results.size()) 159 | { 160 | CPPUNIT_ASSERT(results[0].first == 1337); 161 | CPPUNIT_ASSERT(results[0].second == 100.0); 162 | } 163 | } 164 | 165 | auto results2 = untwister->bruteforce(50000, 100000); 166 | CPPUNIT_ASSERT(0 == results2.size()); 167 | 168 | delete untwister; 169 | } 170 | 171 | void TestUntwister::rubyBruteforceTest() 172 | { 173 | Untwister *untwister = new Untwister(); 174 | for (unsigned int index = 0; index < m_rubyTestInputs->size(); ++index) 175 | { 176 | untwister->addObservedOutput(m_rubyTestInputs->at(index)); 177 | } 178 | CPPUNIT_ASSERT(0 < untwister->getObservedOutputs()->size()); 179 | untwister->setPRNG(std::string("ruby-rand")); 180 | 181 | for (unsigned int index = 0; index < TEST_COUNT; ++index) 182 | { 183 | uint32_t start = 100 * TEST_COUNT; 184 | auto results = untwister->bruteforce(start, 50000); 185 | 186 | CPPUNIT_ASSERT(0 < results.size()); 187 | if (0 < results.size()) 188 | { 189 | CPPUNIT_ASSERT(results[0].first == 31337); 190 | CPPUNIT_ASSERT(results[0].second == 100.0); 191 | } 192 | } 193 | 194 | auto results2 = untwister->bruteforce(50000, 100000); 195 | CPPUNIT_ASSERT(0 == results2.size()); 196 | delete untwister; 197 | } 198 | -------------------------------------------------------------------------------- /prngs/DotNetSystemRandom.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This program is free software: you can redistribute it and/or modify 3 | it under the terms of the GNU General Public License as published by 4 | the Free Software Foundation, either version 3 of the License, or 5 | (at your option) any later version. 6 | 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | 12 | You should have received a copy of the GNU General Public License 13 | along with this program. If not, see . 14 | 15 | ----------------------------------------------------------------------------------------- 16 | Some code based off System.Random code located at: 17 | https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Random.cs 18 | 19 | Above System.random code licensed under MIT license: 20 | " 21 | The MIT License (MIT) 22 | 23 | Copyright (c) .NET Foundation and Contributors 24 | 25 | Permission is hereby granted, free of charge, to any person obtaining a copy 26 | of this software and associated documentation files (the "Software"), to deal 27 | in the Software without restriction, including without limitation the rights 28 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 29 | copies of the Software, and to permit persons to whom the Software is 30 | furnished to do so, subject to the following conditions: 31 | 32 | The above copyright notice and this permission notice shall be included in all 33 | copies or substantial portions of the Software. 34 | 35 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 36 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 37 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 38 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 39 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 40 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 41 | SOFTWARE. 42 | " 43 | ----------------------------------------------------------------------------------------- 44 | Implements System.Random() C# method, using Next(), and Next(min, max). 45 | 46 | */ 47 | 48 | #include 49 | #include 50 | #include 51 | #include 52 | #include 53 | #include "DotNetSystemRandom.h" 54 | #include "../ConsoleColors.h" 55 | 56 | DotNetSystemRandom::DotNetSystemRandom() {} 57 | 58 | DotNetSystemRandom::~DotNetSystemRandom() {} 59 | 60 | const std::string DotNetSystemRandom::getName() { 61 | return DOTNET_SYSTEMRANDOM; 62 | } 63 | 64 | // Based off System.Random Random() 65 | void DotNetSystemRandom::seed(int64_t Seed) { 66 | uint32_t ii = 0; 67 | uint32_t i, k, n; // Used in loops 68 | int32_t mj, mk; 69 | 70 | int32_t subtraction = (Seed == INT_MIN) ? INT_MAX : std::abs(Seed); 71 | mj = MSEED - subtraction; 72 | SeedArray[55] = mj; 73 | mk = 1; 74 | 75 | for (i = 1; i < 55; i++) { 76 | if ((ii += 21) >= 55) ii -= 55; 77 | SeedArray[ii] = mk; 78 | mk = mj - mk; 79 | if (mk < 0) mk+=MBIG; 80 | mj = SeedArray[ii]; 81 | } 82 | 83 | for (k = 1; k < 5; k++) { 84 | for (i = 1; i < 56; i++) { 85 | n = i + 30; 86 | if (n >= 55) n -= 55; 87 | SeedArray[i] -= SeedArray[1 + n]; 88 | if (SeedArray[i] < 0) SeedArray[i]+=MBIG; 89 | } 90 | } 91 | inext = 0; 92 | inextp = 21; 93 | Seed = 1; 94 | } 95 | // Based off System.Random->Sample() 96 | double DotNetSystemRandom::Sample() { 97 | return (DotNetSystemRandom::InternalSample()*(1.0/MBIG)); 98 | } 99 | 100 | // Based off System.Random->InternalSample() 101 | int32_t DotNetSystemRandom::InternalSample() { 102 | int32_t retVal; 103 | uint32_t locINext = inext; 104 | uint32_t locINextp = inextp; 105 | 106 | if (++locINext >= 56) locINext = 1; 107 | if (++locINextp >= 56) locINextp = 1; 108 | 109 | retVal = SeedArray[locINext]-SeedArray[locINextp]; 110 | 111 | if (retVal == MBIG) retVal--; 112 | if (retVal < 0) retVal+=MBIG; 113 | 114 | SeedArray[locINext] = retVal; 115 | 116 | inext = locINext; 117 | inextp = locINextp; 118 | 119 | return retVal; 120 | } 121 | 122 | // Based off System.Random->GetSampleForLargeRange() 123 | double DotNetSystemRandom::GetSampleForLargeRange() { 124 | bool negative; 125 | 126 | int32_t result = DotNetSystemRandom::InternalSample(); 127 | 128 | negative = (DotNetSystemRandom::InternalSample()%2 == 0) ? true : false; 129 | if (negative) { 130 | result = -result; 131 | } 132 | double d = result; 133 | d += (INT_MAX - 1); 134 | d /= 2*(uint32_t)INT_MAX - 1; 135 | return d; 136 | } 137 | 138 | /* 139 | Based off System.Random->Next(), System.Random->Next(minValue, maxValue) 140 | Known limitations; can only return positive numbers (uint32_t) due to 141 | PRNG class virtual uint32_t random(void). 142 | 143 | */ 144 | uint32_t DotNetSystemRandom::random() { 145 | uint32_t randomResult; 146 | 147 | if (m_isBounded) { 148 | // Based off System.Random->Next(minValue, maxValue) 149 | int64_t range = (int64_t)m_maxBound - m_minBound; 150 | if (range <= (int64_t)INT_MAX) { 151 | randomResult = ((int32_t)(DotNetSystemRandom::Sample() * range) + m_minBound); 152 | } else { 153 | randomResult = (int32_t)((int64_t)(DotNetSystemRandom::GetSampleForLargeRange() * range) + m_minBound); 154 | } 155 | } else { 156 | // Based off System.Random->Next() 157 | randomResult = DotNetSystemRandom::InternalSample(); 158 | } 159 | 160 | return randomResult; 161 | } 162 | 163 | void DotNetSystemRandom::setBounds(uint32_t min, uint32_t max) { 164 | m_minBound = min; 165 | m_maxBound = max; 166 | m_isBounded = true; 167 | } 168 | 169 | int64_t DotNetSystemRandom::getMinSeed() { 170 | // System.Random() is seeded with an int; signed integer 171 | return 0; 172 | } 173 | 174 | int64_t DotNetSystemRandom::getMaxSeed() { 175 | // System.Random() is seeded with an int; signed integer 176 | return INT_MAX; 177 | } 178 | 179 | 180 | // Placeholder methods, aren't doing anything yet 181 | 182 | // State inference attack not yet implemented 183 | uint32_t DotNetSystemRandom::getStateSize(void) { 184 | return DOTNET_STATE_SIZE; 185 | } 186 | 187 | int64_t DotNetSystemRandom::getSeed() { 188 | return 0; 189 | } 190 | 191 | void DotNetSystemRandom::setState(std::vector inState) {} 192 | 193 | std::vector DotNetSystemRandom::getState(void) { 194 | std::vector ret; 195 | return ret; 196 | } 197 | 198 | void DotNetSystemRandom::setEvidence(std::vector evidence) {} 199 | 200 | std::vector DotNetSystemRandom::predictForward(uint32_t length) { 201 | std::vector ret; 202 | return ret; 203 | } 204 | 205 | std::vector DotNetSystemRandom::predictBackward(uint32_t length) { 206 | std::vector ret; 207 | return ret; 208 | } 209 | 210 | void DotNetSystemRandom::tune(std::vector evidenceForward, std::vector evidenceBackward) {} 211 | 212 | bool DotNetSystemRandom::reverseToSeed(int64_t *outSeed, uint32_t depth) { 213 | return false; 214 | } 215 | -------------------------------------------------------------------------------- /prngs/GlibcRand.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "GlibcRand.h" 19 | #include "../ConsoleColors.h" 20 | #include 21 | 22 | GlibcRand::GlibcRand() 23 | { 24 | seedValue = 0; 25 | 26 | m_LSBMap.resize(GLIBC_RAND_STATE_SIZE); 27 | } 28 | 29 | GlibcRand::~GlibcRand() {} 30 | 31 | const std::string GlibcRand::getName() 32 | { 33 | return GLIBC_RAND; 34 | } 35 | 36 | void GlibcRand::seed(int64_t long_seed) 37 | { 38 | uint32_t seed = (uint32_t)long_seed; 39 | long int i; 40 | int32_t word; 41 | int32_t *dst; 42 | int kc; 43 | 44 | /* We must make sure the seed is not 0. Take arbitrarily 1 in this case. */ 45 | if (seed == 0) 46 | seed = 1; 47 | m_glibcstate[0] = seed; 48 | 49 | dst = m_glibcstate; 50 | word = seed; 51 | kc = 31; 52 | for (i = 1; i < kc; ++i) 53 | { 54 | /* This does: 55 | state[i] = (16807 * state[i - 1]) % 2147483647; 56 | but avoids overflowing 31 bits. */ 57 | long int hi = word / 127773; 58 | long int lo = word % 127773; 59 | word = 16807 * lo - 2836 * hi; 60 | if (word < 0) 61 | word += 2147483647; 62 | *++dst = word; 63 | } 64 | 65 | m_fptr = &m_glibcstate[3]; 66 | m_rptr = &m_glibcstate[0]; 67 | kc *= 10; 68 | while (--kc >= 0) 69 | { 70 | random(); 71 | } 72 | } 73 | 74 | int64_t GlibcRand::getSeed() 75 | { 76 | return seedValue; 77 | } 78 | 79 | uint32_t GlibcRand::random() 80 | { 81 | int32_t result; 82 | int32_t *state = m_glibcstate; 83 | 84 | int32_t *fptr = m_fptr; 85 | int32_t *rptr = m_rptr; 86 | int32_t *end_ptr = &m_glibcstate[31]; 87 | int32_t val; 88 | 89 | val = *fptr += *rptr; 90 | /* Chucking least random bit. */ 91 | result = (val >> 1) & 0x7fffffff; 92 | ++fptr; 93 | if (fptr >= end_ptr) 94 | { 95 | fptr = state; 96 | ++rptr; 97 | } 98 | else 99 | { 100 | ++rptr; 101 | if (rptr >= end_ptr) 102 | rptr = state; 103 | } 104 | m_fptr = fptr; 105 | m_rptr = rptr; 106 | 107 | return result; 108 | } 109 | 110 | uint32_t GlibcRand::getStateSize(void) 111 | { 112 | return GLIBC_RAND_STATE_SIZE; 113 | } 114 | 115 | void GlibcRand::setState(std::vector inState) 116 | { 117 | m_state = inState; 118 | m_state.resize(GLIBC_RAND_STATE_SIZE, 0); 119 | 120 | /* Shift left one bit to return to mod 2^32. 121 | Of course, we'll be missing the original LSB, 122 | so we'll have to go fishing for it later. */ 123 | for(uint32_t i = 0; i < m_state.size(); i++) 124 | { 125 | m_state[i] = m_state[i]<<1; 126 | } 127 | } 128 | 129 | std::vector GlibcRand::getState(void) 130 | { 131 | return m_state; 132 | } 133 | 134 | void GlibcRand::setEvidence(std::vector evidence) 135 | { 136 | m_evidence = evidence; 137 | } 138 | 139 | std::vector GlibcRand::predictForward(uint32_t length) 140 | { 141 | std::vector running_state = m_state; 142 | running_state.resize(GLIBC_RAND_STATE_SIZE + length); 143 | 144 | std::vector ret; 145 | 146 | /* There is a more memory efficient way to do this. With a 147 | linked list for the state. But meh. */ 148 | for(uint32_t i = 32; i < length + 32; i++) 149 | { 150 | uint32_t val = running_state[i-31] + running_state[i-3]; 151 | running_state[i] = val; 152 | ret.push_back((val >> 1) & 0x7fffffff); 153 | } 154 | 155 | return ret; 156 | } 157 | 158 | std::vector GlibcRand::predictBackward(uint32_t length) 159 | { 160 | std::vector running_state = m_state; 161 | /* Reverse order for simplicity. Deal with it. */ 162 | std::reverse(running_state.begin(), running_state.end()); 163 | running_state.resize(GLIBC_RAND_STATE_SIZE + length); 164 | 165 | std::vector ret; 166 | 167 | /* There is a more memory efficient way to do this. With a 168 | linked list for the state. But meh. */ 169 | for(uint32_t i = GLIBC_RAND_STATE_SIZE; i < length + GLIBC_RAND_STATE_SIZE; i++) 170 | { 171 | uint32_t val = running_state[i-31] - running_state[i-28]; 172 | running_state[i] = val; 173 | ret.push_back((val >> 1) & 0x7fffffff); 174 | } 175 | 176 | /* Reverse order for simplicity. Deal with it. */ 177 | std::reverse(ret.begin(), ret.end()); 178 | return ret; 179 | } 180 | 181 | /* We just have to make some guesses about the LSBs and then test those 182 | guesses one by one */ 183 | void GlibcRand::tune_repeatedIncrements() 184 | { 185 | /* Keep tuning until no improvements are made anymore */ 186 | bool keepGoing = true; 187 | while(keepGoing) 188 | { 189 | keepGoing = true; 190 | 191 | /* Foreach state integer, test if we can improve predictions by incrementing 192 | that state value.*/ 193 | for(uint32_t i = 0; i < GLIBC_RAND_STATE_SIZE; i++) 194 | { 195 | /* Get the success rate of this state */ 196 | std::vector guesses = this->predictForward(m_evidence.size() - GLIBC_RAND_STATE_SIZE); 197 | 198 | int64_t sum = 0; 199 | for(uint32_t j = 0; j < guesses.size(); j++) 200 | { 201 | sum += std::min(guesses[j] - m_evidence[GLIBC_RAND_STATE_SIZE + j], 202 | m_evidence[GLIBC_RAND_STATE_SIZE + j] - guesses[j]); 203 | } 204 | 205 | //Increment the state val 206 | m_state[i] += 1; 207 | 208 | /* Get the success rate of the new state */ 209 | guesses = this->predictForward(m_evidence.size() - GLIBC_RAND_STATE_SIZE); 210 | 211 | int64_t sum_new = 0; 212 | for(uint32_t j = 0; j < guesses.size(); j++) 213 | { 214 | /* The guess can NEVER be bigger than the evidence */ 215 | if(guesses[j] > m_evidence[GLIBC_RAND_STATE_SIZE + j]) 216 | { 217 | sum_new = -1; 218 | break; 219 | } 220 | sum_new += std::min(guesses[j] - m_evidence[GLIBC_RAND_STATE_SIZE + j], 221 | m_evidence[GLIBC_RAND_STATE_SIZE + j] - guesses[j]); 222 | } 223 | 224 | m_state[i] -= 1; 225 | if(sum_new < sum) 226 | { 227 | setLSB(i, 1); 228 | } 229 | else if(sum_new > sum) 230 | { 231 | //setLSB(i, 0); 232 | keepGoing = false; 233 | } 234 | else 235 | { 236 | keepGoing = false; 237 | } 238 | } 239 | } 240 | } 241 | 242 | bool GlibcRand::setLSB(uint32_t index, uint32_t value) 243 | { 244 | if(m_LSBMap[index].m_isKnown == false) 245 | { 246 | if(index < GLIBC_RAND_STATE_SIZE) 247 | { 248 | //Set this LSB's value 249 | m_state[index] += value; 250 | } 251 | m_LSBMap[index].m_isKnown = true; 252 | m_LSBMap[index].m_LSB = value; 253 | 254 | //Set the opposite value for any LSBs saved as XOR'd with 255 | for(uint32_t i = 0; i < m_LSBMap[index].m_xorWith.size(); i++) 256 | { 257 | setLSB(m_LSBMap[index].m_xorWith[i], 1-value); 258 | } 259 | 260 | //Satisfy OR condition recursively 261 | if(value == 1) 262 | { 263 | for(uint32_t i = 0; i < m_LSBMap[index].m_orWith.size(); i++) 264 | { 265 | setLSB(m_LSBMap[index].m_xorWith[i], 0); 266 | } 267 | } 268 | if(index < GLIBC_RAND_STATE_SIZE) 269 | { 270 | return true; 271 | } 272 | } 273 | return false; 274 | } 275 | 276 | void GlibcRand::setLSBxor(uint32_t index1, uint32_t index2) 277 | { 278 | /* If we don't know either value, then save this relationship */ 279 | if(!m_LSBMap[index1].m_isKnown && !m_LSBMap[index2].m_isKnown) 280 | { 281 | m_LSBMap[index1].m_xorWith.push_back(index2); 282 | m_LSBMap[index2].m_xorWith.push_back(index1); 283 | } 284 | else if(m_LSBMap[index1].m_isKnown) 285 | { 286 | setLSB(index2, 1-m_LSBMap[index1].m_LSB); 287 | } 288 | else if(m_LSBMap[index2].m_isKnown) 289 | { 290 | setLSB(index1, 1-m_LSBMap[index2].m_LSB); 291 | } 292 | } 293 | 294 | void GlibcRand::setLSBor(uint32_t index1, uint32_t index2) 295 | { 296 | if(!m_LSBMap[index1].m_isKnown) 297 | { 298 | m_LSBMap[index1].m_orWith.push_back(index2); 299 | } 300 | 301 | if(!m_LSBMap[index2].m_isKnown) 302 | { 303 | m_LSBMap[index2].m_orWith.push_back(index1); 304 | } 305 | } 306 | 307 | bool GlibcRand::handleRemainder(uint32_t i, std::vector guesses) 308 | { 309 | /* Did we learn any new information? */ 310 | bool ret = false; 311 | 312 | uint32_t guess = guesses[i]; 313 | uint32_t observed = m_evidence[GLIBC_RAND_STATE_SIZE + i]; 314 | uint32_t diff = observed - guess; 315 | 316 | uint32_t diff_first, diff_second; 317 | /* Get Diff for first predecessor */ 318 | if((i+1) >= GLIBC_RAND_STATE_SIZE) 319 | { 320 | diff_first = m_evidence[i+1] - guesses[i-31]; 321 | } 322 | else 323 | { 324 | /* All diffs within the first 32 are "0" */ 325 | diff_first = 0; 326 | } 327 | 328 | /* Get Diff for second predecessor */ 329 | if((i+29) >= GLIBC_RAND_STATE_SIZE) 330 | { 331 | diff_second = m_evidence[GLIBC_RAND_STATE_SIZE + i - 3] - guesses[i-3]; 332 | } 333 | else 334 | { 335 | /* All diffs within the first 32 are "0" */ 336 | diff_second = 0; 337 | } 338 | 339 | 340 | /* When diff is 1, AND both predecessors are 0, (guaranteed to be the case 341 | in the first 1 diff) that means BOTH previous values have a set LSB */ 342 | if((diff == 1) && (diff_first == 0) && (diff_second == 0)) 343 | { 344 | /* First Value. IE: O_1*/ 345 | ret |= setLSB(i+1, 1); 346 | if((i+1) >= GLIBC_RAND_STATE_SIZE) 347 | { 348 | //TODO maybe do the recursion at the end? 349 | handleRemainder(i-31, guesses); 350 | } 351 | 352 | /* Second Value. IE: O_31*/ 353 | ret |= setLSB(i+29, 1); 354 | if((i+29) < GLIBC_RAND_STATE_SIZE) 355 | { 356 | //TODO maybe do the recursion at the end? 357 | handleRemainder(i-3, guesses); 358 | } 359 | } 360 | 361 | /* If diff of zero, and LSB of 1, then the two predecessors MUST have 362 | an XOR relationship */ 363 | if((diff == 0) && (m_LSBMap[i].m_isKnown) && (m_LSBMap[i].m_LSB = 1)) 364 | { 365 | setLSBxor(i-3, i-31); 366 | } 367 | 368 | return ret; 369 | } 370 | 371 | /* Keep hopping by 3's, checking for diff increments */ 372 | void GlibcRand::tune_chainChecking() 373 | { 374 | bool keepGoing = true; 375 | while(keepGoing) 376 | { 377 | keepGoing = false; 378 | std::vector guesses = this->predictForward(m_evidence.size() - GLIBC_RAND_STATE_SIZE); 379 | m_LSBMap.resize(GLIBC_RAND_STATE_SIZE + guesses.size()); 380 | 381 | for(uint32_t i = 0; i < guesses.size()-3; i++) 382 | { 383 | uint32_t diff = m_evidence[GLIBC_RAND_STATE_SIZE + i] - guesses[i]; 384 | uint32_t diff_next = m_evidence[GLIBC_RAND_STATE_SIZE + i + 3] - guesses[i+3]; 385 | 386 | if(diff_next - diff == 1) 387 | { 388 | keepGoing |= setLSB(i+4, 1); 389 | keepGoing |= setLSB(GLIBC_RAND_STATE_SIZE + i, 1); 390 | } 391 | if(diff_next - diff == 0) 392 | { 393 | if((m_LSBMap[i+3].m_isKnown) && (m_LSBMap[i+3].m_LSB = 1)) 394 | { 395 | setLSBxor(i+29, i+1); 396 | } 397 | } 398 | } 399 | } 400 | } 401 | 402 | //XXX Maybe not possible?! http://www.mscs.dal.ca/~selinger/random/ 403 | /* Takes a pointer for efficiency (don't want to copy the state over and over) */ 404 | bool GlibcRand::isInitState(std::deque *tmp_state) 405 | { 406 | return false; 407 | } 408 | 409 | bool GlibcRand::reverseToSeed(int64_t *outSeed, uint32_t depth) 410 | { 411 | /* Keep state in a deque for this, as we're going to need to go backwards a lot 412 | This is for efficiency only. As we might have to go very deeply backwards, 413 | this part has to be fast */ 414 | std::deque tmp_state; 415 | tmp_state.resize(GLIBC_RAND_STATE_SIZE); 416 | for(uint32_t i = 0; i < GLIBC_RAND_STATE_SIZE; i++) 417 | { 418 | tmp_state[i] = m_state[i]; 419 | } 420 | 421 | for(uint32_t i = 0; i < depth; i++) 422 | { 423 | //o_-1 = o_30 - 0_28 424 | uint32_t prev = tmp_state[30] - tmp_state[27]; 425 | tmp_state.pop_back(); 426 | tmp_state.push_front(prev); 427 | 428 | if(isInitState(&tmp_state)) 429 | { 430 | *outSeed = tmp_state[0]; 431 | return true; 432 | } 433 | } 434 | return false; 435 | } 436 | 437 | /* In glibc-rand, the rand() function chops off the LSB of the computed value. 438 | This makes reversing it annoying, but not impossible. */ 439 | void GlibcRand::tune(std::vector evidenceForward, std::vector evidenceBackward) 440 | { 441 | tune_chainChecking(); 442 | tune_repeatedIncrements(); 443 | } 444 | 445 | void GlibcRand::setBounds(uint32_t min, uint32_t max) 446 | { 447 | //Setting bounds is unsupported in gblibc, so do nothing here. In fact, this should not get called. 448 | } 449 | 450 | int64_t GlibcRand::getMinSeed() 451 | { 452 | return 0; 453 | } 454 | 455 | int64_t GlibcRand::getMaxSeed() 456 | { 457 | return UINT_MAX; 458 | } 459 | -------------------------------------------------------------------------------- /prngs/PHP5_rand.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This program is free software: you can redistribute it and/or modify 3 | it under the terms of the GNU General Public License as published by 4 | the Free Software Foundation, either version 3 of the License, or 5 | (at your option) any later version. 6 | 7 | This program is distributed in the hope that it will be useful, 8 | but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | GNU General Public License for more details. 11 | 12 | You should have received a copy of the GNU General Public License 13 | along with this program. If not, see . 14 | 15 | Heavily based off GlibcRand.cpp (Copyright Bishop Fox 2014) 16 | 17 | */ 18 | 19 | #include "PHP5_rand.h" 20 | #include "../ConsoleColors.h" 21 | #include 22 | 23 | PHP5_rand::PHP5_rand() 24 | { 25 | seedValue = 0; 26 | 27 | m_LSBMap.resize(PHP5_RAND_STATE_SIZE); 28 | } 29 | 30 | PHP5_rand::~PHP5_rand() {} 31 | 32 | const std::string PHP5_rand::getName() 33 | { 34 | return PHP5_RAND; 35 | } 36 | 37 | void PHP5_rand::seed(int64_t long_seed) 38 | { 39 | uint32_t seed = (uint32_t)long_seed; 40 | long int i; 41 | int32_t word; 42 | int32_t *dst; 43 | int kc; 44 | 45 | /* We must make sure the seed is not 0. Take arbitrarily 1 in this case. */ 46 | if (seed == 0) 47 | seed = 1; 48 | m_glibcstate[0] = seed; 49 | 50 | dst = m_glibcstate; 51 | word = seed; 52 | kc = 31; 53 | for (i = 1; i < kc; ++i) 54 | { 55 | /* This does: 56 | state[i] = (16807 * state[i - 1]) % 2147483647; 57 | but avoids overflowing 31 bits. */ 58 | long int hi = word / 127773; 59 | long int lo = word % 127773; 60 | word = 16807 * lo - 2836 * hi; 61 | if (word < 0) 62 | word += 2147483647; 63 | *++dst = word; 64 | } 65 | 66 | m_fptr = &m_glibcstate[3]; 67 | m_rptr = &m_glibcstate[0]; 68 | kc *= 10; 69 | while (--kc >= 0) 70 | { 71 | random(); 72 | } 73 | } 74 | 75 | int64_t PHP5_rand::getSeed() 76 | { 77 | return seedValue; 78 | } 79 | 80 | uint32_t PHP5_rand::random() 81 | { 82 | int32_t result; 83 | int32_t *state = m_glibcstate; 84 | 85 | int32_t *fptr = m_fptr; 86 | int32_t *rptr = m_rptr; 87 | int32_t *end_ptr = &m_glibcstate[31]; 88 | int32_t val; 89 | 90 | val = *fptr += *rptr; 91 | /* Chucking least random bit. */ 92 | result = (val >> 1) & 0x7fffffff; 93 | ++fptr; 94 | if (fptr >= end_ptr) 95 | { 96 | fptr = state; 97 | ++rptr; 98 | } 99 | else 100 | { 101 | ++rptr; 102 | if (rptr >= end_ptr) 103 | rptr = state; 104 | } 105 | m_fptr = fptr; 106 | m_rptr = rptr; 107 | 108 | if (m_isBounded) { 109 | /* 110 | ----------------------------------------------------------------------------------------- 111 | Adapted from PHP code located at: 112 | https://github.com/php/php-src/blob/PHP-5.6.27/ext/standard/rand.c 113 | https://github.com/php/php-src/blob/PHP-5.6.27/ext/standard/php_rand.h 114 | 115 | Above PHP code licensed under version 3.01 of the PHP license (http://www.php.net/license/3_01.txt) 116 | ----------------------------------------------------------------------------------------- 117 | 118 | int rand([int min, int max]) uses RAND_RANGE(): 119 | https://github.com/php/php-src/blob/PHP-5.6.27/ext/standard/rand.c#L289 120 | ... 121 | if (argc == 2) { 122 | RAND_RANGE(number, min, max, PHP_RAND_MAX); 123 | } 124 | ... 125 | 126 | RAND_RANGE defined here: 127 | https://github.com/php/php-src/blob/PHP-5.6.27/ext/standard/php_rand.h#L44 128 | ... 129 | #define RAND_RANGE(__n, __min, __max, __tmax) \ 130 | (__n) = (__min) + (long) ((double) ( (double) (__max) - (__min) + 1.0) * ((__n) / ((__tmax) + 1.0))) 131 | ... 132 | 133 | */ 134 | result = (uint32_t)((m_minBound) + (long) ((double) ( (double) (m_maxBound) - (m_minBound) + 1.0) * ((result) / ((2147483647) + 1.0)))); 135 | } 136 | 137 | return result; 138 | } 139 | 140 | uint32_t PHP5_rand::getStateSize(void) 141 | { 142 | return PHP5_RAND_STATE_SIZE; 143 | } 144 | 145 | void PHP5_rand::setState(std::vector inState) 146 | { 147 | m_state = inState; 148 | m_state.resize(PHP5_RAND_STATE_SIZE, 0); 149 | 150 | /* Shift left one bit to return to mod 2^32. 151 | Of course, we'll be missing the original LSB, 152 | so we'll have to go fishing for it later. */ 153 | for(uint32_t i = 0; i < m_state.size(); i++) 154 | { 155 | m_state[i] = m_state[i]<<1; 156 | } 157 | } 158 | 159 | std::vector PHP5_rand::getState(void) 160 | { 161 | return m_state; 162 | } 163 | 164 | void PHP5_rand::setEvidence(std::vector evidence) 165 | { 166 | m_evidence = evidence; 167 | } 168 | 169 | std::vector PHP5_rand::predictForward(uint32_t length) 170 | { 171 | std::vector running_state = m_state; 172 | running_state.resize(PHP5_RAND_STATE_SIZE + length); 173 | 174 | std::vector ret; 175 | 176 | /* There is a more memory efficient way to do this. With a 177 | linked list for the state. But meh. */ 178 | for(uint32_t i = 32; i < length + 32; i++) 179 | { 180 | uint32_t val = running_state[i-31] + running_state[i-3]; 181 | running_state[i] = val; 182 | ret.push_back((val >> 1) & 0x7fffffff); 183 | } 184 | 185 | return ret; 186 | } 187 | 188 | std::vector PHP5_rand::predictBackward(uint32_t length) 189 | { 190 | std::vector running_state = m_state; 191 | /* Reverse order for simplicity. Deal with it. */ 192 | std::reverse(running_state.begin(), running_state.end()); 193 | running_state.resize(PHP5_RAND_STATE_SIZE + length); 194 | 195 | std::vector ret; 196 | 197 | /* There is a more memory efficient way to do this. With a 198 | linked list for the state. But meh. */ 199 | for(uint32_t i = PHP5_RAND_STATE_SIZE; i < length + PHP5_RAND_STATE_SIZE; i++) 200 | { 201 | uint32_t val = running_state[i-31] - running_state[i-28]; 202 | running_state[i] = val; 203 | ret.push_back((val >> 1) & 0x7fffffff); 204 | } 205 | 206 | /* Reverse order for simplicity. Deal with it. */ 207 | std::reverse(ret.begin(), ret.end()); 208 | return ret; 209 | } 210 | 211 | /* We just have to make some guesses about the LSBs and then test those 212 | guesses one by one */ 213 | void PHP5_rand::tune_repeatedIncrements() 214 | { 215 | /* Keep tuning until no improvements are made anymore */ 216 | bool keepGoing = true; 217 | while(keepGoing) 218 | { 219 | keepGoing = true; 220 | 221 | /* Foreach state integer, test if we can improve predictions by incrementing 222 | that state value.*/ 223 | for(uint32_t i = 0; i < PHP5_RAND_STATE_SIZE; i++) 224 | { 225 | /* Get the success rate of this state */ 226 | std::vector guesses = this->predictForward(m_evidence.size() - PHP5_RAND_STATE_SIZE); 227 | 228 | int64_t sum = 0; 229 | for(uint32_t j = 0; j < guesses.size(); j++) 230 | { 231 | sum += std::min(guesses[j] - m_evidence[PHP5_RAND_STATE_SIZE + j], 232 | m_evidence[PHP5_RAND_STATE_SIZE + j] - guesses[j]); 233 | } 234 | 235 | //Increment the state val 236 | m_state[i] += 1; 237 | 238 | /* Get the success rate of the new state */ 239 | guesses = this->predictForward(m_evidence.size() - PHP5_RAND_STATE_SIZE); 240 | 241 | int64_t sum_new = 0; 242 | for(uint32_t j = 0; j < guesses.size(); j++) 243 | { 244 | /* The guess can NEVER be bigger than the evidence */ 245 | if(guesses[j] > m_evidence[PHP5_RAND_STATE_SIZE + j]) 246 | { 247 | sum_new = -1; 248 | break; 249 | } 250 | sum_new += std::min(guesses[j] - m_evidence[PHP5_RAND_STATE_SIZE + j], 251 | m_evidence[PHP5_RAND_STATE_SIZE + j] - guesses[j]); 252 | } 253 | 254 | m_state[i] -= 1; 255 | if(sum_new < sum) 256 | { 257 | setLSB(i, 1); 258 | } 259 | else if(sum_new > sum) 260 | { 261 | //setLSB(i, 0); 262 | keepGoing = false; 263 | } 264 | else 265 | { 266 | keepGoing = false; 267 | } 268 | } 269 | } 270 | } 271 | 272 | bool PHP5_rand::setLSB(uint32_t index, uint32_t value) 273 | { 274 | if(m_LSBMap[index].m_isKnown == false) 275 | { 276 | if(index < PHP5_RAND_STATE_SIZE) 277 | { 278 | //Set this LSB's value 279 | m_state[index] += value; 280 | } 281 | m_LSBMap[index].m_isKnown = true; 282 | m_LSBMap[index].m_LSB = value; 283 | 284 | //Set the opposite value for any LSBs saved as XOR'd with 285 | for(uint32_t i = 0; i < m_LSBMap[index].m_xorWith.size(); i++) 286 | { 287 | setLSB(m_LSBMap[index].m_xorWith[i], 1-value); 288 | } 289 | 290 | //Satisfy OR condition recursively 291 | if(value == 1) 292 | { 293 | for(uint32_t i = 0; i < m_LSBMap[index].m_orWith.size(); i++) 294 | { 295 | setLSB(m_LSBMap[index].m_xorWith[i], 0); 296 | } 297 | } 298 | if(index < PHP5_RAND_STATE_SIZE) 299 | { 300 | return true; 301 | } 302 | } 303 | return false; 304 | } 305 | 306 | void PHP5_rand::setLSBxor(uint32_t index1, uint32_t index2) 307 | { 308 | /* If we don't know either value, then save this relationship */ 309 | if(!m_LSBMap[index1].m_isKnown && !m_LSBMap[index2].m_isKnown) 310 | { 311 | m_LSBMap[index1].m_xorWith.push_back(index2); 312 | m_LSBMap[index2].m_xorWith.push_back(index1); 313 | } 314 | else if(m_LSBMap[index1].m_isKnown) 315 | { 316 | setLSB(index2, 1-m_LSBMap[index1].m_LSB); 317 | } 318 | else if(m_LSBMap[index2].m_isKnown) 319 | { 320 | setLSB(index1, 1-m_LSBMap[index2].m_LSB); 321 | } 322 | } 323 | 324 | void PHP5_rand::setLSBor(uint32_t index1, uint32_t index2) 325 | { 326 | if(!m_LSBMap[index1].m_isKnown) 327 | { 328 | m_LSBMap[index1].m_orWith.push_back(index2); 329 | } 330 | 331 | if(!m_LSBMap[index2].m_isKnown) 332 | { 333 | m_LSBMap[index2].m_orWith.push_back(index1); 334 | } 335 | } 336 | 337 | bool PHP5_rand::handleRemainder(uint32_t i, std::vector guesses) 338 | { 339 | /* Did we learn any new information? */ 340 | bool ret = false; 341 | 342 | uint32_t guess = guesses[i]; 343 | uint32_t observed = m_evidence[PHP5_RAND_STATE_SIZE + i]; 344 | uint32_t diff = observed - guess; 345 | 346 | uint32_t diff_first, diff_second; 347 | /* Get Diff for first predecessor */ 348 | if((i+1) >= PHP5_RAND_STATE_SIZE) 349 | { 350 | diff_first = m_evidence[i+1] - guesses[i-31]; 351 | } 352 | else 353 | { 354 | /* All diffs within the first 32 are "0" */ 355 | diff_first = 0; 356 | } 357 | 358 | /* Get Diff for second predecessor */ 359 | if((i+29) >= PHP5_RAND_STATE_SIZE) 360 | { 361 | diff_second = m_evidence[PHP5_RAND_STATE_SIZE + i - 3] - guesses[i-3]; 362 | } 363 | else 364 | { 365 | /* All diffs within the first 32 are "0" */ 366 | diff_second = 0; 367 | } 368 | 369 | 370 | /* When diff is 1, AND both predecessors are 0, (guaranteed to be the case 371 | in the first 1 diff) that means BOTH previous values have a set LSB */ 372 | if((diff == 1) && (diff_first == 0) && (diff_second == 0)) 373 | { 374 | /* First Value. IE: O_1*/ 375 | ret |= setLSB(i+1, 1); 376 | if((i+1) >= PHP5_RAND_STATE_SIZE) 377 | { 378 | //TODO maybe do the recursion at the end? 379 | handleRemainder(i-31, guesses); 380 | } 381 | 382 | /* Second Value. IE: O_31*/ 383 | ret |= setLSB(i+29, 1); 384 | if((i+29) < PHP5_RAND_STATE_SIZE) 385 | { 386 | //TODO maybe do the recursion at the end? 387 | handleRemainder(i-3, guesses); 388 | } 389 | } 390 | 391 | /* If diff of zero, and LSB of 1, then the two predecessors MUST have 392 | an XOR relationship */ 393 | if((diff == 0) && (m_LSBMap[i].m_isKnown) && (m_LSBMap[i].m_LSB = 1)) 394 | { 395 | setLSBxor(i-3, i-31); 396 | } 397 | 398 | return ret; 399 | } 400 | 401 | /* Keep hopping by 3's, checking for diff increments */ 402 | void PHP5_rand::tune_chainChecking() 403 | { 404 | bool keepGoing = true; 405 | while(keepGoing) 406 | { 407 | keepGoing = false; 408 | std::vector guesses = this->predictForward(m_evidence.size() - PHP5_RAND_STATE_SIZE); 409 | m_LSBMap.resize(PHP5_RAND_STATE_SIZE + guesses.size()); 410 | 411 | for(uint32_t i = 0; i < guesses.size()-3; i++) 412 | { 413 | uint32_t diff = m_evidence[PHP5_RAND_STATE_SIZE + i] - guesses[i]; 414 | uint32_t diff_next = m_evidence[PHP5_RAND_STATE_SIZE + i + 3] - guesses[i+3]; 415 | 416 | if(diff_next - diff == 1) 417 | { 418 | keepGoing |= setLSB(i+4, 1); 419 | keepGoing |= setLSB(PHP5_RAND_STATE_SIZE + i, 1); 420 | } 421 | if(diff_next - diff == 0) 422 | { 423 | if((m_LSBMap[i+3].m_isKnown) && (m_LSBMap[i+3].m_LSB = 1)) 424 | { 425 | setLSBxor(i+29, i+1); 426 | } 427 | } 428 | } 429 | } 430 | } 431 | 432 | //XXX Maybe not possible?! http://www.mscs.dal.ca/~selinger/random/ 433 | /* Takes a pointer for efficiency (don't want to copy the state over and over) */ 434 | bool PHP5_rand::isInitState(std::deque *tmp_state) 435 | { 436 | return false; 437 | } 438 | 439 | bool PHP5_rand::reverseToSeed(int64_t *outSeed, uint32_t depth) 440 | { 441 | /* Keep state in a deque for this, as we're going to need to go backwards a lot 442 | This is for efficiency only. As we might have to go very deeply backwards, 443 | this part has to be fast */ 444 | std::deque tmp_state; 445 | tmp_state.resize(PHP5_RAND_STATE_SIZE); 446 | for(uint32_t i = 0; i < PHP5_RAND_STATE_SIZE; i++) 447 | { 448 | tmp_state[i] = m_state[i]; 449 | } 450 | 451 | for(uint32_t i = 0; i < depth; i++) 452 | { 453 | //o_-1 = o_30 - 0_28 454 | uint32_t prev = tmp_state[30] - tmp_state[27]; 455 | tmp_state.pop_back(); 456 | tmp_state.push_front(prev); 457 | 458 | if(isInitState(&tmp_state)) 459 | { 460 | *outSeed = tmp_state[0]; 461 | return true; 462 | } 463 | } 464 | return false; 465 | } 466 | 467 | /* In glibc-rand, the rand() function chops off the LSB of the computed value. 468 | This makes reversing it annoying, but not impossible. */ 469 | void PHP5_rand::tune(std::vector evidenceForward, std::vector evidenceBackward) 470 | { 471 | tune_chainChecking(); 472 | tune_repeatedIncrements(); 473 | } 474 | 475 | void PHP5_rand::setBounds(uint32_t min, uint32_t max) 476 | { 477 | m_minBound = min; 478 | m_maxBound = max; 479 | m_isBounded = true; 480 | } 481 | 482 | int64_t PHP5_rand::getMinSeed() 483 | { 484 | return 0; 485 | } 486 | 487 | int64_t PHP5_rand::getMaxSeed() 488 | { 489 | return UINT_MAX; 490 | } 491 | -------------------------------------------------------------------------------- /Untwister.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include "Untwister.h" 19 | #include 20 | #include 21 | 22 | Untwister::Untwister() 23 | { 24 | m_isCompleted = new std::atomic(false); 25 | m_isRunning = new std::atomic(false); 26 | m_isStarting = new std::atomic(false); 27 | m_isBounded = new std::atomic(false); 28 | m_observedOutputs = new std::vector; 29 | m_depth = DEFAULT_DEPTH; 30 | m_minConfidence = DEFAULT_MIN_CONFIDENCE; 31 | m_threads = std::thread::hardware_concurrency(); 32 | m_prng = "glibc-rand"; 33 | m_answers = new std::vector* >(m_threads); 34 | m_status = new std::vector(m_threads); 35 | } 36 | 37 | Untwister::Untwister(unsigned int observationSize) 38 | { 39 | m_isCompleted = new std::atomic(false); 40 | m_isRunning = new std::atomic(false); 41 | m_isStarting = new std::atomic(false); 42 | m_isBounded = new std::atomic(false); 43 | m_observedOutputs = new std::vector(observationSize); 44 | m_depth = DEFAULT_DEPTH; 45 | m_minConfidence = DEFAULT_MIN_CONFIDENCE; 46 | m_threads = std::thread::hardware_concurrency(); 47 | m_prng = "glibc-rand"; 48 | m_answers = new std::vector* >(m_threads); 49 | m_status = new std::vector(m_threads); 50 | } 51 | 52 | Untwister::~Untwister() 53 | { 54 | delete m_isCompleted; 55 | delete m_isRunning; 56 | delete m_observedOutputs; 57 | delete m_answers; 58 | delete m_status; 59 | delete m_isStarting; 60 | delete m_isBounded; 61 | } 62 | 63 | /* 64 | isStarting: The call to bruteforce() has occurred but all workers threads have not started yet 65 | isRunning: All threads have started and it is safe to call getStatus() externally 66 | isCompleted: The operation has completed and all worker threads have joined 67 | */ 68 | std::vector Untwister::bruteforce(int64_t lowerBoundSeed, int64_t upperBoundSeed) 69 | { 70 | if (m_isRunning->load(std::memory_order_relaxed) || m_isStarting->exchange(true)) 71 | { 72 | throw std::runtime_error("Bruteforce is already in progress"); 73 | } 74 | 75 | if (m_isCompleted->load(std::memory_order_relaxed)) 76 | { 77 | m_isCompleted->store(false, std::memory_order_relaxed); 78 | } 79 | 80 | std::vector labor = m_divisionOfLabor(upperBoundSeed - lowerBoundSeed); 81 | int64_t startAt = lowerBoundSeed; 82 | std::vector pool = std::vector(m_threads); 83 | 84 | for (unsigned int id = 0; id < m_threads; ++id) 85 | { 86 | int64_t endAt = startAt + labor.at(id); 87 | pool[id] = std::thread(&Untwister::m_worker, this, id, startAt, endAt); 88 | startAt += labor.at(id); 89 | } 90 | 91 | m_isRunning->store(true, std::memory_order_relaxed); 92 | m_isStarting->store(false, std::memory_order_relaxed); 93 | 94 | for (unsigned int id = 0; id < pool.size(); ++id) 95 | { 96 | pool[id].join(); 97 | } 98 | 99 | if (!m_isCompleted->load(std::memory_order_relaxed)) 100 | { 101 | m_isCompleted->store(true, std::memory_order_relaxed); 102 | } 103 | 104 | std::vector results = std::vector(); 105 | for (unsigned int id = 0; id < m_answers->size(); ++id) 106 | { 107 | for (unsigned int index = 0; index < m_answers->at(id)->size(); ++index) 108 | { 109 | results.push_back(m_answers->at(id)->at(index)); 110 | } 111 | delete m_answers->at(id); 112 | } 113 | m_isRunning->store(false, std::memory_order_relaxed); 114 | return results; 115 | } 116 | 117 | /* This method is executed as a separate thread */ 118 | void Untwister::m_worker(unsigned int id, uint32_t startingSeed, uint32_t endingSeed) 119 | { 120 | 121 | /* Each thread must have a local factory unless you like mutexes and/or segfaults */ 122 | PRNGFactory factory; 123 | PRNG *generator = factory.getInstance(m_prng); 124 | if(isBounded()) 125 | { 126 | generator->setBounds(m_minBound, m_maxBound); 127 | } 128 | m_answers->at(id) = new std::vector(); 129 | m_status->at(id) = 0; 130 | 131 | for(uint32_t seedIndex = startingSeed; seedIndex <= endingSeed; ++seedIndex) 132 | { 133 | 134 | if(m_isCompleted->load(std::memory_order_relaxed)) 135 | { 136 | break; // Some other thread found the seed 137 | } 138 | 139 | generator->seed(seedIndex); 140 | uint32_t matchesFound = 0; 141 | for(uint32_t index = 0; index < m_depth; index++) 142 | { 143 | uint32_t nextRand = generator->random(); 144 | uint32_t observed = m_observedOutputs->at(matchesFound); 145 | 146 | if(observed == nextRand) 147 | { 148 | matchesFound++; 149 | if(matchesFound == m_observedOutputs->size()) 150 | { 151 | break; // This seed is a winner if we get to the end 152 | } 153 | } 154 | } 155 | 156 | m_status->at(id) = seedIndex - startingSeed; 157 | double confidence = ((double) matchesFound / (double) m_observedOutputs->size()) * 100.0; 158 | if(m_minConfidence <= confidence) 159 | { 160 | Seed seed = Seed(seedIndex, confidence); 161 | m_answers->at(id)->push_back(seed); 162 | } 163 | 164 | if(matchesFound == m_observedOutputs->size()) 165 | { 166 | m_isCompleted->store(true, std::memory_order_relaxed); 167 | } 168 | } 169 | delete generator; 170 | } 171 | 172 | bool Untwister::canInferState() 173 | { 174 | return getStateSize() <= m_observedOutputs->size() ? true:false; 175 | } 176 | 177 | /* 178 | This is the "smarter" method of breaking RNGs. We use consecutive integers 179 | to infer information about the internal state of the RNG. Using this 180 | method, however, we won't typically recover an actual seed value. 181 | But the effect is the same. 182 | */ 183 | State Untwister::inferState() 184 | { 185 | if (!canInferState()) 186 | { 187 | throw std::runtime_error("Invalid state size, cannot infer state"); 188 | } 189 | 190 | PRNGFactory factory; 191 | PRNG *generator = factory.getInstance(m_prng); 192 | uint32_t stateSize = generator->getStateSize(); 193 | 194 | double highscore = 0.0; 195 | 196 | /* Guaranteed from the above to loop at least one time */ 197 | std::vector scores; 198 | std::vector best_state; 199 | 200 | for(uint32_t index = 0; index < (m_observedOutputs->size() - stateSize); ++index) 201 | { 202 | std::vector::const_iterator first = m_observedOutputs->begin() + index; 203 | std::vector::const_iterator last = m_observedOutputs->begin() + index + stateSize; 204 | std::vector state(first, last); 205 | 206 | /* Make predictions based on the state */ 207 | std::vector evidenceForward 208 | ((std::vector::const_iterator)m_observedOutputs->begin(), first); 209 | std::vector evidenceBackward 210 | (last+1, (std::vector::const_iterator)m_observedOutputs->end()); 211 | generator->setState(state); 212 | 213 | /* Provide additional evidence for tuning on PRNGs that require it */ 214 | generator->setEvidence((*m_observedOutputs)); 215 | generator->tune(evidenceForward, evidenceBackward); 216 | 217 | std::vector predictions_forward = 218 | generator->predictForward(((m_observedOutputs->size() - stateSize) - index)); 219 | 220 | std::vector predictions_backward = generator->predictBackward(index); 221 | 222 | /* Test the prediction against the rest of the observed data */ 223 | /* Forward */ 224 | uint32_t matchesFound = 0; 225 | uint32_t index_pred = 0; 226 | uint32_t index_obs = index + stateSize; 227 | while(index_obs < m_observedOutputs->size() && index_pred < predictions_forward.size()) 228 | { 229 | if(m_observedOutputs->at(index_obs) == predictions_forward[index_pred]) 230 | { 231 | matchesFound++; 232 | index_obs++; 233 | } 234 | index_pred++; 235 | } 236 | 237 | /* Backward */ 238 | index_pred = 0; 239 | index_obs = index; 240 | while(index_obs > 0 && index_pred < predictions_backward.size()) 241 | { 242 | if(m_observedOutputs->at(index_obs) == predictions_backward[index_pred]) 243 | { 244 | matchesFound++; 245 | index_obs--; 246 | } 247 | index_pred++; 248 | } 249 | 250 | /* If we get a perfect guess, then try reversing out the seed, and exit */ 251 | if(matchesFound == (m_observedOutputs->size() - stateSize)) 252 | { 253 | int64_t outSeed = 0; 254 | if(generator->reverseToSeed(&outSeed, 10000)) 255 | { 256 | /* We win! */ 257 | // std::cout << SUCCESS << "Found seed " << outSeed << std::endl; 258 | } 259 | else 260 | { 261 | std::vector state = generator->getState(); 262 | } 263 | } 264 | 265 | double score = (double)(matchesFound*100) / (double)(m_observedOutputs->size() - stateSize); 266 | scores.push_back(score); 267 | if(score > highscore) 268 | { 269 | best_state = generator->getState(); 270 | } 271 | } 272 | 273 | /* TODO: Analyze scores */ 274 | State finalState; 275 | finalState.first = best_state; 276 | finalState.second = highscore; 277 | 278 | delete generator; 279 | return finalState; 280 | } 281 | 282 | void Untwister::generateSampleFromSeed(uint32_t depth, int64_t seed) 283 | { 284 | PRNGFactory factory; 285 | PRNG *generator = factory.getInstance(m_prng); 286 | /* If we're bounded, then apply those bounds now */ 287 | if(isBounded()) 288 | { 289 | generator->setBounds(m_minBound, m_maxBound); 290 | } 291 | generator->seed(seed); 292 | 293 | for (unsigned int index = 0; index < depth; ++index) 294 | { 295 | std::cout << generator->random() << std::endl; 296 | } 297 | delete generator; 298 | } 299 | 300 | /* Divide X work among Y number of threads, and evenly distribute remainders */ 301 | std::vector Untwister::m_divisionOfLabor(uint64_t sizeOfWork) 302 | { 303 | uint64_t work = sizeOfWork / m_threads; 304 | uint64_t leftover = sizeOfWork % m_threads; 305 | std::vector labor(m_threads); 306 | for(uint64_t index = 0; index < m_threads; ++index) 307 | { 308 | if (0 < leftover) 309 | { 310 | labor[index] = work + 1; 311 | --leftover; 312 | } 313 | else 314 | { 315 | labor[index] = work; 316 | } 317 | } 318 | return labor; 319 | } 320 | 321 | void Untwister::addObservedOutput(uint32_t observedOutput) 322 | { 323 | m_observedOutputs->push_back(observedOutput); 324 | } 325 | 326 | std::vector* Untwister::getObservedOutputs() 327 | { 328 | return m_observedOutputs; 329 | } 330 | 331 | std::vector* Untwister::getStatus() 332 | { 333 | if (m_isRunning->load(std::memory_order_relaxed)) 334 | { 335 | return m_status; 336 | } 337 | return NULL; 338 | } 339 | 340 | std::vector Untwister::getSupportedPRNGs() 341 | { 342 | PRNGFactory factory; 343 | return factory.getNames(); 344 | } 345 | 346 | 347 | void Untwister::setPRNG(std::string prng) 348 | { 349 | if (isSupportedPRNG(prng)) 350 | { 351 | this->m_prng = prng; 352 | } 353 | else 354 | { 355 | throw std::runtime_error("Unsupported PRNG"); 356 | } 357 | } 358 | 359 | void Untwister::setPRNG(char *prng) 360 | { 361 | setPRNG(std::string(prng)); 362 | } 363 | 364 | std::string Untwister::getPRNG() 365 | { 366 | return m_prng; 367 | } 368 | 369 | bool Untwister::isSupportedPRNG(char *prng) 370 | { 371 | return isSupportedPRNG(std::string(prng)); 372 | } 373 | 374 | bool Untwister::isSupportedPRNG(std::string prng) 375 | { 376 | std::vector names = getSupportedPRNGs(); 377 | return std::find(names.begin(), names.end(), prng) == names.end() ? false:true; 378 | } 379 | 380 | uint32_t Untwister::getStateSize() 381 | { 382 | PRNGFactory factory; 383 | PRNG *generator = factory.getInstance(m_prng); 384 | uint32_t stateSize = generator->getStateSize(); 385 | delete generator; 386 | return stateSize; 387 | } 388 | 389 | void Untwister::setThreads(unsigned int threads) 390 | { 391 | if (!m_isRunning->load(std::memory_order_relaxed)) 392 | { 393 | this->m_threads = threads; 394 | delete m_answers; 395 | delete m_status; 396 | m_answers = new std::vector* >(threads); 397 | m_status = new std::vector(threads); 398 | } 399 | } 400 | 401 | unsigned int Untwister::getThreads() 402 | { 403 | return m_threads; 404 | } 405 | 406 | void Untwister::setDepth(unsigned int depth) 407 | { 408 | this->m_depth = depth; 409 | } 410 | 411 | unsigned int Untwister::getDepth() 412 | { 413 | return m_depth; 414 | } 415 | 416 | void Untwister::setMinConfidence(double minConfidence) 417 | { 418 | this->m_minConfidence = minConfidence; 419 | } 420 | 421 | double Untwister::getMinConfidence() 422 | { 423 | return m_minConfidence; 424 | } 425 | 426 | std::atomic* Untwister::getIsCompleted() 427 | { 428 | return m_isCompleted; 429 | } 430 | 431 | std::atomic* Untwister::getIsRunning() 432 | { 433 | return m_isRunning; 434 | } 435 | 436 | std::atomic* Untwister::getIsStarting() 437 | { 438 | return m_isStarting; 439 | } 440 | 441 | void Untwister::setBounds(uint32_t min, uint32_t max) 442 | { 443 | if(m_prng == GLIBC_RAND) 444 | { 445 | std::string err = "Glibc does not have a bounded rand() function. If your application produces "; 446 | err += "bounded random numbers, consider making a Python mangling script. "; 447 | throw err; 448 | } 449 | else if(m_prng == MT19937) 450 | { 451 | std::string err = "C++ does not have a bounded random function. If your application produces "; 452 | err += "bounded random numbers, consider making a Python mangling script. "; 453 | throw err; 454 | } 455 | 456 | m_minBound = min; 457 | m_maxBound = max; 458 | m_isBounded->store(true, std::memory_order_relaxed); 459 | } 460 | 461 | bool Untwister::isBounded() 462 | { 463 | return m_isBounded->load(std::memory_order_relaxed); 464 | } 465 | 466 | /* Gets the min possible seed, for the given PRNG type */ 467 | int64_t Untwister::getMinSeed() 468 | { 469 | PRNGFactory factory; 470 | PRNG *generator = factory.getInstance(m_prng); 471 | int64_t val = generator->getMinSeed(); 472 | delete generator; 473 | return val; 474 | } 475 | 476 | /* Gets the max possible seed, for the given PRNG type */ 477 | int64_t Untwister::getMaxSeed() 478 | { 479 | PRNGFactory factory; 480 | PRNG *generator = factory.getInstance(m_prng); 481 | int64_t val = generator->getMaxSeed(); 482 | delete generator; 483 | return val; 484 | } 485 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright Bishop Fox, 2014 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | This program is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with this program. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | #include "ConsoleColors.h" 28 | #include "Untwister.h" 29 | 30 | using std::chrono::seconds; 31 | using std::chrono::milliseconds; 32 | using std::chrono::duration; 33 | using std::chrono::duration_cast; 34 | using std::chrono::steady_clock; 35 | 36 | static const unsigned int ONE_YEAR = 31536000; 37 | 38 | 39 | void Usage(Untwister *untwister) 40 | { 41 | std::cout << BOLD << "Untwister" << RESET << " - Recover PRNG seeds from observed values." << std::endl; 42 | std::cout << "\t-i [-d ] [-r ] [-g ] [-t ] [-c ]\n" << std::endl; 43 | std::cout << "\t-i \n\t\tPath to file input file containing observed results of your RNG. The contents" << std::endl; 44 | std::cout << "\t\tare expected to be newline separated 32-bit integers. See test_input.txt for" << std::endl; 45 | std::cout << "\t\tan example." << std::endl; 46 | std::cout << "\t-d \n\t\tThe depth (default 1000) to inspect for each seed value when brute forcing." << std::endl; 47 | std::cout << "\t\tChoosing a higher depth value will make brute forcing take longer (linearly), but is" << std::endl; 48 | std::cout << "\t\trequired for cases where the generator has been used many times already." << std::endl; 49 | std::cout << "\t-r \n\t\tThe PRNG algorithm to use. Supported PRNG algorithms:" << std::endl; 50 | std::vector names = untwister->getSupportedPRNGs(); 51 | for (unsigned int index = 0; index < names.size(); ++index) 52 | { 53 | std::cout << "\t\t" << BOLD << " * " << RESET << names[index]; 54 | if (names[index] == "glibc-rand"){ 55 | std::cout << " (default)"; 56 | } 57 | std::cout << std::endl; 58 | } 59 | std::cout << "\t-u\n\t\tUse bruteforce, but only for unix timestamp values within a range of +/- 1 " << std::endl; 60 | std::cout << "\t\tyear from the current time." << std::endl; 61 | std::cout << "\t-b\n\t\tAlways bruteforce, even if state inference attack is successful" << std::endl; 62 | std::cout << "\t-g \n\t\tGenerate a test set of random numbers from the given seed" << std::endl; 63 | std::cout << "\t-D \n\t\tThe quantity of random numbers to generate when using the -g flag (default 20)" << std::endl; 64 | std::cout << "\t-c \n\t\tSet the minimum confidence percentage to report" << std::endl; 65 | std::cout << "\t-t \n\t\tSpawn this many threads (default is " << untwister->getThreads() << ")" << std::endl; 66 | std::cout << "\t-m \n\t\tSet the minimum bound (inclusive), for a bounded PRNG function" << std::endl; 67 | std::cout << "\t-M \n\t\tSet the maximum bound (inclusive), for a bounded PRNG function" << std::endl; 68 | std::cout << "\t-s \n\t\tSet the minimum seed (inclusive), for brute forcing (a 64 bit signed integer)" << std::endl; 69 | std::cout << "\t-S \n\t\tSet the maxmimum seed (inclusive), for brute forcing (a 64 bit signed integer)" << std::endl; 70 | std::cout << std::endl; 71 | } 72 | 73 | void DisplayProgress(Untwister *untwister, uint64_t totalWork) 74 | { 75 | std::atomic* isStarting = untwister->getIsStarting(); 76 | while (isStarting->load(std::memory_order_relaxed)) 77 | { 78 | std::this_thread::sleep_for(milliseconds(10)); 79 | } 80 | 81 | std::cout.precision(2); 82 | double percent = 0.0; 83 | double seedsPerSec = 0.0; 84 | uint32_t timeLeft = 0.0; 85 | int secondsLeft = 0; 86 | int minutesLeft = 0; 87 | int hoursLeft = 0; 88 | int daysLeft = 0; 89 | int yearsLeft = 0; 90 | steady_clock::time_point started = steady_clock::now(); 91 | std::vector *status = untwister->getStatus(); 92 | if(status == NULL) 93 | { 94 | /* If the status is NULL, we must be in a finished state, since we can't be starting (we already checked that)*/ 95 | /* and we can't be running. So, just clean up and quit if we get this.*/ 96 | return; 97 | } 98 | std::atomic *isCompleted = untwister->getIsCompleted(); 99 | char spinner[] = {'|', '/', '-', '\\'}; 100 | unsigned int count = 0; 101 | while (!isCompleted->load(std::memory_order_relaxed)) 102 | { 103 | unsigned int sum = 0; 104 | duration time_span = duration_cast>(steady_clock::now() - started); 105 | for (unsigned int index = 0; index < status->size(); ++index) 106 | { 107 | sum += status->at(index); 108 | } 109 | percent = ((double) sum / (double) totalWork) * 100.0; 110 | if (0 < time_span.count()) 111 | { 112 | seedsPerSec = (double) sum / (double) time_span.count(); 113 | if (0 == count % 20) 114 | { 115 | timeLeft = ((totalWork - sum) / seedsPerSec); 116 | secondsLeft = timeLeft % 60; 117 | minutesLeft = (timeLeft / 60) % 60; 118 | hoursLeft = (timeLeft / 3600) % 24; 119 | daysLeft = (timeLeft / 86400) % 365; 120 | yearsLeft = (timeLeft / ONE_YEAR); 121 | } 122 | } 123 | 124 | std::cout << CLEAR << BOLD << PURPLE << "[" << spinner[count % 4] << "]" << RESET 125 | << " Progress: " << std::fixed<< percent << '%' 126 | << " [" << sum << " / " << totalWork << "]" 127 | << " ~" << seedsPerSec << "/sec "; 128 | if(yearsLeft > 0) 129 | { 130 | std::cout << " " << yearsLeft << " years"; 131 | } 132 | if(daysLeft > 0) 133 | { 134 | std::cout << " " << daysLeft << " days"; 135 | } 136 | if(hoursLeft > 0) 137 | { 138 | std::cout << " " << hoursLeft << " hours"; 139 | } 140 | if(minutesLeft > 0) 141 | { 142 | std::cout << " " << minutesLeft << " minutes"; 143 | } 144 | std::cout << " " << secondsLeft << " seconds"; 145 | std::cout.flush(); 146 | ++count; 147 | std::this_thread::sleep_for(milliseconds(100)); 148 | } 149 | std::cout << CLEAR; 150 | } 151 | 152 | bool inferenceAttack(Untwister *untwister) 153 | { 154 | if (untwister->canInferState()) 155 | { 156 | std::cout << INFO << "Attempting state inference attack" << std::endl; 157 | auto state = untwister->inferState(); 158 | if (0 < state.second) 159 | { 160 | std::cout << "Recovered state: " << std::endl; 161 | for (uint32_t index = 0; index < state.first.size(); ++index) 162 | { 163 | std::cout << '\t' << state.first[index] << std::endl; 164 | } 165 | std::cout << SUCCESS << "Confidence: " << state.second << std::endl; 166 | } 167 | return 0 < state.second ? true:false; 168 | } 169 | else 170 | { 171 | std::cout << WARN << "Not enough observed values to perform state inference, " 172 | << "try again with more than " << untwister->getStateSize() << " values." << std::endl; 173 | return false; 174 | } 175 | } 176 | 177 | void bruteforceAttack(Untwister *untwister, int64_t lowerBoundSeed, int64_t upperBoundSeed) 178 | { 179 | std::cout << INFO << "Looking for seed using " << BOLD << untwister->getPRNG() << RESET << std::endl; 180 | std::cout << INFO << "Spawning " << untwister->getThreads() << " worker thread(s) ..." << std::endl; 181 | 182 | steady_clock::time_point elapsed = steady_clock::now(); 183 | std::thread progressThread(DisplayProgress, untwister, upperBoundSeed - lowerBoundSeed); 184 | 185 | auto results = untwister->bruteforce(lowerBoundSeed, upperBoundSeed); 186 | 187 | progressThread.join(); 188 | 189 | /* Total time elapsed */ 190 | std::cout << INFO << "Completed in " 191 | << duration_cast(steady_clock::now() - elapsed).count() 192 | << " second(s)" << std::endl; 193 | 194 | /* Display results */ 195 | for (unsigned int index = 0; index < results.size(); ++index) 196 | { 197 | std::cout << SUCCESS << "Found seed " << results[index].first 198 | << " with a confidence of " << results[index].second 199 | << '%' << std::endl; 200 | } 201 | } 202 | 203 | int main(int argc, char *argv[]) 204 | { 205 | int c; 206 | 207 | int64_t lowerBoundSeed = 0; 208 | int64_t upperBoundSeed = UINT_MAX; 209 | bool manualSeedMinFlag = false; 210 | bool manualSeedMaxFlag = false; 211 | bool timestampFlag = false; 212 | uint32_t seed = 0; 213 | uint32_t generationDepth = 20; 214 | uint32_t min_bound = 0; 215 | uint32_t max_bound = -1; 216 | bool boundedMinFlag = false; 217 | bool boundedMaxFlag = false; 218 | bool generateFlag = false; 219 | bool bruteforce = false; 220 | Untwister *untwister = new Untwister(); 221 | 222 | while ((c = getopt(argc, argv, "s:S:m:M:D:d:i:g:t:r:c:ubh")) != -1) 223 | { 224 | switch (c) 225 | { 226 | case 's': 227 | { 228 | lowerBoundSeed = strtoll(optarg, NULL, 10); 229 | manualSeedMinFlag = true; 230 | break; 231 | } 232 | case 'S': 233 | { 234 | upperBoundSeed = strtoll(optarg, NULL, 10); 235 | manualSeedMaxFlag = true; 236 | break; 237 | } 238 | case 'm': 239 | { 240 | min_bound = strtoul(optarg, NULL, 10); 241 | boundedMinFlag = true; 242 | break; 243 | } 244 | case 'M': 245 | { 246 | max_bound = strtoul(optarg, NULL, 10); 247 | boundedMaxFlag = true; 248 | break; 249 | } 250 | case 'g': 251 | { 252 | if(optarg != NULL) 253 | { 254 | seed = strtoul(optarg, NULL, 10); 255 | } 256 | generateFlag = true; 257 | break; 258 | } 259 | case 'D': 260 | { 261 | generationDepth = strtoul(optarg, NULL, 10); 262 | break; 263 | } 264 | case 'u': 265 | { 266 | lowerBoundSeed = time(NULL) - ONE_YEAR; 267 | upperBoundSeed = time(NULL) + ONE_YEAR; 268 | timestampFlag = true; 269 | break; 270 | } 271 | case 'b': 272 | { 273 | bruteforce = true; 274 | break; 275 | } 276 | case 'r': 277 | { 278 | if (!untwister->isSupportedPRNG(optarg)) 279 | { 280 | std::cerr << WARN << "ERROR: The PRNG \"" << optarg << "\" is not supported, see -h" << std::endl; 281 | return EXIT_FAILURE; 282 | } 283 | else 284 | { 285 | untwister->setPRNG(optarg); 286 | } 287 | break; 288 | } 289 | case 'd': 290 | { 291 | unsigned int depth = strtoul(optarg, NULL, 10); 292 | if (depth == 0) 293 | { 294 | std::cerr << WARN << "ERROR: Please enter a valid depth > 1" << std::endl; 295 | return EXIT_FAILURE; 296 | } 297 | else 298 | { 299 | std::cout << INFO << "Depth set to: " << depth << std::endl; 300 | untwister->setDepth(depth); 301 | } 302 | break; 303 | } 304 | case 'i': 305 | { 306 | std::ifstream infile(optarg); 307 | if (!infile) 308 | { 309 | std::cerr << WARN << "ERROR: File \"" << optarg << "\" not found" << std::endl; 310 | } 311 | std::string line; 312 | while (std::getline(infile, line)) 313 | { 314 | /* Ignore lines that start with '#' */ 315 | if(line.at(0) =='#') 316 | { 317 | continue; 318 | } 319 | uint32_t value = strtoul(line.c_str(), NULL, 0); 320 | untwister->addObservedOutput(value); 321 | } 322 | break; 323 | } 324 | case 't': 325 | { 326 | unsigned int threads = strtoul(optarg, NULL, 10); 327 | if (threads == 0) 328 | { 329 | std::cerr << WARN << "ERROR: Please enter a valid number of threads > 1" << std::endl; 330 | return EXIT_FAILURE; 331 | } 332 | else 333 | { 334 | untwister->setThreads(threads); 335 | } 336 | break; 337 | } 338 | case 'c': 339 | { 340 | double minimumConfidence = ::atof(optarg); 341 | if (minimumConfidence <= 0 || 100.0 < minimumConfidence) 342 | { 343 | std::cerr << WARN << "ERROR: Invalid confidence percentage " << std::endl; 344 | return EXIT_FAILURE; 345 | } 346 | else 347 | { 348 | std::cout << INFO << "Minimum confidence set to: " << minimumConfidence << std::endl; 349 | untwister->setMinConfidence(minimumConfidence); 350 | } 351 | break; 352 | } 353 | case 'h': 354 | { 355 | Usage(untwister); 356 | delete untwister; 357 | return EXIT_SUCCESS; 358 | } 359 | case '?': 360 | { 361 | if (optopt == 'd') 362 | std::cerr << "Option -" << optopt << " requires an argument." << std::endl; 363 | else if (isprint(optopt)) 364 | std::cerr << "Unknown option `-" << optopt << "'." << std::endl; 365 | else 366 | std::cerr << "Unknown option character `" << optopt << "'." << std::endl; 367 | Usage(untwister); 368 | delete untwister; 369 | return EXIT_FAILURE; 370 | } 371 | default: 372 | { 373 | Usage(untwister); 374 | delete untwister; 375 | return EXIT_FAILURE; 376 | } 377 | } 378 | } 379 | /* You can't just set one bound flag */ 380 | if (boundedMaxFlag ^ boundedMinFlag) 381 | { 382 | Usage(untwister); 383 | std::cerr << WARN << "ERROR: If you want to have a bounded range, provide both -m min and -M max" << std::endl; 384 | delete untwister; 385 | return EXIT_SUCCESS; 386 | } 387 | /* You can't set both -t (for timestamp) and -s or -S */ 388 | if((manualSeedMaxFlag || manualSeedMinFlag) && timestampFlag) 389 | { 390 | Usage(untwister); 391 | std::cerr << WARN << 392 | "ERROR: You can't set both -t (for timestamp based seeding) and manual seeding with -s or -S" << std::endl; 393 | delete untwister; 394 | return EXIT_SUCCESS; 395 | } 396 | /* If it wasn't set manually, set the min seed */ 397 | if(!manualSeedMinFlag) 398 | { 399 | lowerBoundSeed = untwister->getMinSeed(); 400 | } 401 | /* If it wasn't set manually, set the max seed */ 402 | if(!manualSeedMaxFlag) 403 | { 404 | upperBoundSeed = untwister->getMaxSeed(); 405 | } 406 | /* Set the bounds, if there any any */ 407 | if (boundedMaxFlag && boundedMinFlag) 408 | { 409 | if(max_bound <= min_bound) 410 | { 411 | Usage(untwister); 412 | std::cerr << WARN << "ERROR: Min bound (-m) must be less than max bound (-M)" << std::endl; 413 | delete untwister; 414 | return EXIT_SUCCESS; 415 | } 416 | try 417 | { 418 | untwister->setBounds(min_bound, max_bound); 419 | } 420 | catch(const std::string& ex) 421 | { 422 | std::cerr << WARN << "ERROR: " << ex << std::endl; 423 | delete untwister; 424 | return EXIT_SUCCESS; 425 | } 426 | } 427 | /* If we're generating numbers instead of cracking a seed, then let's do that. */ 428 | if (generateFlag) 429 | { 430 | std::vector results; 431 | untwister->generateSampleFromSeed(generationDepth, seed); 432 | delete untwister; 433 | return EXIT_SUCCESS; 434 | } 435 | /* Check input file for contents */ 436 | if (untwister->getObservedOutputs()->empty()) 437 | { 438 | Usage(untwister); 439 | std::cerr << WARN << "ERROR: No input numbers provided. Use -i to provide a file" << std::endl; 440 | delete untwister; 441 | return EXIT_SUCCESS; 442 | } 443 | /* Perform inference attack. Skip it if we're bounded or it was manually skipped */ 444 | if ((boundedMaxFlag && boundedMinFlag) || bruteforce) 445 | { 446 | std::cout << INFO << "Skipping inference attack..." << std::endl; 447 | } 448 | else 449 | { 450 | inferenceAttack(untwister); 451 | } 452 | 453 | /* Give warning about large seed space */ 454 | if((!boundedMaxFlag || !boundedMinFlag) && (untwister->getPRNG() == "java")) 455 | { 456 | std::cout << WARN << "WARNING: Java Random() seeds are 64 bit signed integers. (Though technically they only" << 457 | " use 48 bits of it.) Anyway, trying to brute force through all possible seeds will probably never finish. " << 458 | "Consider using -s or -S to restrict the seed space to something more reasonable. For instance, Java by" << 459 | " default seeds the PRNG with the current system timestamp in milliseconds." << 460 | " IE: System.currentTimeMillis()" << std::endl; 461 | } 462 | 463 | bruteforceAttack(untwister, lowerBoundSeed, upperBoundSeed); 464 | delete untwister; 465 | return EXIT_SUCCESS; 466 | } 467 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------