Module 'X' has no attribute 'Y' sometimes raised and sometimes not - python

I have multiples files but two are relevant.
The first one is PacketStrings.py and it looks something like this:
import re
from scapy.all import *
def packetString(pkt):
global attacker_ip
global tcp_payload
out = ""
if (IP in pkt):
attacker_ip = pkt[IP].src
out += ipString(pkt[IP])
elif (IPv6 in pkt):
# TODO
pass
if (TCP in pkt):
tcp_payload = payloadString(pkt[TCP])
out += tcpString(pkt[TCP])
out += "[TCP Payload]" + "\n"
out+= payloadString(pkt[TCP])
elif (UDP in pkt):
out += udpString(pkt[UDP])
out += "[UDP Payload]" + "\n"
out += payloadString(pkt[UDP])
return out
The second one is intrusion.py and it looks something like this
from PacketStrings import *
import json
from datetime import datetime
import urllib.parse
from scapy.all import *
SQLinjections = json.loads(open('/redpot/IDS/src_code/attacks/SQLinjections.json').read())
LOG = open("/redpot/logs/IDS/intrusions.log", "a")
def SQLintrusion(pkt):
ip = PacketStrings.attacker_ip
sus = PacketStrings.tcp_payload
if (len(sus) != 0):
for x in SQLinjections:
if (conf.route.route("0.0.0.0")[2] != ip and urllib.parse.quote_plus(x) in sus):
LOG.write(datetime.now().strftime("%d/%m/%Y %H:%M:%S")+" | Possible Intrusion Detected | Type = SQLinjection | IP = "+ip+" | Payload = "+str(x)+"\r\r\n")
When I run the function inside the second file sometimes it works without error and other times it raises the error :
AttributeError: module 'PacketStrings' has no attribute 'attacker_ip'

Related

Two different while loops run simultaneously in Tkinter (python)

I have made a simple chat system with python-requests. There are two different files one is the sender and another is the receiver. the main concept of these two files is
1. sender file contains a while loop which always takes the message as input. after
giving the message as input, it sends the message to a website.
2. receiver file also contains a while loop which gets requests from the website after every
5 seconds.
Now I want to run these two different works in the same window with Tkinter. how to do it? Thanks in advance.
Sender.py Code is here
import configme as con
import requests
import datetime
from cryptography.fernet import Fernet
nam = con.my_name
cookies_dict = con.cookie
key = con.crypto_key
url = con.base_url + '/config.php'
def makeID():
return datetime.datetime.now().timestamp()
# encription staff
fernet = Fernet(key)
# member joining message
if nam.__len__() != 0:
requests.get(url+f"?iD={makeID()}&name=<<<>>>&msg={nam} join the room.", cookies=cookies_dict)
with requests.Session() as r:
while True:
msg = input("Enter your Messege: ")
if msg == ".exit":
# r.get(url+f"?iD={makeID()}&name=<<<>>>&msg={nam} has left the room.", cookies=cookies_dict)
break
else:
encMessage = fernet.encrypt(msg.encode())
messenger = {'iD': makeID() ,'name': nam , 'msg': encMessage}
if msg != "":
r.get(url, params=messenger, cookies=cookies_dict)
Receiver.py code here...
import configme as con
import requests
import json
from cryptography.fernet import Fernet
from time import sleep
from datetime import datetime
from pytz import timezone
import pytz
cookies_dict = con.cookie
ozone = con.my_timezone
key = con.crypto_key
time_format = con.date_time_format
url = con.base_url + '/log.json'
t = con.receive_time
# encription staff
fernet = Fernet(key)
timezone = timezone(ozone)
def setTime(t):
stamptime = int(float(t))
GMT0 = pytz.utc.localize(datetime.utcfromtimestamp(stamptime))
return GMT0.astimezone(timezone).strftime(time_format)
j = 0
while True:
r = requests.get(url, cookies=cookies_dict).text
message = json.loads(r)
message_sz = len(message)
if message_sz == 0:
print("Looks like there are no message")
break
for msg in message[j:]:
local_time = setTime(msg['id'])
if msg['nam'] == '<<<>>>':
print(f"{local_time} :: {msg['nam']} :: {msg['msg']}")
else:
decMessage = fernet.decrypt(bytes(msg['msg'], "utf-8")).decode()
print(f"{local_time} :: {msg['nam']} :: {decMessage}")
j = message_sz
sleep(t)
I would not suggest using this checking and going to website method, but you could thread the while loops to go at the same time. And you could update tk when you want using tk.update().
You could get Data from vars that the threaded loops are setting and use them in your single tk window.
use multi threading .or else load data desperately

