Beispiel #1
0
def testBasicAuth(url,port):
	# Get the test credentials and generate the 
	print _('[+] Credenciais de Teste')
	userName = raw_input(_("Usuario: "))
	psswrd = getpass.getpass()
	encodedData = base64.b64encode(str(userName)+str(psswrd))
	print _('Key gerada (base64): ') + encodedData + '\n'
	
	# Make a BASIC HTTP Authentication Packet to send over the socket
	packet = 'GET / HTTP/1.1\r\nAuthorization: Basic ' + encodedData +'\r\n\r\n' # Maybe Host:www.google.com
	
	# Show the sent information
	print _('[+] Enviando Header') 
	print packet

	try:
		# Try to connect using poor configuration, with no SSL warpping at all
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sock.settimeout(10)
		
		# Use socket to connect with the server by a specific port and send the packet
		sock.connect((url, port))
		sock.send(packet)

		# Receive the result
		return buildResponse(False,'\n',_('Resposta: ') + sock.recv(1024)[:40])
		sock.close()
	except socket.error as e:
		return buildResponse(True,_('O servidor nao esta rodando em HTTP'),'\n')
Beispiel #2
0
def detectWAF(url,port,lang):
	import logging
	
	noWAF = _("\nWeb Application Firewall nao detectado")
	thereIsWAF = _("\nWeb Application Firewall detectado")

	logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
	
	parsed = urlparse(url)
	if len(parsed.netloc) == 0:
		parsed = urlparse('http://'+url)
		pass
	
	dst_ip = socket.gethostbyname(parsed.netloc)
	src_port = RandShort()


	# A TCP packet with the ACK flag (16) set and the port number to connect to is send to the server. 
	ack_flag_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=port,flags="A"),timeout=10, verbose=0)

	# 
	if (str(type(ack_flag_scan_resp))=="<type 'NoneType'>"):
		return _('Resposta: ') + "<No_Response_to_TCP_ACK>" + buildResponse(True, thereIsWAF,_('\n'))
	# If the server responds with the RST flag set inside a TCP packet, then the port is unfiltered and a stateful firewall is absent.
	elif(ack_flag_scan_resp.haslayer(TCP)):
		if(ack_flag_scan_resp.getlayer(TCP).flags == 0x4): # RST flag = 4
			return _('Resposta: ') + "<RST_flag_SET>" + buildResponse(False, _('\n'),noWAF) # RST flag
	# If the server doesnt respond to our TCK ACK scan packet or if it responds with a TCP packet with ICMP type 3 or code 1, 2, 3, 9, 10, or 13 set,
	# then the port is filtered and a stateful firewall is present.
	elif(ack_flag_scan_resp.haslayer(ICMP)):
		if(int(ack_flag_scan_resp.getlayer(ICMP).type)==3 and int(ack_flag_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
			return _('Resposta: ') + "<ICMP_type_3_TCP_Packet>" + buildResponse(True, thereIsWAF,_('\n'))
Beispiel #3
0
def protocolAnalysis(shouldNOTBeOffered,mustBeOffered,beingOffered):
	# Verify if the protocol should NOT be offered and print the proper result 
	if shouldNOTBeOffered:
		return buildResponse(not beingOffered,"Nao oferecido\tNAO SEGURO","Oferecido\tNAO SEGURO")
	# Verify if the protocol MUST be offered and print the proper result 
	elif mustBeOffered:
		return buildResponse(beingOffered,"Oferecido\tRECOMENDADO","Nao oferecido\tRECOMENDADO")
	# Just print if the protocol is offered or not
	elif beingOffered:
		return "Oferecido\t-"
	else:
		return "Nao oferecido\t-"
Beispiel #4
0
def testHttps(url,lang):
	global socket, requests, status_code, ssl
	try:
		r = requests.get('https://'+url)
		response = _('Resposta: ') + str(r) + buildResponse(str(r) == '<Response [200]>', _('\nHttps OK'),_('\nHttps nao utilizado'))
		pass
	except requests.exceptions.SSLError as e:
		err = str(e.message)
		if '[' in err:
			err = err.split("[",1)[1]
			err = err.split("]",1)[0]
		response = _('Resposta: ') + err + buildResponse(False, '',_('\nHttps nao utilizado'))
		pass
	return response
Beispiel #5
0
def compareMd5File(fileName, md5Value):

    # Try to read the file
    try:
        with open(fileName, 'r') as fp:
            md5Check = fp.read()
    except IOError as e:
        # If fails to find the file, print a message
        return _('Arquivo nao encontrado!')

    # Return a msg depending if the search was successful or not
    return _('Arquivo encontrado!\n MD5: {}').format(md5Check) + buildResponse(
        fileFound == md5Value, _(' Valido '), _(' nao confere\n'))

    return buildResponse(fileFound, )
Beispiel #6
0
def getLoginPages(url,lang):
	loginT = getLoginPage(url,lang) # = (msg,pageFound,pageList)
	response = _('Resposta: ') + loginT['msg'] + buildResponse(loginT['pageFound']==0, _('\nPaginas de Login OK'),_('\n[+] Paginas de Login contem url comum:'))
	
	# Including found urls ins the response. 
	# This runs in O(n) because CPython extends the string in the place
	for x in loginT['pageList']:
	 	response += '\n[|]\t' + x 
	 	pass 
	return (response,loginT['pageList'])
Beispiel #7
0
def testClickJack(url,lang):
	# Read the return of a "GET" request
	r = requests.get('http://'+url)
	validation = ('X-Frame-Options' in r.headers)

	# Search for the presence of the 'X-Frame-Options' on the header returned and analyse the value
	if validation == True:
		validation = (r.headers['X-Frame-Options'] == 'DENY') | (r.headers['X-Frame-Options'] == 'SAMEORIGIN')
	response = _('Resposta: ') + str(r) + buildResponse(validation,_('\nX-Frame-Options OK'),_('\nX-Frame-Options nao configurada'))

	return response
Beispiel #8
0
def verifyOpenTestPorts(lang, url, openPorts):
    # Start the list of Test Ports as empty and the found flag as False
    testPortFound = False

    # Search for non Commmon ports on the open port list
    for port in openPorts:
        if port not in COMMON_PORTS:
            testPortFound = True
            testPortList = port

    # If there is any non common port, build a warning message
    if testPortFound:
        # Show a warning if there is any test port open
        msg = _('Portas de teste abertas: ')
        for port in testPortList:
            msg += port + ', '
        # Return the response (if there is a problem) with all the problematic ports
        return buildResponse(False, _('\n'), msg)
    else:
        # Return that there is no problem
        return buildResponse(True, 'Nao ha portas de teste abertas', _('\n'))
Beispiel #9
0
def testPFS(host,port,protocol):
	# Create a list of pfs cipher used by the server
	pfsCipherOk = ''
	foundOne = False

	# Test each pfs cipher based on their protocol 
	for cipher in pfsCipherList.keys():
		okResult = testPFSCipher(host,port,cipher)
		if okResult:
			foundOne = True
			pfsCipherOk += (', ' if (len(pfsCipherOk)>0) else '') + cipher 
	
	return buildResponse(foundOne,_('PFS habilitado com as cifras: ') + pfsCipherOk, _('PFS nao detectado com as cifras testadas'))
Beispiel #10
0
def testXSS(url,lang):
	crawler = Crawler(CrawlerCache('crawler.db'))
	root_re = re.compile('^/$').match

	# Important declarations
	paths = ["/"]
	usedStrings = []
	selection = 3
	pageList = []
	msg = ["Website is not XSS vulnerable","XSS Vulnerability Found with: "]
	msgIndex = 0
	testAt = (False,"")

	# Map website structure
	while (selection != 1) & (selection != 2):
		selection = int(raw_input(_('Escolha um metodo: \n1 - Inserir os caminhos manualmente\n2 - Buscar os caminhos recursivamente (pode demorar)\n')))
	
	# Append the entire Recursive Search to the end of the paths list
	if selection == 2:
		paths = set(paths + crawler.crawl('http://'+url, no_cache=root_re))

	# Input method
	while selection == 1:
		path = raw_input(_('Insira um caminho iniciando por /: '))
		if not path in paths:
			paths.append(path)
			pass
		selection = raw_input(_('Deseja inserir mais caminhos? \n1 - Sim\n2 - Nao\n'))
	
	# Testing XSS vulnerabilites on every path
	for path in paths:
		print _('Testando ') + bcolors.UNDERLINE + path +  bcolors.ENDC
		testAt = xss('http://'+ str(url) + path)
		if testAt[0] == True:
			msgIndex = 1
			pageList.append(path)
			if not testAt[1] in usedStrings:
				msg[1] = msg[1] + testAt[1]
				usedStrings.append(testAt[1])
	
	# Making the result
	response =  _('Resposta: ') + msg[msgIndex] + buildResponse(msgIndex==0, _('\nTratamento de XSS OK'),_('\n[+] Paginas vulneraveis XSS:'))
	for x in pageList:
	 	response += '\n[|]\t' + x 
	 	pass 
	return response
Beispiel #11
0
def binExtract(fileName):
    # Generate the file descriptor using the file name
    with open(fileName, 'r') as outFile:
        file_content = outFile.read()

    # Parse the File content
    parser = uefi_firmware.AutoParser(file_content)
    firmwareData = parser.parse()

    # If the file has a known type, extract the content
    if parser.type() == 'unknown':
        firmwareContent = ''
    else:
        firmwareContent = firmwareData.showinfo()
    return _('Resultado: ') + parser.type() + '\n' + buildResponse(
        parser.type() == 'unknown', _('Sistema de arquivos nao identificado'),
        _('Sistema de arquivo identificado:\n') + firmwareContent)
Beispiel #12
0
def detectWAF2(url,lang):
	maliciousRequest = mechanize.Browser()
	maliciousRequest.set_handle_robots(False)
	maliciousRequest.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
	noWAF = "No WAF detected"
	thereIsWAF = "WAF detected"
	headersChange = "Headers Changed" # to a possible improvement

	#request = urllib2.Request("https://"+url, headers=hdr)
	maliciousRequest.open("http://"+url)
	
	crossSiteScriptingPayLoad = "<svg><script>alert&grave;1&grave;<p>"

	currentForm = 0
	for form in maliciousRequest.forms():
		maliciousRequest.select_form(nr = currentForm)

		# get all the possible SelectControls
		TextControls = getTextControls(str(maliciousRequest.form))
		if len(TextControls)==0:
			controlT = raw_input(_('Nao ha inputs para teste de Firewall\n'))
		for x in TextControls:
			try:
				# Test if the object is read only or none type (not present)
				maliciousRequest.form[x] = crossSiteScriptingPayLoad
				try:
					maliciousRequest.submit()
					pass
				except (mechanize.HTTPError,urllib2.HTTPError) as e:
					pass
			except (mechanize._form.AmbiguityError, TypeError,ValueError) as e:
				pass			
			sourceCode =  maliciousRequest.response().read()

			# Search for a message block from a Firewall
			if sourceCode.find('WebKnight') >= 0:
				return _('Resposta: ') + thereIsWAF + buildResponse(True, _('Firewall: WebKnight'),_(''))
			elif sourceCode.find('Mod_Security') >= 0:
				return _('Resposta: ') + thereIsWAF + buildResponse(True, _('Firewall: Mod Security'),_(''))
			elif sourceCode.find('Mod_Security') >= 0:
				return _('Resposta: ') + thereIsWAF + buildResponse(True, _('Firewall: Mod Security'),_(''))
			elif sourceCode.find('dotDefender') >= 0:
				return _('Resposta: ') + thereIsWAF + buildResponse(True, _('Firewall: Dot Defender'),_(''))
			elif (sourceCode.find('firewall') >= 0) | (sourceCode.find('Firewall') >= 0) | (sourceCode.find('WAF') >= 0):
				return _('Resposta: ') + thereIsWAF + buildResponse(True, _('Firewall is present'),_(''))
			
		## 
		# Test the nest
		currentForm += 1
	
	# Build the response
	return _('Resposta: ') + noWAF + buildResponse(False, _('\n'),_('\nFirewall nao detectado'))
Beispiel #13
0
def testFuzz(lang, url, openPorts):
    # Define the time of the fuzzing tests
    secondsOfTest = 7

    # Define the crash flag
    crashFlag = False

    # Send a Fuzz test using common commands for each port depending on the service running
    for port in openPorts:
        commonCommand = raw_input(
            _('\n[+] Porta {}:\n[|] Insira o comando a ser testado: ').format(
                port))
        tempFlag = sendFuzz(url, port, commonCommand, "rn", secondsOfTest)
        crashFlag = (crashFlag or tempFlag)

    # Return the response
    return buildResponse(not crashFlag, _('\nNenhum servico comprometido'),
                         _('\nUma das portas nao respondeu aos requests'))
Beispiel #14
0
		if response.status_code == 200:
			# Read the source code and get each field name to try an attack on it
			params = getParams(response.content)
			print _('Testando '+ bcolors.UNDERLINE + urlTest +  bcolors.ENDC + ' - Campos: ' + ' '.join(str(p) for p in params) )
			# Test a SQL Injection on each of the fields in the page source
			for param in params:
				# Try to access the url modifying the fields sent
				try:
					if (sqli(url,urlTest,param,"1\' or \'1\' = \'1") | sqli(url,urlTest,param,'1\" or \"1\" = \"1')):
						msgIndex = 1
						pageList.append(urlTest)
				except urllib2.HTTPError, e: # Access forbidden
					continue
		response.close()

	response =  _('Resposta: ') + msg[msgIndex] + buildResponse(msgIndex==0, _('\nTratamento de SQL Injection OK - Verificar arquivo de saida'),_('\n[+] Paginas vulneraveis a SQL Injection:'))
	for page in pageList:
	 	response += '\n[|]\t' + bcolors.UNDERLINE + page +  bcolors.ENDC 
	 	pass 
	return response

'''
	Test the XSS attack on the website
'''
def testXSS(url,lang):
	crawler = Crawler(CrawlerCache('crawler.db'))
	root_re = re.compile('^/$').match

	# Important declarations
	paths = ["/"]
	usedStrings = []