My specific question is around what exactly zipfile.ZipFile(myfile.zip).extractall(thepassword) actually does. I'm working through some pentest tutorials and have written the following snippet.
There are two files that the script acts upon. The first is a zip file that was created using zip -P very_long_random_string_password -r myfile.zip myfiles.txt. This is on Kali Linux from the CLI with Python3 (3.9). The second file is a list of common passwords from github ([passlist.txt][1]).
#Python3
from zipfile import ZipFile
with open('passlist.txt', 'r') as f:
for line in f:
password = line.strip('\n')
password = password.encode('utf-8')
try:
foundpass = ZipFile('myfile.zip').extractall(pwd=password)
if foundpass == None:
print("\nPassword: ", password.decode())
break
except RuntimeError:
pass
The expected result would be for the script to try every password in the passlist.txt and if the extractall method didn't throw a RuntimeError to print out the successful password. If the password is wrong, the program continues.
This in fact does work and I've tried multiple passwords that are caught as expected based on passwords in the passlist.txt. BUT... I wanted to have the script run unsuccessfully and got an unexpected result.
Using a -P pashdshGivgisudhfagn9879te6rtq6rr in the zip process, which doesn't exist in the passlist.txt resulted in successfully unlocking the zip file using the password rabbit11. As it turns out I can unzip the file with rabbit11 or pashdshGivgisudhfagn9879te6rtq6rr.
I've run this several times now with different very_long_random_string_passwords and been able to find corresponding simple_passwords that will unlock the zip file.
Why? I don't see any pattern to encoded text and this seems to be odd behavior.
Other examples (I actually haven't found one that doesn't work):
Complex: 444hdshGivgisudhfagn9879te6rtq6rr
Simple: rugby12
Complex: rszv8FoGGM6JRWGX
Simple: lickme
Related
I created a script that analyzes files based on yara rules ( the yara are the ones from this repository https://github.com/Yara-Rules/rules). My script import a yara file that include all other rules.When i try to compile it, i receive a syntax error: "can't open include file: rules_for_files\Antidebug_AntiVM_index.yar", pointing me to one of the rules. I tried to exclude it but it continue points to others.
I tried to use different versions of python: 1.i used python2.7 and i received the mentioned error in both case when i use a binary string/raw string. About python 3.5 when i mentioned a binary string like the one from my code sample, the interpreter broke/reset(in case i use a GUI). How can i resolve this? Thank you.
rules = yara.compile(filepaths={
"malware_set1 rules": b'C:/Users/g_bondrila/Desktop/phishme/functionalitati/yararules/importyara.yar'})
def yara_match(file_path, rules=rules):
try:
matches = rules.match(file_path, timeout=60)
return matches
#except TimeoutError:
# print("the time is running out")
except:
print("something")
Try giving the directory path as below:
"C:\\Users\\g_bondrila\\Desktop\\phishme\\functionalitati\\yararules\\importyara.yar"
Since Python doesn't reads single slash for a path in windows.
I have a server/client socket pair in Python. The server receives specific commands, then prepares the response and send it to the client.
In this question, my concern is just about possible injections in the code: if it could be possible to ask the server doing something weird with the 2nd parameter -- if the control on the command contents is not sufficient to avoid undesired behaviour.
EDIT:
according to advices received
added parameter shell=True when calling check_output on windows. Should not be dangerous since the command is a plain 'dir'.
.
self.client, address = self.sock.accept()
...
cmd = bytes.decode(self.client.recv(4096))
ls: executes a system command but only reads the content of a directory.
if cmd == 'ls':
if self.linux:
output = subprocess.check_output(['ls', '-l'])
else:
output = subprocess.check_output('dir', shell=True)
self.client.send(output)
cd: just calls os.chdir.
elif cmd.startswith('cd '):
path = cmd.split(' ')[1].strip()
if not os.path.isdir(path):
self.client.send(b'is not path')
else:
os.chdir(path)
self.client.send( os.getcwd().encode() )
get: send the content of a file to the client.
elif cmd.startswith('get '):
file = cmd.split(' ')[1].strip()
if not os.path.isfile(file):
self.client.send(b'ERR: is not a file')
else:
try:
with open(file) as f: contents = f.read()
except IOError as er:
res = "ERR: " + er.strerror
self.client.send(res.encode())
continue
... (send the file contents)
Except in implementation details, I cannot see any possibilities of direct injection of arbitrary code because you do not use received parameters in the only commands you use (ls -l and dir).
But you may still have some security problems :
you locate commands through the path instead of using absolute locations. If somebody could change the path environment variable what could happen ... => I advice you to use directly os.listdir('.') which is portable and has less risks.
you seem to have no control on allowed files. If I correctly remember reading CON: or other special files on older Windows version gave weird results. And you should never give any access to sensible files, configuration, ...
you could have control on length of asked files to avoid users to try to break the server with abnormally long file names.
Typical issues in a client-server scenario are:
Tricking the server into running a command that is determined by the client. In the most obvious form this happens if the server allows the client to run commands (yes, stupid). However, this can also happen if the client can supply only command parameters but shell=True is used. E.g. using subprocess.check_output('dir %s' % dir, shell=True) with a client-supplied dir variable would be a security issue, dir could have a value like c:\ && deltree c:\windows (a second command has been added thanks to the flexibility of the shell's command line interpreter). A relatively rare variation of this attack is the client being able to influence environment variables like PATH to trick the server into running a different command than intended.
Using unexpected functionality of built-in programming language functions. For example, fopen() in PHP won't just open files but fetch URLs as well. This allows passing URLs to functionality expecting file names and playing all kinds of tricks with the server software. Fortunately, Python is a sane language - open() works on files and nothing else. Still, database commands for example can be problematic if the SQL query is generated dynamically using client-supplied information (SQL Injection).
Reading data outside the allowed area. Typical scenario is a server that is supposed to allow only reading files from a particular directory, yet by passing in ../../../etc/passwd as parameter you can read any file. Another typical scenario is a server that allows reading only files with a particular file extension (e.g. .png) but passing in something like passwords.txt\0harmless.png still allows reading files of other types.
Out of these issues only the last one seems present in your code. In fact, your server doesn't check at all which directories and files the client should be allowed to read - this is a potential issue, a client might be able to read confidential files.
So i've searched through all the questions on this site (maybe not all, but most), and none of them have quite the right answer for what i'm looking for!
Part of my code, in Python, is setup as:
specialstring = special
if input == "T"
trash = commandline("sudo dd if=zero blahblah%blah" % specialstring)
Every time I run the command, it asks for a password. I do not want it to request a password! I don't need a lecture on how unsafe it is to run a root without a password (or however your phrase it)... I would just like to know what to do to have my code not need a password to run the command, and then exit root after the command so I can continue on normally with the rest of my code. THANKS!
-NOOB
You can make a "user" not have to enter in the password when using sudo for a specific program by editing the /etc/sudoers file.
Open up the file and edit it to include this line (where is the name of the user):
<user> ALL = NOPASSWD: /bin/dd
As mentioned in the comments of your previous question, you need to add to your sudoers file like this for the sake of simplicity just turn off the passwords and you will be able to run this without a password
admin ALL = NOPASSWD: ALL
the file will be found in /etc/sudoers
Then your python script will run fine and not require a password
Here is a tutorial on how to use visudo which is what you will need to use to edit sudo password settings
Why would you need to run 'dd' as root anyway? The 'dd' program is available to all users, so running the same command without 'sudo' in front would be sufficient. The only reason I can think of is if the file where you write the output of 'dd' to is only writable by root or another user.
So, try this:
specialstring = special
if input == "T"
trash = commandline("dd if=zero blahblah%blah" % specialstring)
Is there a simple module that let's you paste input in python ?
Asking someone to type letter by letter is kinda harsh .
By default a .py file is opened with python.exe if is installed and this does not allow "rightclick+paste" in the console .So how can i make this happen with python ? i think this would be more of a exact question .
You can make this by open cmd.exe and type here "C:\Python32\python".
Path is depend on the version of python. Mine is 3.2.
If you're looking for a way to simply paste something into the windows command prompt, John Giotta is correct that a user can click on the little icon in the top left.
I imagine, however, that you're looking for a way that a user can input a large amount of text, without typing it in line by line. A simple way to do this, would be to let the user input a file name, which python would then read. Perhaps something like this is what you're looking for:
while True:
filename = raw_input("Path to file to be read: ")
try:
with open(filename, 'rb') as f:
contents = f.read()
break
except IOError:
print "That was not a valid file \n"
This loop will keep asking the user for a file until then enter a valid path. When they enter a valid path, it will be read in as a string to the contents variable. This way, a user could enter a large amount of text into a file, and then you simply prompt them for the path to the file.
You can read up on file input more In the docs.
I have a program written in python that uploads an archive (zip file) to a remote server. But before uploading it I need to test that it is not corrupted, so I want to execute something like an unzip -t and throw an error if it fails.
Is there something implemented in python that can do that (couldn't find anything on google), or is there a way to catch the error from my program if I execute the system call unzip -t?
Thanks
Zipfile.testzip is your friend.
Read all the files in the archive and check their CRC’s and file headers. Return the name of the first bad file, or else return None.
Use ZipFile.testzip:
import zipfile
def zip_isOk(fn):
with zipfile.ZipFile(fn, 'r') as zipf:
return zipf.testzip() is None