Exemplo n.º 1
0
void exercise6(){
/* Exercise 6 */
// Break repeating-key XOR

	bool failed = false;

	Xstr decoded_part = "I'm back and I'm ringin' the bell \n"
						"A rockin' on the mike while the fly girls yell \n"
						"In ecstasy in the back of me \n"
						"Well that's my DJ Deshay cuttin' all them Z's \n"
						"Hittin' hard and the girlies goin' crazy \n"
						"Vanilla's on the mike, man I'm not lazy.";

	string line;
	string base64_encoded = string("");
	ifstream string_file("test_files/encoded_ex6.txt");

	Xstr ascii_encoded;
	decoded_message message;
	Xstr decoded;

	// testing hamming distance - should be 37
	int hamming_dist = Xstr("this is a test").hamming_distance("wokka wokka!!!");

	if(hamming_dist != 37){
		failed = true;
		goto eval6;
	}

	// read string into vector from file
	if (string_file.is_open()){
		while( getline(string_file, line) ){
			base64_encoded += line;
		}

		string_file.close();
	}
	else{
		cout << "ERROR: Unable to open file" << endl;
		failed = true;
		goto eval6;
	}

	ascii_encoded = Xstr(base64_encoded, Xstr::BASE64_ENCODED );
	message = solve_repeating_key_xor( ascii_encoded );

	decoded = ascii_encoded.XOR_wraparound(message.key);

	if(decoded.substr(0, decoded_part.size()) != decoded_part)
		failed = true;

	eval6: ;
	crypto_exercise_test(6, !failed);
}
Exemplo n.º 2
0
void exercise24(){
/* Exercise 24 */

	bool failed = false;

	int max_score = 1;
	Xstr best_key = Xstr();
	Xstr test_str = Xstr("This is test str");
	Xstr key_guess = Xstr(2, 0); // 2 bytes, start at 0x0000
	Xstr result = Xstr();

	// testing MT19937 encryption/decryption
	Xstr encrypted = BlockCipher::MT19937_encrypt(test_str, "AA");
	Xstr decrypted = BlockCipher::MT19937_decrypt(encrypted, "AA");

	if(decrypted != test_str){
		failed = true;
		goto eval24;
	}

	// testing MT19937 key cracking
	failed = false;

	// 0xFFFF represents the capacity of 16 bits
	// iterate through possibilities (65536) and evaluate for common
	// egnlish characters
	for(int i = 0; i < 0xFFFF; i++){
		result = BlockCipher::MT19937_decrypt(test_str, key_guess);

		char element;
		int score = 0;

		do{
			element = result[result.size() - score - 1];
		}while(is_english_character(element) and ++score < result.size());

		if(score > max_score){
			best_key = key_guess;
			max_score = score;
		}

		key_guess++;
	}

	decrypted = BlockCipher::MT19937_decrypt(test_str, best_key);

	if(decrypted != test_str){
		failed = true;
		goto eval24;
	}

	eval24:	crypto_exercise_test(24, !failed);
}
Exemplo n.º 3
0
void exercise8(){
/* Exercise 8 */

	bool failed = false;

	Xstr expected_ECB_cipher = Xstr(
			"D880619740A8A19B7840A8A31C810A3D08649AF70DC06F4FD5D2D69C744C"
			"D283E2DD052F6B641DBF9D11B0348542BB5708649AF70DC06F4FD5D2D69C"
			"744CD2839475C9DFDBC1D46597949D9C7E82BF5A08649AF70DC06F4FD5D2"
			"D69C744CD28397A93EAB8D6AECD566489154789A6B0308649AF70DC06F4F"
			"D5D2D69C744CD283D403180C98C8F6DB1F2A3F9C4040DEB0AB51B29933F2"
			"C123C58386B06FBA186A", Xstr::HEX_ENCODED);

	ifstream string_file("test_files/encoded_ex8.txt");

	vector<Xstr> possible_ciphers;
	string line;
	Xstr ECB_found;


	// read string into vector from file
	if (string_file.is_open()){
		while( getline(string_file, line) ){
			Xstr ascii_string = Xstr( line, Xstr::HEX_ENCODED );
			possible_ciphers.push_back( ascii_string );
		}

		string_file.close();
	}
	else{
		failed = true;
		goto eval8;
		cout << "ERROR: Unable to open file" << endl;;
	}

	// iterate through ciphers and see if they are ECB encoded
	for(Xstr cipher: possible_ciphers){
		if( detect_ECB_AES_encryption( cipher ) ){
			ECB_found = cipher;
			break;
		}
	}

	if(expected_ECB_cipher != ECB_found)
		failed = true;

	eval8: ;
	crypto_exercise_test(8, !failed);

}
Exemplo n.º 4
0
void exercise1(){
	bool failed = false;

	ifstream encoded_strings("test_files/encoded_b64_ex19.txt");

	Xstr newstr;
	string b64_str;
	string new_b64_str;

	string test[4] = {
			"dGhpcyBpcyBhIHRlc3Qu",
			"dGhpcyBpcyBhIHRlc3QuLg==",
			"dGhpcyBpcyBhIHRlc3QuLi4=",
			"dGhpcyBpcyBhIHRlc3QuLi4u"
	};

	// test different amounts of trailing '=' placeholders
	// and uneven b64:ascii element ratios
	for(int s = 0; s <= 3; s++){

		Xstr ascii_str = Xstr(test[s], Xstr::BASE64_ENCODED);

		if(ascii_str.as_base64() != test[s]){
			failed = true;
			goto eval1;
			break;
		}
	}


	eval1:	crypto_exercise_test(1,	!failed);

}
Exemplo n.º 5
0
int 
main()
{
	int i = 9;
	printf("%s\n",Xstr(OP));
	TRACE(i,%d);
	printf("this is ""a macros test""i=""%x""\n",i);
}
Exemplo n.º 6
0
void exercise20(){
//	vector.push_back() is busted
//
// ONLY EXERCISE THAT HAS NOT BEEN FIXED
/* Exercise 20 */

	vector<Xstr> strings;
	vector<Xstr> ciphers;

	Xstr random_key = generate_random_AES_key();

	Xstr newstr;
	Xstr next_cipher;

	/* Make 8-byte nonce for CTR, fill with 0's
	 * We use the same nonce for all encryptions, which is where the
	 * weakness is */
	Xstr nonce;
	nonce.resize(AES::CTR_NONCE_SIZE, 0);

	ifstream string_file("test_files/plaintext_ex20.txt");
	string line;

	cout << "HERE" << endl;
	int i = 0;
	// read string into vector from file and encrypt
	// TODO: make function that will encrypt batch
	if (string_file.is_open()){
		while( getline(string_file, line) ){
			newstr = Xstr(line, Xstr::BASE64_ENCODED);
//				cout << "\tHERE0" << endl;
//				strings[i] = ( newstr );

//				cout << "\tHERE1" << endl;
			next_cipher = BlockCipher::encrypt(
					EncryptType::CTR_ENCRYPT, nonce, random_key, nonce);

//				cout << newstr.as_base64() << endl;

//				cout << "\tHERE2" << endl;
//				ciphers.push_back(next_cipher);
//				cout << "\tHERE3" << endl;
			i++;
			cout << ">>>>> " << i << endl;
		}
		cout << "HERE" << endl;
		string_file.close();
	}
	else{
		cout << " Unable to open file" << endl;
	}

	cout << "HERE" << endl;
	vector<Xstr> decoded = break_fixed_nonce_CTR_statistically(ciphers);

//		for (auto i = decoded.begin(); i != decoded.end(); ++i)
//		    std::cout << *i << ' ' << endl;
}
Exemplo n.º 7
0
void exercise25(){
/* Exercise 25 */
// TODO: Needs fixing, decoded output is returning known_text (all X's)

	bool failed = false;
	string line;
	string base64_encoded = string("");
	Xstr cipher, intermediate, decoded, edited_cipher;
	Xstr known_text;

	ifstream string_file("test_files/encoded_ex7.txt");


	// read string into vector from file
	if (string_file.is_open()){
		while( getline(string_file, line) ){
			base64_encoded += line;
		}

		string_file.close();
	}
	else{
		cout << "ERROR: Unable to open file" << endl;
		failed = true;
		goto eval25;
	}

	cipher = Xstr( base64_encoded, Xstr::BASE64_ENCODED );
	known_text = Xstr(cipher.size(), 'X'); // fill known text with X's


	edited_cipher = server_API_cipher_edit(EncryptType::CTR_ENCRYPT, cipher, 0, known_text);

	intermediate = edited_cipher ^ known_text;

	decoded = intermediate ^ cipher;

//		if(decoded.substr(0, decoded_part.size()) != decoded_part){
//			failed = true;
//		}

	eval25: ;
	crypto_exercise_test(25, !failed);
}
Exemplo n.º 8
0
void exercise9(){
/* Exercise 9 */

	static Xstr output = "YELLOW SUBMARINE\x04\x04\x04\x04";

	Xstr message = Xstr("YELLOW SUBMARINE");

	crypto_exercise_test(9,
				output == message.add_padding(Xstr::PKCS7_PADDING, 20)
			);
}
Exemplo n.º 9
0
void exercise4(){
/* Exercise 4 */
// Detect single-character XOR

	bool failed = false;

	vector<Xstr> possible_strings;
	string line;
	ifstream string_file("test_files/encoded_ex4.txt");
	Xstr output("Now that the party is jumping\n");

	int max_idx = -1;
	bool max_found = false;

	decoded_message max_message;
	max_message.score = 0;
	max_message.decoded = Xstr();

	// read string into vector from file
	if (string_file.is_open()){
		while( getline(string_file, line) ){
			Xstr ascii_string(line, Xstr::HEX_ENCODED );
			possible_strings.push_back( ascii_string );
		}

		string_file.close();
	}
	else{
		cout << "Unable to open file" << endl;
		failed = true;
		goto eval4;
	}

	// iterate through potential strings and find the best solution for each.
	// Regard string with highest score as encoded string
	for(Xstr next_str: possible_strings){
		decoded_message message = solve_single_byte_xor( next_str );

		if(message.score > max_message.score){
			max_found = true;
			max_message.score = message.score;
			max_message.decoded = message.decoded;
		}
	}

	if(max_message.decoded != output)
		failed = true;

	eval4:
		crypto_exercise_test(4, !failed);
}
Exemplo n.º 10
0
void exercise7(){
/* Exercise 7 */

	bool failed = false;
	string line;
	string base64_encoded = string("");
	Xstr encoded, decoded;

	Xstr decoded_part = "I'm back and I'm ringin' the bell \n"
						"A rockin' on the mike while the fly girls yell \n"
						"In ecstasy in the back of me \n"
						"Well that's my DJ Deshay cuttin' all them Z's \n"
						"Hittin' hard and the girlies goin' crazy \n"
						"Vanilla's on the mike, man I'm not lazy.";

	ifstream string_file("test_files/encoded_ex7.txt");
	string key = string("YELLOW SUBMARINE");


	// read string in from file
	if (string_file.is_open()){
		while( getline(string_file, line) ){
			base64_encoded += line;
		}

		string_file.close();
	}
	else{
		cout << "ERROR: Unable to open file" << endl;
		//TODO: put two next lines in all file open operations
		//TODO: also, make read_file() function
		failed = true;
		goto eval7;
	}

	encoded = Xstr( base64_encoded, Xstr::BASE64_ENCODED );
	decoded = BlockCipher::decrypt(EncryptType::ECB_ENCRYPT, encoded, key);

//		cout << decoded_part.size() << endl;
//		cout << decoded.substr(0, decoded_part.size()).size() << endl;
//		cout << decoded.substr(0, decoded_part.size()) << endl;

	if(decoded.substr(0, decoded_part.size()) != decoded_part){
		failed = true;
	}

	eval7: ;
	crypto_exercise_test(7, !failed);
}
Exemplo n.º 11
0
void exercise18(){
/* Exercise 18 */

	Xstr encrypted = Xstr("L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ",
							Xstr::BASE64_ENCODED);

	Xstr key = "YELLOW SUBMARINE";

	Xstr nonce;
	nonce.resize(AES::CTR_NONCE_SIZE, 0); // size 8 - nonce is all zeroes!

	Xstr decrypted = BlockCipher::decrypt(EncryptType::CTR_ENCRYPT, encrypted, key, nonce);

	Xstr encrypted2 = BlockCipher::encrypt(EncryptType::CTR_ENCRYPT, decrypted, key, nonce);
	Xstr decrypted2 = BlockCipher::decrypt(EncryptType::CTR_ENCRYPT, encrypted2, key, nonce);

	crypto_exercise_test(18, decrypted == decrypted2);
}
Exemplo n.º 12
0
void exercise5(){
/* Exercise 5 */
// Implement repeating-key XOR

	bool failed = false;

	Xstr expected = Xstr(
			"0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2"
			"a26226324272765272a282b2f20430a652e2c652a3124333a653e2b20"
			"27630c692b20283165286326302e27282f", Xstr::HEX_ENCODED);

	Xstr message = "Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal";
	Xstr key = "ICE";

	Xstr encoded = message.XOR_wraparound(key);

	if(encoded == expected)
		failed = false;

	crypto_exercise_test(5, !failed);
}
Exemplo n.º 13
0
void exercise26(){
/* Exercise 26 */
// CTR bit flipping attacks

	// generate unknown key only once
	static Xstr random_key = generate_random_AES_key();
	// generate unknown nonce only once
	static Xstr rand_nonce = generate_random_nonce(AES::CTR_NONCE_SIZE);
	// create unknown string once
	static Xstr unknown_string = Xstr(
			"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg"
			"aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq"
			"dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg"
			"YnkK", Xstr::BASE64_ENCODED);

	static Xstr prefix = "comment1=cooking%20MCs;userdata=";
	static Xstr suffix = ";comment2=%20like%20a%20pound%20of%20bacon";
	static string admin_token = ";admin=true;";

	Xstr message = "XXXXXXXXXXXXXXXX:admin<true:XXXX";
	Xstr encrypted = BlockCipher::encrypt(EncryptType::CTR_ENCRYPT, prefix + message + suffix, random_key, rand_nonce);

	// in the attack message we chose values for the tokens of interest
	// such that we can just XOR them with 0b01 to obtain the desired tokens
	//
	// NOTE: the indices are the only thing different between this and Ex. 16
	// 		Not sure why the indices should be different though... explanation needed
	encrypted[48] ^= 1;
	encrypted[54] ^= 1;
	encrypted[59] ^= 1;

	Xstr decrypted = BlockCipher::decrypt(EncryptType::CTR_ENCRYPT, encrypted, random_key, rand_nonce);
	decrypted = decrypted.remove_padding(Xstr::UNKNOWN_PADDING);

	crypto_exercise_test(26,
				// find doesn't reach end of string = successfully found
				// our injected admin token
				decrypted.as_ascii().find(admin_token) != std::string::npos
			);
}
Exemplo n.º 14
0
void exercise10(){
/* Exercise 10 */

	static string output =
		"I'm back and I'm ringin' the bell \nA rockin' on the mike while the fly girls yell \nIn ecstasy in the back of me \nWell that's my DJ Deshay cuttin' all them Z's \nHittin' hard and the girlies goin' crazy \nVanilla's on the mike, man I'm not lazy. \n\nI'm lettin' my drug kick in \nIt controls my mouth and I begin \nTo just let it flow, let my concepts go \nMy posse's to the side yellin', Go Vanilla Go! \n\nSmooth 'cause that's the way I will be \nAnd if you don't give a damn, then \nWhy you starin' at me \nSo get off 'cause I control the stage \nThere's no dissin' allowed \nI'm in my own phase \nThe girlies sa y they love me and that is ok \n"
		"And I can dance better than any kid n' play \n\nStage 2 -- Yea the one ya' wanna listen to \nIt's off my head so let the beat play through \nSo I can funk it up and make it sound good \n1-2-3 Yo -- Knock on some wood \nFor good luck, I like my rhymes atrocious \nSupercalafragilisticexpialidocious \nI'm an effect and that you can bet \nI can take a fly girl and make her wet. \n\nI'm like Samson -- Samson to Delilah \nThere's no denyin', You can try to hang \nBut you'll keep tryin' to get my style \nOver and over, practice makes perfect \nBut not if you're a loafer. \n\nYou'll get nowhere, no place, no time, no girls \nSoon -- Oh my God, homebody, you probably eat \n"
		"Spaghetti with a spoon! Come on and say it! \n\nVIP. Vanilla Ice yep, yep, I'm comin' hard like a rhino \nIntoxicating so you stagger like a wino \nSo punks stop trying and girl stop cryin' \nVanilla Ice is sellin' and you people are buyin' \n'Cause why the freaks are jockin' like Crazy Glue \nMovin' and groovin' trying to sing along \nAll through the ghetto groovin' this here song \nNow you're amazed by the VIP posse. \n\nSteppin' so hard like a German Nazi \nStartled by the bases hittin' ground \nThere's no trippin' on mine, I'm just gettin' down \nSparkamatic, I'm hangin' tight like a fanatic \nYou trapped me once and I thought that \nYou might have it \nSo step down and lend me your ear \n"
		"'89 in my time! You, '90 is my year. \n\nYou're weakenin' fast, YO! and I can tell it \nYour body's gettin' hot, so, so I can smell it \nSo don't be mad and don't be sad \n'Cause the lyrics belong to ICE, You can call me Dad \nYou're pitchin' a fit, so step back and endure \nLet the witch doctor, Ice, do the dance to cure \nSo come up close and don't be square \nYou wanna battle me -- Anytime, anywhere \n\nYou thought that I was weak, Boy, you're dead wrong \nSo come on, everybody and sing this song \n\nSay -- Play that funky music Say, go white boy, go white boy go \nplay that funky music Go white boy, go white boy, go \nLay down and boogie and play that funky music till you die. \n\n"
		"Play that funky music Come on, Come on, let me hear \nPlay that funky music white boy you say it, say it \nPlay that funky music A little louder now \nPlay that funky music, white boy Come on, Come on, Come on \nPlay that funky music \n";

	string line;
	string base64_encoded = string("");
	string key = string("YELLOW SUBMARINE");

	string IV = string();
	IV.resize(AES::BLOCKSIZE, 0); // size 16 - IV is all zeroes!

	ifstream string_file("test_files/encoded_ex10.txt");

	// read string in from file
	if (string_file.is_open()){
		while( getline(string_file, line) ){
			base64_encoded += line;
		}
		string_file.close();
	}
	else{
		cout << "Exercise 10: Unable to open file" << endl;
	}

	Xstr ascii_encoded = Xstr( base64_encoded, Xstr::BASE64_ENCODED );
	Xstr message = BlockCipher::decrypt(EncryptType::CBC_ENCRYPT, ascii_encoded, key, IV);

	crypto_exercise_test(10,
				output == message.remove_padding(Xstr::UNKNOWN_PADDING)
			);
}
Exemplo n.º 15
0
void exercise16(){
/* Exercise 16 */
/* 	CBC bitflipping attacks */

	// generate unknown key only once
	static Xstr random_key = generate_random_AES_key();
	// generate unknown IV only once
	static Xstr rand_IV = generate_random_AES_IV();
	// create unknown string once
	static Xstr unknown_string = Xstr(
			"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg"
			"aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq"
			"dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg"
			"YnkK", Xstr::BASE64_ENCODED);

	static Xstr prefix = "comment1=cooking%20MCs;userdata=";
	static Xstr suffix = ";comment2=%20like%20a%20pound%20of%20bacon";
	static string admin_token = ";admin=true;";

	Xstr message = "XXXXXXXXXXXXXXXX:admin<true:XXXX";
	Xstr encrypted = BlockCipher::encrypt(EncryptType::CBC_ENCRYPT, prefix + message + suffix, random_key, rand_IV);

	// in the attack message we chose values for the tokens of interest
	// such that we can just XOR them with 0b01 to obtain the desired tokens
	encrypted[32] ^= 1;
	encrypted[38] ^= 1;
	encrypted[43] ^= 1;

	Xstr decrypted = BlockCipher::decrypt(EncryptType::CBC_ENCRYPT, encrypted, random_key, rand_IV);
	decrypted = decrypted.remove_padding(Xstr::UNKNOWN_PADDING);

	crypto_exercise_test(16,
				// find doesn't reach end of string
				decrypted.as_ascii().find(admin_token) != std::string::npos
			);
}
Exemplo n.º 16
0
void exercise19(){
//	vector.push_back() is busted

	/* Exercise 19 */
		Xstr keystream("Z/kf0FmwkR2EwZr1qdZfgqaoWbSlLy/QGY/VRRhA9LAAA===", Xstr::BASE64_ENCODED);

		string strings[38] = {
				"SSBoYXZlIG1ldCB0aGVtIGF0IGNsb3NlIG9mIGRheQ==",
				"Q29taW5nIHdpdGggdml2aWQgZmFjZXM=",
				"RnJvbSBjb3VudGVyIG9yIGRlc2sgYW1vbmcgZ3JleQ==",
				"RWlnaHRlZW50aC1jZW50dXJ5IGhvdXNlcy4=",
				"SSBoYXZlIHBhc3NlZCB3aXRoIGEgbm9kIG9mIHRoZSBoZWFk",
				"T3IgcG9saXRlIG1lYW5pbmdsZXNzIHdvcmRzLA==",
				"T3IgaGF2ZSBsaW5nZXJlZCBhd2hpbGUgYW5kIHNhaWQ=",
				"UG9saXRlIG1lYW5pbmdsZXNzIHdvcmRzLA==",
				"QW5kIHRob3VnaHQgYmVmb3JlIEkgaGFkIGRvbmU=",
				"T2YgYSBtb2NraW5nIHRhbGUgb3IgYSBnaWJl",
				"VG8gcGxlYXNlIGEgY29tcGFuaW9u",
				"QXJvdW5kIHRoZSBmaXJlIGF0IHRoZSBjbHViLA==",
				"QmVpbmcgY2VydGFpbiB0aGF0IHRoZXkgYW5kIEk=",
				"QnV0IGxpdmVkIHdoZXJlIG1vdGxleSBpcyB3b3JuOg==",
				"QWxsIGNoYW5nZWQsIGNoYW5nZWQgdXR0ZXJseTo=",
				"QSB0ZXJyaWJsZSBiZWF1dHkgaXMgYm9ybi4=",
				"VGhhdCB3b21hbidzIGRheXMgd2VyZSBzcGVudA==",
				"VW50aWwgaGVyIHZvaWNlIGdyZXcgc2hyaWxsLg==",
				"V2hhdCB2b2ljZSBtb3JlIHN3ZWV0IHRoYW4gaGVycw==",
				"V2hlbiB5b3VuZyBhbmQgYmVhdXRpZnVsLA==",
				"U2hlIHJvZGUgdG8gaGFycmllcnM/",
				"VGhpcyBtYW4gaGFkIGtlcHQgYSBzY2hvb2w=",
				"QW5kIHJvZGUgb3VyIHdpbmdlZCBob3JzZS4=",
				"VGhpcyBvdGhlciBoaXMgaGVscGVyIGFuZCBmcmllbmQ=",
				"V2FzIGNvbWluZyBpbnRvIGhpcyBmb3JjZTs=",
				"SGUgbWlnaHQgaGF2ZSB3b24gZmFtZSBpbiB0aGUgZW5kLA==",
				"U28gc2Vuc2l0aXZlIGhpcyBuYXR1cmUgc2VlbWVkLA==",
				"U28gZGFyaW5nIGFuZCBzd2VldCBoaXMgdGhvdWdodC4=",
				"VGhpcyBvdGhlciBtYW4gSSBoYWQgZHJlYW1lZA==",
				"QSBkcnVua2VuLCB2YWluLWdsb3Jpb3VzIGxvdXQu",
				"SGUgaGFkIGRvbmUgbW9zdCBiaXR0ZXIgd3Jvbmc=",
				"VG8gc29tZSB3aG8gYXJlIG5lYXIgbXkgaGVhcnQs",
				"WWV0IEkgbnVtYmVyIGhpbSBpbiB0aGUgc29uZzs=",
				"SGUsIHRvbywgaGFzIHJlc2lnbmVkIGhpcyBwYXJ0",
				"SW4gdGhlIGNhc3VhbCBjb21lZHk7",
				"VHJhbnNmb3JtZWQgdXR0ZXJseTo=",
				"QSB0ZXJyaWJsZSBiZWF1dHkgaXMgYm9ybi4=",
		};

		vector<Xstr> ciphers;
		Xstr random_key("Rfh9orvO75Iba9PsvseQPg==",  Xstr::BASE64_ENCODED);


		/* Make 8-byte nonce for CTR, fill with 0's
		 * We use the same nonce for all encryptions, which is where the
		 * weakness is */
		Xstr nonce;
		nonce.resize(AES::CTR_NONCE_SIZE, 0);


		Xstr next_str;
		Xstr next_cipher;
		Xstr newstr;
		string s;

		// encrypt the strings
		for(int i = 0; i < 37; i++){
			newstr = Xstr(strings[i], Xstr::BASE64_ENCODED);

			next_cipher = BlockCipher::encrypt(EncryptType::CTR_ENCRYPT, newstr, random_key, nonce);

			ciphers.push_back( next_cipher );
		}

		// get keystream with partially solved characters
		Xstr cracked_keystream = break_fixed_nonce_CTR_by_substituting(ciphers);

		// I could waste my time guessing and complete the keystream, but I
		// have better things to do :)

		crypto_exercise_test(19,
					keystream == cracked_keystream
				);
}
Exemplo n.º 17
0
static gint pop3_getrange_uidl_recv(Pop3Session *session, const gchar *data,
				    guint len)
{
	gchar id[IDLEN + 1];
	gchar buf[POPBUFSIZE];
	gint buf_len;
	guint32 num;
	time_t recv_time;
	gint partial_recv;
	const gchar *p = data;
	const gchar *lastp = data + len;
	const gchar *newline;

	while (p < lastp) {
		if ((newline = memchr(p, '\r', lastp - p)) == NULL)
			return -1;
		buf_len = MIN(newline - p, sizeof(buf) - 1);
		memcpy(buf, p, buf_len);
		buf[buf_len] = '\0';

		p = newline + 1;
		if (p < lastp && *p == '\n') p++;

		if (sscanf(buf, "%d %" Xstr(IDLEN) "s", &num, id) != 2 ||
		    num <= 0 || num > session->count) {
			log_warning(LOG_PROTOCOL, _("invalid UIDL response: %s\n"), buf);
			continue;
		}

		session->msg[num].uidl = g_strdup(id);

		recv_time = (time_t)(GPOINTER_TO_INT(g_hash_table_lookup(
			   		session->uidl_table, id)));
		session->msg[num].recv_time = recv_time;

		if (recv_time != RECV_TIME_NONE) {
			debug_print("num %d uidl %s: already got it\n", num, id);		
		} else {
			debug_print("num %d uidl %s: unknown\n", num, id);
		}

		partial_recv = (gint)(GPOINTER_TO_INT(g_hash_table_lookup(
					session->partial_recv_table, id)));

		if (recv_time != RECV_TIME_NONE
		|| partial_recv != POP3_TOTALLY_RECEIVED) {
			session->msg[num].received = 
				(partial_recv != POP3_MUST_COMPLETE_RECV);
			session->msg[num].partial_recv = partial_recv;
			if (partial_recv == POP3_MUST_COMPLETE_RECV)
				session->new_msg_exist = TRUE;
		}
		if (!session->new_msg_exist &&
		    (recv_time == RECV_TIME_NONE ||
		     session->ac_prefs->rmmail)) {
			session->cur_msg = num;
			session->new_msg_exist = TRUE;
		}
	}

	session->uidl_is_valid = TRUE;
	return PS_SUCCESS;
}
Exemplo n.º 18
0
Handle poly_dispatch_c(TaskData *taskData, Handle args, Handle code)
{
    unsigned c = get_C_unsigned(taskData, DEREFWORDHANDLE(code));
    switch (c)
    {
    case 1:
        return exportNative(taskData, args); // Export
    case 2:
        raise_syscall(taskData, "C Export has been withdrawn", 0);
        return 0;
    case 3:
        return exportPortable(taskData, args); // Export as portable format

    case 9: // Return the GIT version if appropriate
        {
             return SAVE(C_string_to_Poly(taskData, GitVersion));
        }

    case 10: // Return the RTS version string.
        {
            const char *version;
            switch (machineDependent->MachineArchitecture())
            {
            case MA_Interpreted:    version = "Portable-" TextVersion; break;
            case MA_I386:           version = "I386-" TextVersion; break;
            case MA_X86_64:         version = "X86_64-" TextVersion; break;
            default:                version = "Unknown-" TextVersion; break;
            }
            return SAVE(C_string_to_Poly(taskData, version));
        }

    case 11: // Return the RTS copyright string
        return SAVE(C_string_to_Poly(taskData, poly_runtime_system_copyright));

    case 12: // Return the architecture
        {
            const char *arch;
            switch (machineDependent->MachineArchitecture())
            {
            case MA_Interpreted:    arch = "Interpreted"; break;
            case MA_I386:           arch = "I386"; break;
            case MA_X86_64:         arch = "X86_64"; break;
            default:                arch = "Unknown"; break;
            }
            return SAVE(C_string_to_Poly(taskData, arch));
        }

    case 13: // Share common immutable data.
        {
            ShareData(taskData, args);
            return SAVE(TAGGED(0));
        }

        // ObjSize and ShowSize have their own IO vector entries but really they don't
        // need them.  Include them here and add ObjProfile.
    case 14:
        return ObjSize(taskData, args);

    case 15:
        return ShowSize(taskData, args);

    case 16:
        return ObjProfile(taskData, args);

    /* 17 and 18 are no longer used. */

    case 19: // Return the RTS argument help string.
        return SAVE(C_string_to_Poly(taskData, RTSArgHelp()));

    case 20: // Write a saved state file.
        return SaveState(taskData, args);

    case 21: // Load a saved state file and any ancestors.
        return LoadState(taskData, false, args);

    case 22: // Show the hierarchy.
        return ShowHierarchy(taskData);

    case 23: // Change the name of the immediate parent stored in a child
        return RenameParent(taskData, args);

    case 24: // Return the name of the immediate parent stored in a child
        return ShowParent(taskData, args);

    case 25: // Old statistics - now removed
    case 26:
        raise_exception_string(taskData, EXC_Fail, "No statistics available");

    case 27: // Get number of user statistics available
        return Make_arbitrary_precision(taskData, N_PS_USER);

    case 28: // Set an entry in the user stats table.
        {
            unsigned index = get_C_unsigned(taskData, DEREFHANDLE(args)->Get(0));
            if (index >= N_PS_USER)
                raise_exception0(taskData, EXC_subscript);
            POLYSIGNED value = getPolySigned(taskData, DEREFHANDLE(args)->Get(1));
            globalStats.setUserCounter(index, value);
            Make_arbitrary_precision(taskData, 0);
        }

    case 29: // Get local statistics.
        return globalStats.getLocalStatistics(taskData);

    case 30: // Get remote statistics.  The argument is the process ID to get the statistics.
        return globalStats.getRemoteStatistics(taskData, getPolyUnsigned(taskData, DEREFHANDLE(args)));

    case 31: // Store a module
        return StoreModule(taskData, args);

    case 32: // Load a module
        return LoadModule(taskData, args);

    case 33: // Load hierarchy.  This provides a complete list of children and parents.
        return LoadState(taskData, true, args);

    case 34: // Return the system directory for modules.  This is configured differently
        // in Unix and in Windows.
#if (defined(MODULEDIR))
    return SAVE(C_string_to_Poly(taskData, Xstr(MODULEDIR)));
#elif (defined(_WIN32) && ! defined(__CYGWIN__))
        {
            // This registry key is configured when Poly/ML is installed using the installer.
            // It gives the path to the Poly/ML installation directory.  We return the
            // Modules subdirectory.
            HKEY hk;
            if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                    _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\PolyML.exe"), 0,
                    KEY_QUERY_VALUE, &hk) == ERROR_SUCCESS)
            {
                DWORD valSize;
                if (RegQueryValueEx(hk, _T("Path"), 0, NULL, NULL, &valSize) == ERROR_SUCCESS)
                {
#define MODULEDIR _T("Modules")
                    TempString buff((TCHAR*)malloc(valSize + (_tcslen(MODULEDIR) + 1)*sizeof(TCHAR)));
                    DWORD dwType;
                    if (RegQueryValueEx(hk, _T("Path"), 0, &dwType, (LPBYTE)(LPTSTR)buff, &valSize) == ERROR_SUCCESS)
                    {
                        RegCloseKey(hk);
                        // The registry entry should end with a backslash.
                        _tcscat(buff, MODULEDIR);
                        return SAVE(C_string_to_Poly(taskData, buff));
                    }
                }
                RegCloseKey(hk);
            }
            return SAVE(C_string_to_Poly(taskData, ""));
        }
