I am trying to build a winzip file cracker without a dictionary attack (For an essay on password security). It needs to scroll through the "combos" iteration trying each combination until the passwords is found. So close to being done but currently it needs the password entry as a single string which is required to be converted to bytes whereas I need it to try each output of the combostotal
Thank you in advance for any help
I have saved it in a sandbox https://onlinegdb.com/ryRYih2im
Link to the file is here
https://drive.google.com/open?id=1rpkJnImBJdg_aoiVpX4x5PP0dpEum2fS
Click for screenshot
Simple zip brute force password cracker
from itertools import product
from zipfile import ZipFile, BadZipFile
import string
def find_pw():
pw_length = 1
while True:
s = string.ascii_lowercase
for x in product(s, repeat=pw_length):
pwd = "".join(x)
with ZipFile("test.zip") as zf:
try:
zf.extractall(pwd=bytes(pwd, "UTF-8"))
print("Password is {}".format(pwd))
return
except RuntimeError as e:
pass
except BadZipFile as e:
pass
pw_length += 1
we need itertools.product for this type of tasks
string got alphanumeric strings for simplicity
Related
I was given a problem to solve, asking to add 3 more letters to 'Super' and then use it to unlock a zip file. My code is as follows:
import zipfile
import itertools
import time
# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
try:
zip_file.extractall(pwd=password)
return True
except KeyboardInterrupt:
exit(0)
except Exception, e:
pass
# Main code starts here...
# The file name of the zip file.
zipfilename = 'planz.zip'
# The first part of the password. We know this for sure!
first_half_password = 'Super'
# We don't know what characters they add afterwards...
# This is case sensitive!
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
zip_file = zipfile.ZipFile(zipfilename)
# We know they always have 3 characters after Super...
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
# Slowing it down on purpose to make it work better with the web terminal
# Remove at your peril
time.sleep(0.001)
# Add the three letters to the first half of the password.
password = first_half_password+''.join(c)
# Try to extract the file.
print "Trying: %s" % password
# If the file was extracted, you found the right password.
if extractFile(zip_file, password):
print '*' * 20
print 'Password found: %s' % password
print 'Files extracted...'
exit(0)
# If no password was found by the end, let us know!
print 'Password not found.'
But my code returns
./code.py: line 6: syntax error near unexpected token ('./code.py: line 6: def extractFile(zip_file, password):'
What is the syntax error, because I'm not able to find it?
You have to add a shebang:
In the first line add
#! /usr/bin/env python2
I am trying to write a quick little program that will parse through a CSV file pull usernames and passwords and test login to a FTP to create a directory and delete it with those usernames and passwords. I have written a try catch so it can output any errors I get so that I can review which FTP logins may need tweaking. The problem is when I run it, it will stall if any of the logins are broken instead of proceeding. I have tried using pass and finally after my try but it won't return to the loop. Any help is appreciated.
import csv
import ftplib
from ftplib import FTP
with open ('Filename.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
lineCount = 0
rowCount = 0
for row in readCSV:
username = row[rowCount]
passwordFTP = row[rowCount+1]
print (username)
ftp = FTP('ftp.org') #place the FTP address here
ftp.set_debuglevel(2) #this is set to highest debug level
try:
ftp.login(user='usernameGoesHere', passwd='passwordGoesHere', acct='')
except ftplib.all_errors as e:
errorcode_string = str(e).split(None, 1)[0]
pass
finally:
ftp.cwd('/TestDir')
ftp.mkd('testDir')
ftp.rmd('testDir')
ftp.quit()
pass
There is actually no pint in putting the code in finally. Despite the fact that you have put a pass statement, it has no role in this code. On getting an error on login the program will log the error and still try to make a folder for the given connection.
Instead move the cwd, mkd and other methods to the try block. If an error is thrown there, the except will catch it and stop the execution.
There is absolutely no need to put pass statements anywhere in the try. The only thing that can still remain in the finally block is ftp.quit() so it cleans up, closing the connection if one of the operations fails, but on the other hand what will happen if login is not successful?
Do something like:
with FTP('ftp.org') as ftp
try:
ftp.login(user='usernameGoesHere', passwd='passwordGoesHere', acct='')
ftp.cwd('/TestDir')
ftp.mkd('testDir')
ftp.rmd('testDir')
except ftplib.all_errors as e:
errorcode_string = str(e).split(None, 1)[0]
Using context manager (the with statement) will help you quitting manually.
I am currently writing a program in Python that asks if you have a log in. If no, they proceed to create a username and password. If yes, they log in and their details are checked against a text file. The text file looks like this (Username then password):
whitehallj27
EXpass%20
Username2
EXPASSWORD%%%
james_27
password1234
I am trying to figure out a way of programming this as simply as possible. It seems to work, but isn't nearly as simple and doesn't really work how I thought it would. Here is the code snippet:
logins={}
usernames_passwords=open("UsernamesAndPasswords.txt","r")
count=0
for line in usernames_passwords:
count=count+1
count=count/2
usernames_passwords.close()
usernames_passwords=open("UsernamesAndPasswords.txt","r")
try:
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
except TypeError:
count=int(count+0.5)
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
usernames_passwords.close()
print(logins)
Also, how would I go about authenticating the username and password to check it's correct.
Many thanks,
James Duxbury
Assuming that variables user and passwd have the username and password provided by the user, then just read the file in two lines:
file_contents = []
with open("UsernamesAndPasswords.txt","r") as f: #use "with", it will auotamtically close the file
file_contents = f.readlines()
usernames = file_contents[0::2] #step by 2, take all elements starting at index 0
passwords = file_contents[1::2] #step by 2, take all elements starting at index 1
found_at_index = -1
for i in range(0,len(usernames)):
if user == usernames[i] and passwd == passwrods[i]:
found_at_index = i
break
if found_at_index >= 0 :
#do whatever you want, there is match
else:
#I don't know what you wanted to do in this case
Please read this for the with keyword and this for how to read a file nicelly.
Also this about the [::] syntax.
You could create a dictionary with the user names and passwords like this:
dict = {
'user-name': 'password-hashing',
'another-user': 'another-password'
}
after you've done it you can save this dict in a json file, and load its content when the user asks for login.
the docs for handling json files with python: https://docs.python.org/3/library/json.html
obs.: it will look simpler, but its not the best way of doing this king of thing
I have read the other posts on this, but my situation is a bit unique I think. I am trying to use python to read my grades off of the school's home access center website, but I think there is something peculiar in the way they have it programmed, here is the code that I am using:
import urllib
def WebLogin(password):
params = urllib.urlencode(
{'txtLogin': username,
'txtPassword': password })
f = urllib.urlopen("http://home.tamdistrict.org/homeaccess/Student/Assignments.aspx", params)
if "The following errors occurred while attempting to log in:" in f.read():
print "Login failed."
print f.read()
else:
print "Correct!"
print f.read()
It always prints "Correct" no matter what I enter for the username and password. Each f.read() returns only a blank line. I am really stuck here, thanks for all of your help!
urlopen returns a file-like object. In particular, you can only call read() once (with no arguments -- you can read in chunks by passing a size to read, but ya) -- subsequent calls to read() will return None because you've exhausted it (and unlike regular file objects, there is no seek method). You should store the result in a variable.
content = f.read()
if "The following errors occurred while attempting to log in:" in content:
print "Login failed."
print content
else:
print "Correct!"
print content
I've got a program I would like to use to input a password and one or multiple strings from a web page. The program takes the strings and outputs them to a time-datestamped text file, but only if the password matches the set MD5 hash.
The problems I'm having here are that
I don't know how to get this code on the web. I have a server, but is it as easy as throwing pytext.py onto my server?
I don't know how to write a form for the input to this script and how to get the HTML to work with this program. If possible, it would be nice to make it a multi-line input box... but it's not necessary.
I want to return a value to a web page to let the user know if the password authenticated successfully or failed.
dtest
import sys
import time
import getopt
import hashlib
h = hashlib.new('md5')
var = sys.argv[1]
print "Password: ", var
h.update(var)
print h.hexdigest()
trial = h.hexdigest()
check = "86fe2288ac154c500983a8b89dbcf288"
if trial == check:
print "Password success"
time_stamp = time.strftime('%Y-%m-%d_%H-%M-%S', (time.localtime(time.time())))
strFile = "txt_" + str(time_stamp) + ".txt"
print "File created: txt_" + str(time_stamp) + ".txt"
#print 'The command line arguments are:'
#for i in sys.argv:
#print i
text_file = open(strFile, "w")
text_file.write(str(time_stamp) + "\n")
for i in range(2, len(sys.argv)):
text_file.write(sys.argv[i] + "\n")
#print 'Debug to file:', sys.argv[i]
text_file.close()
else:
print "Password failure"
You'll need to read up on mod_python (if you're using Apache) and the Python CGI module.
Take a look at django. It's an excellent web framework that can accomplish exactly what you are asking. It also has an authentication module that handles password hashing and logins for you.