How to make sure the logged message goes to a new line?

I'm trying to make my own logging system because I don't like Python's one, but I ran into a small problem. Whenever I log two or more things, only the last log is written. Example - I log 'code initialized' at the start of the program. Then, I log 'exiting'. The result in the log file is only 'exiting' How do I fix this? Here is my code.
File 1.
from functions import *
from variables import *
try:
open('key.txt', "r")
key = True
except FileNotFoundError:
key = False
if check_internet():
x = status_boot[0]
elif not check_internet():
x = status_boot[1]
log("archer initialized")
if key:
print("archer status: " + x)
elif not key:
print(status_boot[4])
File 2.
from datetime import datetime
from variables import *
import requests
def time():
now = datetime.now()
return now.strftime("%H:%M:%S")
def check_internet():
timeout = 5
try:
_ = requests.get(url, timeout=timeout)
return True
except requests.ConnectionError:
return False
def log(m):
write = open('archerlog.txt', 'w+')
return write.write(f'[{time()}] archer: {m}\n')
File 3.
url = "http://www.google.com/"
status_boot = ["online", "offline", "key invalid", "error", "Error: Key not accessible!"]
x = status_boot[3]

Changing Bitcoin Wallet Address Range for Plutus.py

I am working with the following script from https://github.com/Isaacdelly/Plutus/blob/master/plutus.py
The script works for wallet addresses in the 2^160 range. I am curious where in the script I can change this to look at the 2^128 range or 2^n range. Would it be possible to even have a window? Like 2^0 - 2^100?
Not trying to do anything malicious, just trying to get data to show that even selecting ranges is futile due to the large number of addresses.
# Plutus Bitcoin Brute Forcer
# Made by Isaac Delly
# https://github.com/Isaacdelly/Plutus
try:
import sys
import os
import time
import hashlib
import binascii
import multiprocessing
from multiprocessing import Process, Queue
from multiprocessing.pool import ThreadPool
import threading
import base58
import ecdsa
import requests
except ImportError:
import subprocess
subprocess.check_call(["python", '-m', 'pip', 'install', 'base58==1.0.0'])
subprocess.check_call(["python", '-m', 'pip', 'install', 'ecdsa==0.13'])
subprocess.check_call(["python", '-m', 'pip', 'install', 'requests==2.19.1'])
import base58
import ecdsa
import requests
def generate_private_key():
return binascii.hexlify(os.urandom(32)).decode('utf-8')
def private_key_to_WIF(private_key):
var80 = "80" + str(private_key)
var = hashlib.sha256(binascii.unhexlify(hashlib.sha256(binascii.unhexlify(var80)).hexdigest())).hexdigest()
return str(base58.b58encode(binascii.unhexlify(str(var80) + str(var[0:8]))), 'utf-8')
def private_key_to_public_key(private_key):
sign = ecdsa.SigningKey.from_string(binascii.unhexlify(private_key), curve = ecdsa.SECP256k1)
return ('04' + binascii.hexlify(sign.verifying_key.to_string()).decode('utf-8'))
def public_key_to_address(public_key):
alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
count = 0; val = 0
var = hashlib.new('ripemd160')
var.update(hashlib.sha256(binascii.unhexlify(public_key.encode())).digest())
doublehash = hashlib.sha256(hashlib.sha256(binascii.unhexlify(('00' + var.hexdigest()).encode())).digest()).hexdigest()
address = '00' + var.hexdigest() + doublehash[0:8]
for char in address:
if (char != '0'):
break
count += 1
count = count // 2
n = int(address, 16)
output = []
while (n > 0):
n, remainder = divmod (n, 58)
output.append(alphabet[remainder])
while (val < count):
output.append(alphabet[0])
val += 1
return ''.join(output[::-1])
def get_balance(address):
try:
response = requests.get("https://bitaps.com/api/address/" + str(address))
return int(response.json()['balance'])
except:
return -1
def data_export(queue):
while True:
private_key = generate_private_key()
public_key = private_key_to_public_key(private_key)
address = public_key_to_address(public_key)
data = (private_key, address)
queue.put(data, block = False)
def worker(queue):
while True:
if not queue.empty():
data = queue.get(block = True)
balance = get_balance(data[1])
process(data, balance)
def process(data, balance):
private_key = data[0]
address = data[1]
if (balance == 0):
print("{:<34}".format(str(address)) + ": " + str(balance))
if (balance > 0):
file = open("plutus.txt","a")
file.write("address: " + str(address) + "\n" +
"private key: " + str(private_key) + "\n" +
"WIF private key: " + str(private_key_to_WIF(private_key)) + "\n" +
"public key: " + str(private_key_to_public_key(private_key)).upper() + "\n" +
"balance: " + str(balance) + "\n\n")
file.close()
def thread(iterator):
processes = []
data = Queue()
data_factory = Process(target = data_export, args = (data,))
data_factory.daemon = True
processes.append(data_factory)
data_factory.start()
work = Process(target = worker, args = (data,))
work.daemon = True
processes.append(work)
work.start()
data_factory.join()
if __name__ == '__main__':
try:
pool = ThreadPool(processes = multiprocessing.cpu_count()*2)
pool.map(thread, range(0, 10))
except:
pool.close()
exit()
Thank you
You seem to be misunderstanding the purpose of the 2^160 bit range.
Each standard bitcoin address is tied to the HASH160 of the public key. A HASH160 is 160 bits long, which is why your search space is 2^160. If you are able to find two private keys for which the HASH160 of the public keys are equal, any of those two private keys can spend coins sent to that address.
Searching a smaller space does not make sense since you are no longer searching for bitcoin addresses. If you just want to search random hash functions, then you simply need to replace RIPEMD160 hash function with another one that has an output in whatever bitsize you wish to search.
Note that if you do that, the rest of the code talking about checking balances etc. will be of no use, since your output will no longer be a bitcoin address.