#else
        return SAVE(C_string_to_Poly(taskData, ""));
#endif

    case 50: // GCD
        return gcd_arbitrary(taskData, SAVE(DEREFHANDLE(args)->Get(0)), SAVE(DEREFHANDLE(args)->Get(1)));
    case 51: // LCM
        return lcm_arbitrary(taskData, SAVE(DEREFHANDLE(args)->Get(0)), SAVE(DEREFHANDLE(args)->Get(1)));

        // These next ones were originally in process_env and have now been moved here,
    case 100: /* Return the maximum word segment size. */
            return taskData->saveVec.push(TAGGED(MAX_OBJECT_SIZE));
    case 101: /* Return the maximum string size (in bytes).
                 It is the maximum number of bytes in a segment
                 less one word for the length field. */
            return taskData->saveVec.push(TAGGED((MAX_OBJECT_SIZE)*sizeof(PolyWord) - sizeof(PolyWord)));
    case 102: /* Test whether the supplied address is in the io area.
                 This was previously done by having get_flags return
                 256 but this was changed so that get_flags simply
                 returns the top byte of the length word. */
        {
            PolyWord *pt = (PolyWord*)DEREFWORDHANDLE(args);
            if (gMem.IsIOPointer(pt))
                return Make_arbitrary_precision(taskData, 1);
            else return Make_arbitrary_precision(taskData, 0);
        }
    case 103: /* Return the register mask for the given function.
                 This is used by the code-generator to find out
                 which registers are modified by the function and
                 so need to be saved if they are used by the caller. */
        {
            PolyObject *pt = DEREFWORDHANDLE(args);
            if (gMem.IsIOPointer(pt))
            {
                /* IO area.  We need to get this from the vector. */
                int i;
                for (i=0; i < POLY_SYS_vecsize; i++)
                {
                    if (pt == (PolyObject*)IoEntry(i))
                    {
                        int regMask = taskData->GetIOFunctionRegisterMask(i);
                        POLYUNSIGNED props = rtsProperties(taskData, i);
                        return taskData->saveVec.push(TAGGED(regMask | props));
                    }
                }
                raise_exception_string(taskData, EXC_Fail, "Io pointer not found");
            }
            else
            {
                /* We may have a pointer to the code or a pointer to
                   a closure.  If it's a closure we have to find the
                   code. */
                if (! pt->IsCodeObject() && ! pt->IsByteObject())
                    pt = pt->Get(0).AsObjPtr();

                /* Should now be a code object. */
                if (pt->IsCodeObject())
                {
                    /* Compiled code.  This is the second constant in the
                       constant area. */
                    PolyWord *codePt = pt->ConstPtrForCode();
                    PolyWord mask = codePt[1];
                    // A real mask will be an integer.
                    if (IS_INT(mask)) return SAVE(mask);
                    else raise_exception_string(taskData, EXC_Fail, "Invalid mask");
                }
                else raise_exception_string(taskData, EXC_Fail, "Not a code pointer");
            }
        }

    case 104: return Make_arbitrary_precision(taskData, POLY_version_number);

    case 105: /* Get the name of the function. */
        {
            PolyObject *pt = DEREFWORDHANDLE(args);
            if (gMem.IsIOPointer(pt))
            {
                /* IO area. */
                int i;
                for (i=0; i < POLY_SYS_vecsize; i++)
                {
                    if (pt == (PolyObject*)IoEntry(i))
                    {
                        char buff[8];
                        sprintf(buff, "RTS%d", i);
                        return SAVE(C_string_to_Poly(taskData, buff));
                    }
                }
                raise_syscall(taskData, "Io pointer not found", 0);
            }
            else if (pt->IsCodeObject()) /* Should now be a code object. */ 
            {
                /* Compiled code.  This is the first constant in the constant area. */
                PolyWord *codePt = pt->ConstPtrForCode();
                PolyWord name = codePt[0];
                /* May be zero indicating an anonymous segment - return null string. */
                if (name == PolyWord::FromUnsigned(0))
                    return SAVE(C_string_to_Poly(taskData, ""));
                else return SAVE(name);
            }
            else raise_syscall(taskData, "Not a code pointer", 0);
        }

    default:
        {
            char msg[100];
            sprintf(msg, "Unknown poly-specific function: %d", c);
            raise_exception_string(taskData, EXC_Fail, msg);
            return 0;
        }
    }
}