1 /*
2  * freerainbowtables is a project for generating, distributing, and using
3  * perfect rainbow tables
4  *
5  * Copyright (C) Zhu Shuanglei <shuanglei@hotmail.com>
6  * Copyright Martin Westergaard Jørgensen <martinwj2005@gmail.com>
7  * Copyright 2009, 2010 Daniël Niggebrugge <niggebrugge@fox-it.com>
8  * Copyright 2009, 2010, 2011, 2012 James Nobis <quel@quelrod.net>
9  * Copyright 2011 Logan Watt <logan.watt@gmail.com>
10  * Copyright 2011 Karl Fox <karl@lithik.com>
11  *
12  * This file is part of freerainbowtables.
13  *
14  * freerainbowtables is free software: you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation, version 2 of the License.
17  *
18  * freerainbowtables is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with freerainbowtables.  If not, see <http://www.gnu.org/licenses/>.
25 */
26 
27 #include "Public.h"
28 
29 #ifdef _WIN32
30 	#ifdef BOINC
31 		#include "boinc_win.h"
32 	#endif
33 #else
34 	#include <cstdio>
35 	#include <cctype>
36 	#include <ctime>
37 	#include <cstring>
38 	#include <cstdlib>
39 	#include <csignal>
40 	#include <unistd.h>
41 #endif
42 
43 #include <sys/stat.h>
44 #include <algorithm>
45 #include <iostream>
46 #include <iterator>
47 #include <map>
48 #include <sstream>
49 
50 #ifdef BOINC
51 	#include "filesys.h"
52 	#include "boinc_api.h"
53 #endif
54 
55 #ifdef _WIN32
56 	#include <windows.h>
57 #endif
58 
59 #if defined(_WIN32) && !defined(__GNUC__)
60 	#include <windows.h>
61 	#include <time.h>
62 	#include <io.h>
63 
64 	#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
65 		#define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
66 	#else
67 		#define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL
68 	#endif
69 
70 	struct timezone
71 	{
72 		int tz_minuteswest; /* minutes W of Greenwich */
73 		int tz_dsttime;     /* type of dst correction */
74 	};
75 
gettimeofday(struct timeval * tv,struct timezone * tz)76 	int gettimeofday(struct timeval *tv, struct timezone *tz)
77 	{
78 		// Define a structure to receive the current Windows filetime
79 		FILETIME ft;
80 
81 		// Initialize the present time to 0 and the timezone to UTC
82   		unsigned __int64 tmpres = 0;
83 		static int tzflag = 0;
84 
85 		if (NULL != tv)
86 		{
87 			GetSystemTimeAsFileTime(&ft);
88 
89 			// The GetSystemTimeAsFileTime returns the number of 100 nanosecond
90 			// intervals since Jan 1, 1601 in a structure. Copy the high bits to
91 			// the 64 bit tmpres, shift it left by 32 then or in the low 32 bits.
92 			tmpres |= ft.dwHighDateTime;
93 			tmpres <<= 32;
94 			tmpres |= ft.dwLowDateTime;
95 
96 			// Convert to microseconds by dividing by 10
97 			tmpres /= 10;
98 
99 			// The Unix epoch starts on Jan 1 1970.  Need to subtract the difference
100 			// in seconds from Jan 1 1601.
101 			tmpres -= DELTA_EPOCH_IN_MICROSECS;
102 
103 			// Finally change microseconds to seconds and place in the seconds value.
104 			// The modulus picks up the microseconds.
105 			tv->tv_sec = (long)(tmpres / 1000000UL);
106 			tv->tv_usec = (long)(tmpres % 1000000UL);
107 		}
108 
109 		if (NULL != tz)
110 		{
111 			if (!tzflag)
112 			{
113 				_tzset();
114 				tzflag++;
115 			}
116 
117 			// Adjust for the timezone west of Greenwich
118 			tz->tz_minuteswest = _timezone / 60;
119 			tz->tz_dsttime = _daylight;
120 		}
121 
122 		return 0;
123 	}
124 
125 #elif defined(__APPLE__) || \
126 	((defined(__unix__) || defined(unix)) && !defined(USG))
127 
128 	#include <sys/param.h>
129 
130 	#if defined(BSD)
131 		#include <sys/sysctl.h>
132 	#elif defined(__linux__) || defined(__sun__)
133 		#include <sys/sysinfo.h>
134 	#else
135 		#error Unsupported Operating System
136 	#endif
137 #endif
138 
139 //////////////////////////////////////////////////////////////////////
140 
141 enum RTfileFormatValue { RT
142 	, RTI
143 	, RTI2
144 };
145 
146 static std::map<std::string, RTfileFormatValue> mapRTFileFormatValue;
147 
initializeRTfileFormatMap()148 static void initializeRTfileFormatMap()
149 {
150 	mapRTFileFormatValue["RT"] = RT;
151 	mapRTFileFormatValue["RTI"] = RTI;
152 	mapRTFileFormatValue["RTI2"] = RTI2;
153 }
154 
getRTfileFormatId(std::string RTfileFormatName)155 uint8_t getRTfileFormatId( std::string RTfileFormatName )
156 {
157 	initializeRTfileFormatMap();
158 	std::map<std::string, RTfileFormatValue>::iterator iter;
159 
160 	iter = mapRTFileFormatValue.find( RTfileFormatName );
161 
162 	if ( iter == mapRTFileFormatValue.end() )
163 	{
164 		std::cout << "RT file format " << RTfileFormatName << " is not supported"
165 			<< std::endl;
166 		exit( 1 );
167 	}
168 
169 	return iter->second;
170 }
171 
sub_timeofday(timeval tv2,timeval tv)172 timeval sub_timeofday( timeval tv2, timeval tv )
173 {
174 	timeval final;
175 
176 	final.tv_usec = tv2.tv_usec - tv.tv_usec;
177 	final.tv_sec = tv2.tv_sec - tv.tv_sec;
178 
179 	if ( final.tv_usec < 0 )
180 	{
181 		final.tv_usec += 1000000;
182 		--final.tv_sec;
183 	}
184 
185 	return final;
186 }
187 
188 /*
189  * 32-bit this is a problem if the file is > (2^31-1) bytes
190  * to get 64-bit behavior on 32 and 64 platforms:
191  * for gcc add these before including sys/types.h and sys/stat.h:
192  * 	#define __USE_LARGEFILE64
193  * 	#define _LARGEFILE_SOURCE
194  * 	#define _LARGEFILE64_SOURCE
195  * 	then use stat64 instead of stat for the structure and the call
196  * for VS
197  * 	use _stat64 for the structure and stat64 for the call
198  */
GetFileLen(char * file)199 long GetFileLen( char* file )
200 {
201 	struct stat sb;
202 
203 	if ( stat(file, &sb ) == -1 )
204 		return -1;
205 
206 	return sb.st_size;
207 }
208 
209 // 32-bit this is a problem if the file is > (2^31-1) bytes
GetFileLen(std::string file)210 long GetFileLen( std::string file )
211 {
212 	struct stat sb;
213 
214 	if ( stat(file.c_str(), &sb ) == -1 )
215 		return -1;
216 
217 	return sb.st_size;
218 }
219 
220 /*
221  * In use by items that resolve boinc filenames
222  * 1) boinc_ReadLinesFromFile in this file
223  * 2) boinc_software/boinc_client_apps/distrrtgen/distrrtgen.cpp
224  * 3) boinc_software/boinc_client_apps/distrrtgen_cuda/distrrtgen.cpp
225  */
GetFileLen(FILE * file)226 long GetFileLen(FILE* file)
227 {
228 	// XXX on x86/x86_64 linux returns long
229 	// 32-bit this is a problem if the file is > (2^31-1) bytes
230 	long pos = ftell(file);
231 	fseek(file, 0, SEEK_END);
232 	long len = ftell(file);
233 	fseek(file, pos, SEEK_SET);
234 
235 	return len;
236 }
237 
TrimString(std::string s)238 std::string TrimString( std::string s )
239 {
240 	while (s.size() > 0)
241 	{
242 		if (s[0] == ' ' || s[0] == '\t')
243 			s = s.substr(1);
244 		else
245 			break;
246 	}
247 
248 	while (s.size() > 0)
249 	{
250 		if (s[s.size() - 1] == ' ' || s[s.size() - 1] == '\t')
251 			s = s.substr(0, s.size() - 1);
252 		else
253 			break;
254 	}
255 
256 	return s;
257 }
GetHybridCharsets(std::string sCharset,std::vector<tCharset> & vCharset)258 bool GetHybridCharsets( std::string sCharset, std::vector<tCharset>& vCharset )
259 {
260 	// Example: hybrid(mixalpha-numeric-all-space#6-6,numeric#1-4)
261 	if(sCharset.substr(0, 6) != "hybrid") // Not hybrid charset
262 		return false;
263 
264 	std::string::size_type nEnd = sCharset.rfind(')');
265 	std::string::size_type nStart = sCharset.rfind('(');
266 	std::string sChar = sCharset.substr(nStart + 1, nEnd - nStart - 1);
267 	std::string commas = "";
268 
269 	int commaCount = std::count( sChar.begin(), sChar.end(), ',' );
270 
271 	for ( int i = 0; i < commaCount; i++ )
272 		commas += ",";
273 
274 	std::vector<std::string> vParts;
275 
276 	if ( !SeperateString(sChar, commas, vParts) )
277 	{
278 		std::cout << "Failed to SeperateString: " << sChar << std::endl;
279 		return false;
280 	}
281 
282 	for(uint32_t i = 0; i < vParts.size(); i++)
283 	{
284 		tCharset stCharset;
285 		std::vector<std::string> vParts2;
286 
287 		if ( !SeperateString(vParts[i], "#", vParts2) )
288 		{
289 			std::cout << "Failed to SeperateString: " << vParts[i] << std::endl;
290 			return false;
291 		}
292 
293 		stCharset.sName = vParts2[0];
294 		std::vector<std::string> vParts3;
295 
296 		if( !SeperateString(vParts2[1], "-", vParts3) )
297 		{
298 			std::cout << "Failed to SeperateString: " << vParts2[1] << std::endl;
299 			return false;
300 		}
301 
302 		stCharset.nPlainLenMin = atoi(vParts3[0].c_str());
303 		stCharset.nPlainLenMax = atoi(vParts3[1].c_str());
304 
305 		vCharset.push_back(stCharset);
306 	}
307 
308 	return true;
309 }
310 #ifdef BOINC
boinc_ReadLinesFromFile(std::string sPathName,std::vector<std::string> & vLine)311 bool boinc_ReadLinesFromFile( std::string sPathName, std::vector<std::string>& vLine )
312 {
313 	vLine.clear();
314 #ifdef USE_INTEGRATED_CHARSET
315 	vLine.push_back("byte                        = []");
316 	vLine.push_back("alpha                       = [ABCDEFGHIJKLMNOPQRSTUVWXYZ]");
317 	vLine.push_back("alpha-space                 = [ABCDEFGHIJKLMNOPQRSTUVWXYZ ]");
318 	vLine.push_back("alpha-numeric               = [ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]");
319 	vLine.push_back("alpha-numeric-space         = [ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ]");
320 	vLine.push_back("alpha-numeric-symbol14      = [ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D]");
321 	vLine.push_back("alpha-numeric-symbol14-space= [ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D\x20]");
322 	vLine.push_back("all                         = [ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D\x7E\x60\x5B\x5D\x7B\x7D\x7C\x5C\x3A\x3B\x22\x27\x3C\x3E\x2C\x2E\x3F\x2F]");
323 	vLine.push_back("all-space                   = [ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D\x7E\x60\x5B\x5D\x7B\x7D\x7C\x5C\x3A\x3B\x22\x27\x3C\x3E\x2C\x2E\x3F\x2F\x20]");
324 	vLine.push_back("alpha-numeric-symbol32-space = [ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D\x7E\x60\x5B\x5D\x7B\x7D\x7C\x5C\x3A\x3B\x22\x27\x3C\x3E\x2C\x2E\x3F\x2F\x20]");
325 	vLine.push_back("lm-frt-cp437                = [\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x7B\x7C\x7D\x7E\x80\x8E\x8F\x90\x92\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA5\xE0\xE1\xE2\xE3\xE4\xE6\xE7\xE8\xE9\xEA\xEB\xEE]");
326 	vLine.push_back("lm-frt-cp850                = [\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x7B\x7C\x7D\x7E\x80\x8E\x8F\x90\x92\x99\x9A\x9C\x9D\x9F\xA5\xB5\xB6\xB7\xBD\xBE\xC7\xCF\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xDE\xE0\xE1\xE2\xE3\xE5\xE6\xE8\xE9\xEA\xEB\xED\xEF]");
327 	vLine.push_back("lm-frt-cp437-850            = [\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x7B\x7C\x7D\x7E\x80\x8E\x8F\x90\x92\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA5\xB5\xB6\xB7\xBD\xBE\xC7\xCF\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xDE\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xED\xEE\xEF]");
328 	vLine.push_back("numeric                     = [0123456789]");
329 	vLine.push_back("numeric-space               = [0123456789 ]");
330 	vLine.push_back("loweralpha                  = [abcdefghijklmnopqrstuvwxyz]");
331 	vLine.push_back("loweralpha-space            = [abcdefghijklmnopqrstuvwxyz ]");
332 	vLine.push_back("loweralpha-numeric          = [abcdefghijklmnopqrstuvwxyz0123456789]");
333 	vLine.push_back("loweralpha-numeric-space    = [abcdefghijklmnopqrstuvwxyz0123456789 ]");
334 	vLine.push_back("loweralpha-numeric-symbol14 = [abcdefghijklmnopqrstuvwxyz0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D]");
335 	vLine.push_back("loweralpha-numeric-all      = [abcdefghijklmnopqrstuvwxyz0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D\x7E\x60\x5B\x5D\x7B\x7D\x7C\x5C\x3A\x3B\x22\x27\x3C\x3E\x2C\x2E\x3F\x2F]");
336 	vLine.push_back("loweralpha-numeric-symbol32-space= [abcdefghijklmnopqrstuvwxyz0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D\x7E\x60\x5B\x5D\x7B\x7D\x7C\x5C\x3A\x3B\x22\x27\x3C\x3E\x2C\x2E\x3F\x2F\x20]");
337 	vLine.push_back("mixalpha                    = [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]");
338 	vLine.push_back("mixalpha-space              = [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ]");
339 	vLine.push_back("mixalpha-numeric            = [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]");
340 	vLine.push_back("mixalpha-numeric-space      = [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ]");
341 	vLine.push_back("mixalpha-numeric-symbol14   = [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D]");
342 	vLine.push_back("mixalpha-numeric-all        = [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D\x7E\x60\x5B\x5D\x7B\x7D\x7C\x5C\x3A\x3B\x22\x27\x3C\x3E\x2C\x2E\x3F\x2F]");
343 	vLine.push_back("mixalpha-numeric-symbol32-space  = [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D\x7E\x60\x5B\x5D\x7B\x7D\x7C\x5C\x3A\x3B\x22\x27\x3C\x3E\x2C\x2E\x3F\x2F\x20]");
344 	vLine.push_back("mixalpha-numeric-all-space  = [abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\x21\x40\x23\x24\x25\x5E\x26\x2A\x28\x29\x2D\x5F\x2B\x3D\x7E\x60\x5B\x5D\x7B\x7D\x7C\x5C\x3A\x3B\x22\x27\x3C\x3E\x2C\x2E\x3F\x2F\x20]");
345 #endif
346 
347 	char input_path[512];
348 	boinc_resolve_filename(sPathName.c_str(), input_path, sizeof(input_path));
349 	FILE *file = boinc_fopen(input_path, "rb");
350 	if (!file) {
351 		fprintf(stderr,
352 			"Couldn't find input file, resolved name %s.\n", input_path
353 		);
354 		exit(-1);
355 	}
356 
357 	if (file != NULL)
358 	{
359 		long len = GetFileLen(file);
360 		char* data = new char[len + 1];
361 		fread(data, 1, len, file);
362 		data[len] = '\0';
363 		std::string content = data;
364 		content += "\n";
365 		delete [] data;
366 
367 		unsigned int i;
368 		for (i = 0; i < content.size(); i++)
369 		{
370 			if (content[i] == '\r')
371 				content[i] = '\n';
372 		}
373 
374 		std::string::size_type n;
375 		while ((n = content.find("\n", 0)) != std::string::npos)
376 		{
377 			std::string line = content.substr(0, n);
378 			line = TrimString(line);
379 			if (line != "")
380 				vLine.push_back(line);
381 			content = content.substr(n + 1);
382 		}
383 
384 		fclose(file);
385 	}
386 	else
387 		return false;
388 
389 	return true;
390 }
391 #endif
ReadLinesFromFile(std::string sPathName,std::vector<std::string> & vLine)392 bool ReadLinesFromFile( std::string sPathName, std::vector<std::string>& vLine )
393 {
394 	vLine.clear();
395 
396 	FILE* file = fopen(sPathName.c_str(), "rb");
397 	if (file != NULL)
398 	{
399 		long len = GetFileLen( sPathName );
400 		char* data = new char[len + 1];
401 		fread(data, 1, len, file);
402 		data[len] = '\0';
403 		std::string content = data;
404 		content += "\n";
405 		delete [] data;
406 
407 		unsigned int i;
408 		for (i = 0; i < content.size(); i++)
409 		{
410 			if (content[i] == '\r')
411 				content[i] = '\n';
412 		}
413 
414 		std::string::size_type n;
415 		while ((n = content.find("\n", 0)) != std::string::npos)
416 		{
417 			std::string line = content.substr(0, n);
418 			line = TrimString(line);
419 			if (line != "")
420 				vLine.push_back(line);
421 			content = content.substr(n + 1);
422 		}
423 
424 		fclose(file);
425 	}
426 	else
427 		return false;
428 
429 	return true;
430 }
431 
writeResultLineToFile(std::string sOutputFile,std::string sHash,std::string sPlain,std::string sBinary)432 bool writeResultLineToFile( std::string sOutputFile, std::string sHash, std::string sPlain, std::string sBinary )
433 {
434 	FILE* file = fopen(sOutputFile.c_str(), "a");
435 	if (file!=NULL)
436 	{
437 		std::string buffer = sHash + ":" + sPlain + ":" + sBinary + "\n";
438 		fputs (buffer.c_str(), file);
439 		fclose (file);
440 		return true;
441 	}
442 	else
443 		return false;
444 }
445 
SeperateString(std::string s,std::string sSeperator,std::vector<std::string> & vPart)446 bool SeperateString( std::string s, std::string sSeperator, std::vector<std::string>& vPart )
447 {
448 	vPart.clear();
449 
450 	unsigned int i;
451 	for (i = 0; i < sSeperator.size(); i++)
452 	{
453 		std::string::size_type n;
454 		if ( (n = s.find(sSeperator[i])) != std::string::npos)
455 		{
456 			vPart.push_back(s.substr(0, n));
457 			s = s.substr(n + 1);
458 		}
459 		else
460 		{
461 			printf("not found: %c\n", sSeperator[i]);
462 			printf("s: %s\n", s.c_str());
463 			return false;
464 		}
465 	}
466 	vPart.push_back(s);
467 
468 	return true;
469 }
470 
uint64tostr(uint64_t n)471 std::string uint64tostr(uint64_t n)
472 {
473 	char str[32];
474 
475 	sprintf(str, "%"PRIu64, n);
476 
477 	return str;
478 }
479 
uint64tohexstr(uint64_t n)480 std::string uint64tohexstr(uint64_t n)
481 {
482 	char str[32];
483 
484 	//sprintf(str, "%016llx", n);
485 	sprintf(str, "%016"PRIx64, n);
486 
487 	return str;
488 }
489 
HexToBinary(const char * data,int len)490 std::string HexToBinary( const char* data, int len  )
491 {
492 	std::string tmpData = std::string( data, len );
493 	std::string binary;
494 
495 	for ( int i = 0; i <= len; i += 2 )
496 	{
497 		std::string dataPart = tmpData.substr( i, 2 );
498 		std::istringstream iss( dataPart );
499 		int j;
500 
501 		iss >> std::hex >> j;
502 		binary += j;
503 	}
504 
505 	return binary;
506 }
507 
HexToStr(const unsigned char * pData,int nLen)508 std::string HexToStr(const unsigned char* pData, int nLen)
509 {
510 	std::string sRet;
511 	int i;
512 	for (i = 0; i < nLen; i++)
513 	{
514 		char szByte[3];
515 		sprintf(szByte, "%02x", pData[i]);
516 		sRet += szByte;
517 	}
518 
519 	return sRet;
520 }
521 
GetAvailPhysMemorySize()522 unsigned long GetAvailPhysMemorySize()
523 {
524 #ifdef _WIN32
525 	MEMORYSTATUS ms;
526 	GlobalMemoryStatus(&ms);
527 	return ms.dwAvailPhys;
528 #elif defined(BSD)
529 	int mib[2] = { CTL_HW, HW_PHYSMEM };
530 	uint64_t physMem;
531 	//XXX warning size_t isn't portable
532 	size_t len;
533 	len = sizeof(physMem);
534 	sysctl(mib, 2, &physMem, &len, NULL, 0);
535 	return physMem;
536 #elif defined(__linux__)
537 	FILE *procfd = NULL;
538 
539 	if ( (procfd = fopen("/proc/meminfo", "r")) != NULL )
540 	{
541 		char result[256]={0};
542 		char *tmp = NULL;
543 		unsigned int cachedram = 0, freeram = 0, bufferram = 0;
544 		uint64_t tempram = 0;
545 
546 		while( fgets(result,sizeof(char)*256,procfd) != NULL )
547 		{
548 			tmp = strtok(result, " ");
549 			if( (strncmp(tmp,"MemFree:" , 8)) == 0 )
550 			{
551 				tmp = strtok(NULL, " ");
552 				freeram = atoi(tmp);
553 			}
554 			else if( (strncmp(tmp, "Buffers:", 8)) == 0 )
555 			{
556 				tmp = strtok(NULL, " ");
557 				bufferram = atoi(tmp);
558 			}
559 			else if( (strncmp(tmp, "Cached:", 7)) == 0 )
560 			{
561 				tmp = strtok(NULL, " ");
562 				cachedram = atoi(tmp);
563 				/*
564 				 * in 2.6 and 3.0 kernels the order is maintained and this is the
565 				 * last value to read.  Break and don't read more lines
566 				 */
567 				break;
568 			}
569 		}
570 
571 		fclose(procfd);
572 
573 		tempram = (uint64_t)(freeram + bufferram + cachedram) * 1024;
574 
575 		if ( sizeof(long) == 4 )
576 		{
577 			// ensure that we don't return more than 2^31-1 on 32-bit platforms
578 			if ( tempram > 0x7FFFFFFFLLU )
579 				return (unsigned long) 0x7FFFFFFFLLU;
580 			else
581 				return (unsigned long) tempram;
582 		}
583 
584 		return tempram;
585 	}
586 
587 	struct sysinfo info;
588 	sysinfo(&info);
589 	return ( info.freeram + info.bufferram ) * (unsigned long) info.mem_unit;
590 #elif defined(__sun__)
591 	return ((unsigned long)sysconf(_SC_AVPHYS_PAGES) * (unsigned long)sysconf(_SC_PAGESIZE));
592 #else
593 	return 0;
594 	#error Unsupported Operating System
595 #endif
596 }
597 
GetApplicationPath()598 std::string GetApplicationPath()
599 {
600 	char fullPath[FILENAME_MAX];
601 
602 #ifdef _WIN32
603 	GetModuleFileName(NULL, fullPath, FILENAME_MAX);
604 #else
605 	char szTmp[32];
606 	// XXX linux/proc file system dependent
607 	sprintf(szTmp, "/proc/%d/exe", (int)getpid());
608 	int bytes = readlink(szTmp, fullPath, FILENAME_MAX);
609 
610 	if( bytes >= 0 )
611 		fullPath[bytes] = '\0';
612 #endif
613 
614 	std::string sApplicationPath = fullPath;
615 #ifdef _WIN32
616 	std::string::size_type nIndex = sApplicationPath.find_last_of('\\');
617 #else
618 	std::string::size_type nIndex = sApplicationPath.find_last_of('/');
619 #endif
620 
621 	if ( nIndex != std::string::npos )
622 		sApplicationPath = sApplicationPath.substr(0, nIndex+1);
623 
624 	return sApplicationPath;
625 }
626 
ParseHash(std::string sHash,unsigned char * pHash,int & nHashLen)627 void ParseHash( std::string sHash, unsigned char* pHash, int& nHashLen )
628 {
629 	uint32_t i;
630 	for (i = 0; i < sHash.size() / 2; i++)
631 	{
632 		std::string sSub = sHash.substr(i * 2, 2);
633 		unsigned int nValue;
634 		sscanf(sSub.c_str(), "%02x", &nValue);
635 		pHash[i] = (unsigned char)nValue;
636 	}
637 
638 	nHashLen = (int) sHash.size() / 2;
639 }
640 
Logo()641 void Logo()
642 {
643 	std::cout	<< "RainbowCrack (improved, multi-threaded) - Making a Faster Cryptanalytic Time-Memory Trade-Off" << std::endl
644 			<< "by Martin Westergaard <martinwj2005@gmail.com>" << std::endl
645 			<< "multi-threaded and enhanced by neinbrucke" << std::endl
646 			<< "*nix/64-bit compatibility and co-maintainer - James Nobis <quel@quelrod.net>" << std::endl
647 			<< "http://www.freerainbowtables.com/" << std::endl
648 			<< "All code/binaries are under GPL2 Copyright at a minimum" << std::endl
649 			<< "original code by Zhu Shuanglei <shuanglei@hotmail.com>" << std::endl << std::endl;
650 }
651 
652 // XXX nmap is GPL2, will check newer releases regarding license
653 // Code comes from nmap, used for the linux implementation of kbhit()
654 #ifndef _WIN32
655 
656 static int tty_fd = 0;
657 struct termios saved_ti;
658 
tty_getchar()659 int tty_getchar()
660 {
661 	int c, numChars;
662 
663 	if (tty_fd && tcgetpgrp(tty_fd) == getpid()) {
664 		c = 0;
665 		numChars = read(tty_fd, &c, 1);
666 		if (numChars > 0) return c;
667 	}
668 
669 	return -1;
670 }
671 
tty_done()672 void tty_done()
673 {
674 	if (!tty_fd) return;
675 
676 	tcsetattr(tty_fd, TCSANOW, &saved_ti);
677 
678 	close(tty_fd);
679 	tty_fd = 0;
680 }
681 
tty_init()682 void tty_init()
683 {
684 	struct termios ti;
685 
686 	if (tty_fd)
687 		return;
688 
689 	if ((tty_fd = open("/dev/tty", O_RDONLY | O_NONBLOCK)) < 0) return;
690 
691 	tcgetattr(tty_fd, &ti);
692 	saved_ti = ti;
693 	ti.c_lflag &= ~(ICANON | ECHO);
694 	ti.c_cc[VMIN] = 1;
695 	ti.c_cc[VTIME] = 0;
696 	tcsetattr(tty_fd, TCSANOW, &ti);
697 
698 	atexit(tty_done);
699 }
700 
tty_flush(void)701 void tty_flush(void)
702 {
703 	tcflush(tty_fd, TCIFLUSH);
704 }
705 // end nmap code
706 #endif
707