Unicode-objects Array Python 3.7

This is my second python project (I'm not experienced) and I seem to be struggling with a problem regarding encoding. I believe the problem to be existing within an array. I have tried pre-encoding the inputs as well as the '297aae72' that I took using a similar resolution that I found here .encode('utf-8') but I experience the same error.
I believe this is a hashing problem due to an encoding conflict within the array that is being constructed.
This file is speed test.py, where I believe the error to be found.
import hashlib
from hashlib import md5
import urllib.request, urllib.error, urllib.parse
import sys
from urllib.parse import parse_qs
import functions
ping = 16
accuracy = 8
server = functions.setup()
def speed_test(up, down):
get_data = [
'download=%s' % down,
'ping=%s' % ping,
'upload=%s' % up,
'promo=',
'startmode=%s' % 'pingselect',
'recommendedserverid=%s' % server,
'accuracy=%s' % 8,
'serverid=%s' % server,
'hash=%s' % md5('%s-%s-%s-%s' %
(ping, up, down, '297aae72')
).hexdigest()]
request = urllib.request.Request('http://www.speedtest.net/api/api.php',
data='&'.join(get_data))
request.add_header('Referer', 'http://c.speedtest.net/flash/speedtest.swf')
connection = urllib.request.urlopen(request)
response = connection.read()
response_code = connection.code
connection.close()
if int(response_code) != 200:
print('There was an issue submitting data')
sys.exit(1)
qs_args = parse_qs(response)
result_id = qs_args.get('resultid')
if not result_id or len(result_id) != 1:
print('No speedtest image found?')
sys.exit(1)
print(('Speedtest Results: http://www.speedtest.net/result/%s.png' % result_id[0]))
down_input = input("Please enter your download speed (EX: 375.520): ")
down_input = down_input.replace(".", "")
up_input = input("Please enter your upload speed (EX: 375.520): ")
up_input = up_input.replace(".", "")
speed_test(up_input, down_input)
This file is funcitons.py
import math
import urllib.request, urllib.error, urllib.parse
import os
import time
from xml.dom import minidom as DOM
def calculate_distance(origin, destination):
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
latitude = math.radians(lat2 - lat1)
longitude = math.radians(lon2 - lon1)
a = (math.sin(latitude / 2) * math.sin(latitude / 2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(longitude / 2)
* math.sin(longitude / 2))
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
destination = radius * c
return destination
def get_closest_servers(client, complete=False):
connection = urllib.request.urlopen('http://speedtest.net/speedtest-servers.php')
server_xml = connection.read()
if int(connection.code) != 200:
return None
connection.close()
root = DOM.parseString(server_xml)
servers = {}
for server in root.getElementsByTagName('server'):
attrib = dict(list(server.attributes.items()))
d = calculate_distance([float(client['lat']), float(client['lon'])],
[float(attrib.get('lat')), float(attrib.get('lon'))])
attrib['d'] = d
if d not in servers:
servers[d] = [attrib]
else:
servers[d].append(attrib)
closest = []
for d in sorted(servers.keys()):
for s in servers[d]:
closest.append(s)
if len(closest) == 5 and not complete:
break
else:
continue
break
del servers
del root
return closest
def get_best_server(servers):
results = {}
for server in servers:
cum = 0
url = os.path.dirname(server['url'])
for i in range(0, 3):
uh = urllib.request.urlopen('%s/latency.txt' % url)
start = time.time()
text = uh.read().strip()
total = time.time() - start
if int(uh.code) == 200 and text == 'test=test':
cum += total
else:
cum += 3600
uh.close()
avg = round((cum / 3) * 1000000, 3)
results[avg] = server
fastest = sorted(results.keys())[0]
best = results[fastest]
best['latency'] = fastest
return best
def get_config():
uh = urllib.request.urlopen('http://www.speedtest.net/speedtest-config.php')
config_xml = uh.read()
if int(uh.code) != 200:
return None
uh.close()
root = DOM.parseString(config_xml)
config = {
'client': extract_tag_name(root, 'client'),
'times': extract_tag_name(root, 'times'),
'download': extract_tag_name(root, 'download'),
'upload': extract_tag_name(root, 'upload')}
del root
return config
def extract_tag_name(dom, tag_name):
elem = dom.getElementsByTagName(tag_name)[0]
return dict(list(elem.attributes.items()))
def setup():
print('Configuring server, one moment.')
configs = get_config()
closest_server = get_closest_servers(configs['client'])
best = get_best_server(closest_server)
return best['id']
This is the error I receive when the application is executed.
Traceback (most recent call last):
File "speedtest.py", line 54, in <module>
speed_test(up_input, down_input)
File "speedtest.py", line 25, in speed_test
(ping, up, down, '297aae72')
TypeError: Unicode-objects must be encoded before hashing
Am I missing something here? After encoding the variables there is no change to the error in my instance.
Thanks for any help that can be provided.
This doesn't have anything to do with "arrays"; you are being confused by the fact that you're trying to do everything inline when you define get_data. Actually, the problem is your call to md5(); as the error says, you can't pass a unicode string to that, you need to pass bytes. So, just encode the string:
hash = md5(('%s-%s-%s-%s' % (ping, up, down, '297aae72')).encode('utf-8')).hexdigest()

Python replace statement

I'm pretty new to Python but need to patch this glitch/exploit in an addon service.
My code looks like this:
#!/usr/bin/env python
import subprocess
import sys
import os
import yaml
from xml.dom import minidom
sys.path.append('/scripts')
import createvhosts
doc = minidom.parse(sys.stdin)
param0taglist = doc.getElementsByTagName('param0')
param1taglist = doc.getElementsByTagName('param1')
param0 = param0taglist[0].childNodes[0].toxml()
param1 = param1taglist[0].childNodes[0].toxml()
domain = param0 + '.' + param1
usertaglist = doc.getElementsByTagName('USER')
user = usertaglist[0].childNodes[0].toxml()
f = open('/var/cpanel/userdata/' + user + '/main')
ydata = yaml.load(f)
f.close()
sublist = ydata['sub_domains']
addondict = ydata['addon_domains']
parkedlist = ydata['parked_domains']
mainlist = ydata['main_domain']
serverip = createvhosts.getmainip()
if len(sublist) != 0:
slcont = 0
while slcont < len(sublist):
domain = sublist[slcont]
docroot, yip, alias = createvhosts.getvars(sublist[slcont])
if yip == serverip:
createvhosts.writeconfshared(user, domain, docroot, yip, alias)
else:
createvhosts.writeconfded(user, domain, docroot, yip, alias)
slcont = slcont + 1
proc = subprocess.Popen("/etc/init.d/nginx restart > /dev/null 2>&1", shell=True)
The issue is when you add a subdomain in CPanel with * it will crash the server because apparently nginx does not seem to allow and accept that. What I need help doing is figuring out how to replace/block * so it does not go in.
Does something like Param0.find( "*" ) !=-1 work?
The construct you're looking for is char in string.
>>> s = 'ab*de'
>>> '*' in s
True
Put this in a conditional and you've got what you want - something like:
if '*' in param0:
raise ValueError("Can't use '*'!")
This, along with a comprehensive list of the methods available on strings to do more involved work, is documented in the official docs, under Built-in Types.

Categories