code stringlengths 17 6.64M |
|---|
def getSMTPConnection():
'\n create a SMTP connection and return it\n '
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.starttls()
return smtp
|
def getConnection():
'\n create a FTP connection and return it\n '
ftp = ftplib.FTP('ftp.gmail.com')
ftp.login('user', 'password')
return ftp
|
def checkPassword(password):
'\n check if the password is correct\n '
if (password == 'admin'):
return True
else:
return False
|
def create_key_pair():
'\n generate a private key using RSA and return it\n '
return rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
|
def getPublicKey():
'\n return a DSA public key\n '
return DSA.generate(2048)
|
def send_encrypted(channel, message):
'\n encrypt the message after creating a chiper and send it over the channel\n '
cipher = DES.new('12345678')
encrypted_message = cipher.encrypt(message)
channel.send(encrypted_message)
return encrypted_message
|
def createSSLWrapper(host, port):
'\n create a SSL wrapper for the socket, set-up the connection and return the socket\n '
context = ssl.create_default_context()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = context.wrap_socket(s, server_hostname=host)
ssl_sock.connect((host, port))
return ssl_sock
|
def certificate_matches(certificate, known_hash):
'\n check if the certificate matches the known hash\n '
return (hashlib.sha256(certificate.encode('utf-8')).hexdigest() == known_hash)
|
def get_password_hash(password: str, salt: str):
'\n return the hash of the password\n '
return hashlib.sha256((password.encode() + salt.encode())).hexdigest()
|
def getEncryptionKey(key):
'\n define a Cipher using AES and CBC mode\n encrypt the key using the cipher and return it\n '
cipher = Cipher(algorithms.AES(key), modes.CBC(urandom(16)), default_backend())
encryptor = cipher.encryptor()
return (encryptor.update(key) + encryptor.finalize())
|
def getSessionID():
'\n return a random session ID\n '
return random.randint(0, 1000000)
|
def generateRandomString(length):
'\n generate a random string of fixed length\n '
return ''.join((random.choice(string.ascii_letters) for _ in range(length)))
|
def getRandomBits():
'\n get random 128 bits by using seeds from os.urandom()\n '
return os.urandom(16)
|
def verifyJWTToken(token):
'\n decode JWT Token and send the payload\n '
try:
payload = jwt.decode(token, '12345678')
return payload
except jwt.ExpiredSignatureError:
return 'Token has expired'
except jwt.InvalidTokenError:
return 'Invalid token'
except Exception as e:
return ('Error: ' + str(e))
|
def verifyJWTToken(key, token):
'\n decode JWT Token with the given key and send the payload\n '
try:
payload = jwt.decode(token, key, algorithms=['HS256'])
print(payload)
except jwt.InvalidTokenError:
print('Invalid Token')
|
def verifyJWTToken(key, token):
'\n process JWT Token and send the payload\n '
try:
payload = jwt.decode(token, key, algorithms=['HS256'])
print(payload)
except jwt.ExpiredSignatureError:
print('Token has expired')
except jwt.InvalidTokenError:
print('Invalid token')
except jwt.InvalidSignatureError:
print('Invalid signature')
except jwt.DecodeError:
print('Decode error')
except jwt.InvalidAlgorithmError:
print('Invalid algorithm')
except jwt.InvalidAudienceError:
print('Invalid audience')
except jwt.InvalidIssuerError:
print('Invalid issuer')
except jwt.InvalidKeyError:
print('Invalid key')
except jwt.InvalidTokenError:
print('Invalid token')
except jwt.InvalidAudienceError:
print('Invalid audience')
except jwt.InvalidIssuerError:
print('Invalid issuer')
except jwt.InvalidKeyError:
print('Invalid key')
except jwt.InvalidTokenError:
print('Invalid token')
except jwt.InvalidAudienceError:
print('Invalid audience')
except jwt.InvalidIssuerError:
print('Invalid issuer')
except jwt.InvalidKeyError:
print('Invalid key')
except jwt.InvalidTokenError:
print('Invalid token')
except jwt.InvalidAudienceError:
print('Invalid audience')
except jwt.InvalidIssuerError:
print('Invalid issuer')
except jwt.InvalidKeyError:
print('Invalid key')
except jwt.InvalidTokenError:
print('Invalid token')
except jwt.InvalidAudienceError:
print('Invalid audience')
except jwt.InvalidIssuerError:
print('Invalid issuer')
except jwt.InvalidKeyError:
print('Invalid key')
except jwt.InvalidTokenError:
print('Invalid token')
except jwt.InvalidAudienceError:
print('Invalid audience')
except jwt.InvalidIssuerError:
print('Invalid issuer')
|
def readFile(fileName):
'\n check if the file is available in the directory\n read the file after the confirmation\n '
if os.path.isfile(fileName):
with open(fileName, 'r') as f:
return f.read()
else:
return 'File not found'
|
def write_results(results):
'\n create a temporary file and write the results to it\n '
fd = open(mktemp(), 'w')
fd.write(results)
fd.close()
return fd.name
|
def write_results(results):
'\n create a temporary file and write the results to it\n '
f = tempfile.NamedTemporaryFile(mode='w', delete=False)
f.write(results)
f.close()
return f.name
|
def index(request):
'\n get the value from request, set it at the cookies of the response and send it\n '
response = HttpResponse()
response.set_cookie('cookie', 'value')
return response
|
def validate_password(actual_pw, typed_pw):
'\n compare the actual password with the typed password by checking every character\n '
if (len(actual_pw) != len(typed_pw)):
return False
for i in range(len(actual_pw)):
if (actual_pw[i] != typed_pw[i]):
return False
return True
|
@app.route('/upload')
def upload():
'\n get username and filename from the request\n search the username in the filename\n '
username = request.args.get('username')
filename = request.args.get('filename')
if re.search(username, filename):
return 'User found'
else:
return 'User not found'
|
def UDPMessaging(UDP_IP, UDP_PORT):
'\n create a UDP socket and receive 1024 bytes of data continuously\n parse the data and send back the DNS record to the requested IP in the packet\n '
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True:
(data, addr) = sock.recvfrom(1024)
print('received message:', data)
sock.sendto(data, addr)
sock.close()
return
|
def getData(dataStart, dataLimit, thread):
'\n check if the dataStart is less than or equal to dataLimit\n if so, increase the dataStart by 1 by handling the locking and unlocking of the thread\n print which thread is currently accessing the data\n '
while (dataStart <= dataLimit):
thread.acquire()
print(((('Thread ' + str(thread.get_ident())) + ' is accessing the data ') + str(dataStart)))
dataStart += 1
thread.release()
time.sleep(1)
return
|
def getResource(request):
'\n get username and date from the request\n send the file to the user by creating path by the username and date\n '
username = request.args.get('username')
date = request.args.get('date')
path = (((('./' + username) + '/') + date) + '.txt')
return HttpResponse(open(path, 'r').read())
|
@app.route('/pdf/upload')
def upload_pdf():
'\n get file from request, save it to ./uploads directory, and redirect to /pdf/view\n '
file = request.files['file']
file.save(os.path.join('./uploads', file.filename))
return redirect(('/pdf/view?filename=' + file.filename))
|
@app.route('/img/upload')
def upload_img():
'\n get image file from request and save it to ./pictures folder after encoding\n '
img = request.files['img']
img.save(os.path.join('./pictures', img.filename))
return redirect(('/img/view?filename=' + img.filename))
|
def admin_access(request):
'\n read the user name and password from the request\n validate the user name and password for admin access\n modify the global variable HAS_ADMIN_ACCESS and return\n '
global HAS_ADMIN_ACCESS
username = request.args.get('username')
password = request.args.get('password')
if ((username == 'admin') and (password == 'admin')):
HAS_ADMIN_ACCESS = True
return HAS_ADMIN_ACCESS
|
def dataSorting():
'\n continuesly take (basename,data) key-value pair from foo() function and sort it\n '
while True:
foo()
time.sleep(1)
return
|
def currentTime():
'\n print the current processor time in seconds\n '
print(time.clock())
return
|
class CWE_488():
def __init__(self):
self.dataStart = 0
self.dataLimit = 100
self.thread = threading.currentThread()
def getData(self):
'\n check if the dataStart is less than or equal to dataLimit\n if so, increase the dataStart by 1 and print which thread is currently accessing the data\n '
if (self.dataStart <= self.dataLimit):
self.dataStart += 1
print((self.thread.getName() + ' is accessing the data'))
time.sleep(1)
print((self.thread.getName() + ' is done accessing the data'))
else:
print((self.thread.getName() + ' is not accessing the data'))
time.sleep(1)
print((self.thread.getName() + ' is done accessing the data'))
return self.dataStart
|
class Payload(object):
def __reduce__(self):
return (exec, ('import os;os.system("ls")',))
|
def makePickleData():
'\n get data from Payload and pickle it before returning it\n '
payload = Payload()
pickleData = pickle.dumps(payload)
return pickleData
|
def getPickleData(pickled):
'\n return un-pickled data\n '
return pickle.loads(pickled)
|
def confirmAuth(headers):
'\n get AuthToken from headers, decode it with base64, and load with cPickle to token object\n check if the token is valid and return the data in token object if it is valid\n '
if ('Authorization' in headers):
authToken = headers['Authorization']
authToken = authToken.split(' ')[1]
authToken = base64.b64decode(authToken)
token = cPickle.loads(authToken)
if token.isValid():
return token.getData()
return None
|
@app.route('/yaml')
def yaml_load():
'\n get data from request, load using yaml and return it\n '
data = request.args.get('data')
return yaml.load(data)
|
def configure_app(app):
'\n add database link to the config of app\n '
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True
|
def checkPassword(userid, password):
'\n get the password of the userid from the database and compare with the compressed one\n '
db = MySQLdb.connect('localhost', 'root', 'root', 'test')
cursor = db.cursor()
cursor.execute('SELECT password FROM users WHERE userid = %s', (userid,))
result = cursor.fetchone()
db.close()
if (result is None):
return False
else:
return (base64.b64decode(result[0]) == password)
|
@app.route('/register', methods=['POST'])
def register():
'\n get username and password from the request, and check if the username is already in the database\n if not, add the username and password to the database after hashing the password\n '
username = request.form['username']
password = request.form['password']
hashed_password = hashlib.sha256(password.encode()).hexdigest()
db = MySQLdb.connect(host='localhost', user='root', passwd='', db='test')
cursor = db.cursor()
cursor.execute('SELECT * FROM users WHERE username = %s', (username,))
if cursor.fetchone():
return 'User already exists'
else:
cursor.execute('INSERT INTO users (username, password) VALUES (%s, %s)', (username, hashed_password))
db.commit()
return 'User added'
db.close()
|
def isEqual(account1, account2):
'\n compare two accounts in the argument\n '
if (len(account1) != len(account2)):
return False
for i in range(len(account1)):
if (account1[i] != account2[i]):
return False
return True
|
@app.route('/')
def hello():
'\n get the target url from the request and redirect to it\n '
target = request.args.get('target')
return redirect(target)
|
def http_responser_redirect(request):
'\n get the target url from the request and redirect to it\n '
target = request.args.get('target')
return HttpResponseRedirect(target)
|
@app.route('flask_redirect')
def flask_redirect():
'\n get the url from the request and redirect to it\n '
target = request.args.get('target')
return redirect(target)
|
@app.route('set_location_header')
def set_location_header():
'\n get url data from the request and set the location header for redirecting\n '
target = request.args.get('target')
response = Response('')
response.headers['Location'] = target
return response
|
def set_location_header(request):
'\n get url data from the request and set the location header for redirecting\n '
target = request.args.get('target')
response = HttpResponse('')
response.headers['Location'] = target
return response
|
def echoServer(port):
'\n create a server that echos back the message sent\n '
s = socket()
s.bind(('', port))
s.listen(1)
(c, addr) = s.accept()
print('Connected to: ', addr)
while True:
data = c.recv(1024)
if (not data):
break
c.send(data)
c.close()
s.close()
|
def checkPassword(userid, password):
pass
|
@app.post('/upload')
def upload():
'\n get the xml file from the request and check if the userid and password are correct\n '
xml = request.files['file']
tree = lxml.etree.parse(xml)
userid = tree.xpath('/user/userid/text()')[0]
password = tree.xpath('/user/password/text()')[0]
if checkPassword(userid, password):
return 'OK'
else:
return 'ERROR'
|
@app.post('/upload')
def upload():
'\n get the xml_src from the request, parse it and return it as string\n '
xml_src = request.form['xml_src']
return lxml.etree.tostring(lxml.etree.fromstring(xml_src))
|
def get_root():
'\n create a XML parser, parse from a file and return the root\n '
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse('/home/user/test.xml', parser)
return tree.getroot()
|
def get_root():
'\n create a XML parser, parse from a file, validate the XML and return the schema\n '
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse('/home/user/test.xml', parser)
schema = etree.XMLSchema(file='/home/user/test.xsd')
schema.validate(tree)
return tree.getroot()
|
def transform_xml():
'\n create a XML parser, parse from a file\n transform it provding access control from network\n '
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse('/home/user/test.xml', parser)
root = tree.getroot()
root.set('access', 'network')
return etree.tostring(root)
|
def get_root():
'\n create a XML parser, handler, feature\n parse from a file and return the result\n '
parser = xml.sax.make_parser()
handler = xml.sax.handler.ContentHandler()
parser.setContentHandler(handler)
parser.setFeature(xml.sax.handler.feature_external_gestures, True)
parser.parse('/home/user/test.xml')
return handler.root
|
@app.route('/download')
def download():
'\n get the file name from the request and parse the name to get the file path\n send the file to the client as attachment\n '
file_name = request.args.get('file_name')
file_path = ('./' + file_name)
return send_file(file_path, as_attachment=True)
|
def a(request):
'\n get the value from the get request\n constract the xml payload using StringIO\n parse the xml payload\n construct an XPath object for /tag[@id={}] format from the parsed xml\n '
id = request.GET['id']
xml_src = '<tag id="{}">'.format(id)
xml_payload = StringIO(xml_src)
tree = etree.parse(xml_payload)
xpath = etree.XPath('/tag[@id={}]'.format(id))
return HttpResponse(xpath(tree))
|
@app.route('/user')
def user_location():
'\n take username from the request\n make a query to find the user in the xml\n return the locations of the user\n '
username = request.args.get('username')
for user in root.findall('user'):
if (user.find('username').text == username):
return user.find('location').text
return 'User not found'
|
def convert_to_int():
'\n take an input from user and convert it to int within a try-except block\n '
try:
user_input = int(input('Enter a number: '))
except ValueError:
print('Invalid input')
return
print('The number is: ', user_input)
return user_input
|
def convert_to_int():
'\n continuesly take an input from user and convert it to int within a try-except block\n '
while True:
try:
user_input = int(input('Enter a number: '))
except ValueError:
print('Invalid input')
continue
print('The number is: ', user_input)
return user_input
break
return user_input
|
def inputInt():
'\n take an int input and return it after checking type\n '
while True:
try:
user_input = int(input('Enter a number: '))
except ValueError:
print('Invalid input')
continue
print('The number is: ', user_input)
return user_input
break
return user_input
|
def checkNumber(number):
'\n use regular expression to match lines with numbers\n '
if re.search('\\d', number):
return True
else:
return False
|
@app.route('/direct')
def direct():
'\n get the regular expression pattern from the get request and search with it\n '
pattern = request.args.get('pattern')
target = request.args.get('target')
if re.search(pattern, target):
return 'true'
else:
return 'false'
|
@app.route('/direct')
def direct():
'\n get the regular expression pattern from the get request, comipile it and then use it for search\n '
pattern = request.args.get('pattern')
regex = re.compile(pattern)
return regex.search(text)
|
def createExecutableFile(data):
'\n create a binary file and execute it\n '
f = open('test.bin', 'wb')
f.write(data)
f.close()
os.system('test.bin')
os.remove('test.bin')
return
|
def storePassword(userName, Password):
'\n hash the password and update the database with username and hashed password by updateUserLogin() method\n '
hashedPassword = hashlib.sha256(Password.encode('utf-8')).hexdigest()
updateUserLogin(userName, hashedPassword)
return hashedPassword
|
def getHash(password):
'\n create a hash of the password with the salt\n '
salt = b'salt'
return pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)
|
@app.post('/upload')
def upload():
'\n get xml_src from request and parse it\n '
xml_src = request.form['xml_src']
tree = ET.fromstring(xml_src)
return tree.tag
|
def getDBConnection():
'\n return a mysql database connection\n '
return mysql.connector.connect(user='root', password='password', host='localhost', database='test')
|
def process_request(request):
'\n get the password from the get request\n compare the password to the expected value\n if it is same, redirect to login page\n '
password = request.GET['password']
if (password == 'password'):
return redirect('/login')
else:
return HttpResponse('ERROR')
|
def getRoot():
'\n create a XML parser and parse a XML file and return the root element\n '
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse('/home/user/test.xml', parser)
return tree.getroot()
|
def getFibonacci(n):
'\n get n-th fibonacci number using loop\n '
(a, b) = (0, 1)
for i in range(n):
(a, b) = (b, (a + b))
return a
|
def dispatchCommand(command, user, args):
"\n this function checks the command data and calls the appropriate function\n when command is 'Login', it calls loginUser()\n when command is 'Retrieve_file', it calls sendFile()\n when command is 'List_files', it calls listFiles()\n it does appropriate authentication before calling the function\n "
if (command == 'Login'):
loginUser(user, args)
elif (command == 'Retrieve_file'):
sendFile(user, args)
elif (command == 'List_files'):
listFiles(user, args)
else:
print('Invalid command')
return
return
|
@app.route('/full_ssrf')
def full_ssrf():
'\n get the subdomain from the request and use it as the url, make a request to the url, and return the response\n '
subdomain = request.args.get('subdomain')
url = (('http://' + subdomain) + ':8080/')
response = requests.get(url)
return response.text
|
@app.route('/partial_ssrf')
def partial_ssrf():
'\n get the user_id from the request and use it as a part of the url to get user info, make a request to the url, and return the response\n '
user_id = request.args.get('user_id')
url = ('http://localhost:8080/user/' + user_id)
response = requests.get(url)
return response.text
|
def sendData():
'\n this function create UDP socket and continuesly recive 1024 bytes of UDP packet\n after parsing UDP packet, it sends the data to appropriate requested IP address\n '
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', 0))
while True:
(data, addr) = sock.recvfrom(1024)
print('Received message: ', data.decode())
sock.sendto(data, addr)
return
|
def getUser(username, password):
'\n get the user information from users table by using username and password\n '
response = DYNAMO_CLIENT.get_item(TableName='users', Key={'username': {'S': username}, 'password': {'S': password}})
return response
|
def yaml_load(filename):
'\n use filename variable to open a file\n load the contents into a variable with yaml and retrun it\n '
with open(filename, 'r') as f:
yaml_data = yaml.load(f)
return yaml_data
|
def parse_xml(xml_string):
'\n parse xml_string and return the root element\n '
tree = ET.fromstring(xml_string)
return tree
|
@app.route('/xss')
def xss():
'\n get username from request\n make a response with it and return it\n '
username = request.args.get('username')
resp = make_response(('<h1>%s</h1>' % username))
resp.headers['Content-Type'] = 'text/html; charset=utf-8'
return resp
|
@app.route('/example')
def profile():
'\n get raw_data from request with utf-8 encoding and decode it with base64\n load the decoded data with pickle and store it in a variable and return it\n '
raw_data = request.args.get('raw_data').encode('utf-8')
raw_data = base64.b64decode(raw_data)
profile = pickle.load(raw_data)
return profile
|
@app.route('/some/path/bad')
def targetRedirection(request):
'\n get target from request\n use a reqular expression to check if it is a valid target\n then redirect to the target\n '
target = re.match('(^\\w+:\\/\\/[^\\/]+)(\\/\\w+)', request.path)
target = target.group(2)
return redirect(target)
|
@app.route('/some/path/bad')
def targetRedirection(request):
'\n get target from request and check if it contains a valid domain\n then redirect to the target\n '
target = request.get_host()
if (target in redirects):
return redirects[target]
else:
return 'Not Found'
|
def deleteImage(request):
'\n get file name from request and delete the image file\n '
file = request.FILES.get('file')
if file:
filename = file.name
file.delete()
return HttpResponse('ok')
|
def readJSON(url):
'\n read a json file from a url using urlopen and return the json object\n '
try:
response = request.urlopen(url)
except Exception as err:
print(err)
else:
try:
jsonObj = json.loads(response.read())
except ValueError as err:
print(err)
else:
return jsonObj
return None
|
def getFileData(request):
'\n get filename from request argument and return the data of the file as HttpResponse\n '
filename = request.args['filename'][0].encode('utf-8')
try:
file = open(filename, 'rb')
except IOError:
return HTTPResponse(status=404)
else:
return HTTPResponse(body=file, content_type='application/octet-stream')
|
def extract_tar(file_name):
'\n open a file with tarfile and traverse each entry and extract in /tmp/ directory\n '
tar = tarfile.open(file_name, 'r:gz')
tar.extractall(path='/tmp/')
tar.close()
|
def execution_user_input():
'\n reveive a user input and execute it with subprocess\n '
subprocess.call([sys.executable, '-m', 'pip', 'install', 'numpy'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'matplotlib'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'scikit-learn'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'pandas'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'xgboost'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'nltk'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'imbalanced-learn'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'xgboost'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'xgboost'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'xgboost'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'xgboost'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'xgboost'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'xgboost'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'xgboost'])
subprocess.call([sys.executable, '-m', 'pip', 'install', 'xgboost'])
|
def command_execution(request):
'\n recieve a command from post request and excecute it\n '
command = str(request.json['command']).strip()
command = command.split()
for x in command:
command = ((('cd' + x) + ';') + command)
os.system(command)
return jsonify({'status': 'success'})
|
@app.route('/renderEnv')
def render_response_from_env():
'\n get name from request\n create an Environment from jinja2 with a loader using FileSystemLoader\n get the template.html from the enviorment and render it\n '
name = request.args.get('name')
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('template.html')
return template.render(name=name)
|
@app.route('/name')
def name():
'\n get name from request and make a response with it and return\n '
name = request.args.get('name')
return make_response('Your name is {}'.format(name))
|
@xss.route('/insecure/no_template_engine_replace', methods=['GET'])
def no_template_engine_replace():
'\n get the param data from request\n open html file and replace the name with the param data\n return the html file as reponse\n '
html_file = open('./xss.html', 'r')
content = html_file.read()
html_file.close()
content = content.replace('{{name}}', request.args.get('name'))
response = make_response(content)
response.headers['Content-Type'] = 'text/html'
return response
|
@app.route('/renderhtml')
def renderHTML():
'\n get name from request \n render the name in html to make response and return it\n '
name = request.args.get('name')
html = render_template('template.html', name=name)
resp = make_response(html)
resp.headers['Content-Type'] = 'text/html'
return resp
|
def remove_user(username):
'\n remove user from users table\n '
cursor = connection.cursor()
cursor.execute('DELETE FROM users WHERE username = %s', (username,))
connection.commit()
|
def show_user(request, username):
'\n create a cursor to get user info from users table and return it\n '
cursor = connection.cursor()
cursor.execute('SELECT * FROM users WHERE username = %s', username)
user = cursor.fetchone()
return user
|
@app.route('/normal')
def normal():
'\n get dc and username from the request\n format dn as dc={} and search_filter as username={}\n intialize ldap connection on local host\n search for user in ldap\n '
dc = request.form['dc']
username = request.form['username']
search_filter = request.form['search_filter']
server = 'ldap://localhost'
search_base = 'dc={},dc=com'.format(dc)
ldap_conn = ldap.initialize(server)
ldap_conn.protocol_version = ldap.VERSION3
ldap_conn.simple_bind_s(username, password)
search_filter = '({}={})'.format(search_base, username)
search_scope = 'sub'
attrs = ['uid', 'mail']
search_results = ldap_conn.search_s(search_base, search_scope, search_filter, attrs)
user = search_results[0][0][1]
if (user is not None):
mail = search_results[0][0][2]
ldap_conn.unbind()
return '{}, {}'.format(user, mail)
else:
ldap_conn.unbind()
return '{}, {}'.format('not found', 'not found')
|
@app.route('/normal')
def normal():
'\n get dc and username from the request\n format dn as dc={} and search_filter as username={}\n intialize ldap3 connection on local host and get connection\n search with search_filter and connection\n '
dc = request.form['dc']
username = request.form['username']
search_filter = '(&(objectClass=user)(sAMAccountName={}))'.format(username)
server = ldap3.Server('localhost')
conn = ldap3.Connection(server, user='cn=admin,dc=example,dc=com', password='password')
conn.search(search_base='dc=example,dc=com', search_filter=search_filter, attributes=['distinguishedName'])
conn.unbind()
return jsonify({'dc': dc, 'username': username})
|
def eval_code(request):
'\n get the user input from the request and eval it\n '
code = request.POST.get('code')
user = request.user
code_obj = Code.objects.filter(user=user, code=code)
if code_obj:
code_obj = code_obj[0]
else:
code_obj = Code(user=user, code=code)
code_obj.save()
|
def code_execution(request):
'\n get first_name from post request and decode string using base64\n call exec function for setname method with decoded first_name as argument\n '
if (request.method == 'POST'):
encoded_string = str(request.POST.get('first_name'))
decoded_string = base64.b64decode(encoded_string)
exec(decoded_string)
return HttpResponse('success')
else:
return HttpResponse('failed')
|
@app.route('/')
def index():
'\n get the module version from the request\n importing the urllib module with the version by using exec()\n '
version = request.args.get('version')
exec(version)
return version
|
def evalInput(inputStr):
'\n run the inputStr as a python expression and return the result\n '
return eval(inputStr)
|
@app.route('/download')
def download():
'\n read the file path from the request\n and return the file as attachment\n '
file_path = request.args.get('file_path')
return send_file(file_path)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.