code stringlengths 17 6.64M |
|---|
def getHash(password):
'\n create a hash of the password with the salt\n '
salt = getSalt()
return pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 10000)
|
@app.post('/upload')
def upload():
'\n get xml_src from request and parse it\n '
xml_src = request.form['xml_src']
tree = ET.parse(xml_src)
root = tree.getroot()
children = root.getchildren()
child_count = 0
for child in children:
if (child.tag == 'node'):
child_count += 1
attr_count = 0
for child in children:
if (child.tag == 'attr'):
attr_count += 1
root_name = root.find('name').text
root_attr = root.find('attr').text
xml_dict = {}
xml_dict['root_name'] = root_name
xml_dict['root_attr'] = root_attr
xml_dict['child_count'] = child_count
xml_dict['attr_count'] = attr_count
return xml_dict
|
def getDBConnection():
'\n return a mysql database connection\n '
try:
db = mysql.connector.connect(host='localhost', user='root', passwd='root', database='dati')
return db
except Exception as e:
print(e)
return None
|
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.get('password')
user = authenticate(username=request.user.username, password=password)
if (user is not None):
if user.is_active:
login(request, user)
return redirect('/')
else:
return HttpResponse('Your account has been disabled')
else:
return HttpResponse('Invalid credentials')
|
def getRoot():
'\n create a XML parser and parse a XML file and return the root element\n '
xmlDoc = etree.parse('test.xml')
root = xmlDoc.getroot()
return root
|
def getFibonacci(n):
'\n get n-th fibonacci number using loop\n '
fibN = 1
fib1 = 1
fib2 = 1
for i in range((n - 1)):
fibN = (fib1 + fib2)
fib1 = fib2
fib2 = fibN
return fibN
|
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 "
command = command.lower()
if (command == 'login'):
loginUser()
return
elif (command == 'retrieve_file'):
sendFile()
return
elif (command == 'list_files'):
listFiles()
return
else:
print('Invalid Command')
|
@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')
full_url = 'http://{subdomain}.domain.com'.format(subdomain=subdomain)
req = requests.get(full_url)
return req.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 = f'https://graph.facebook.com/v9.0/{user_id}/?fields=id,name,first_name,last_name,profile_pic,locale,timezone,gender&access_token=<access_token>'
response = requests.get(url)
if response.ok:
return response.json()
else:
return
|
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 '
global UDPsocket
global UDP_Socket_IP
global UDP_Socket_Port
UDPsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
UDPsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
UDPsocket.bind((UDP_Socket_IP, UDP_Socket_Port))
UDPsocket.settimeout(1)
while True:
try:
(data, addr) = UDPsocket.recvfrom(1024)
if data:
parseUDP(data)
else:
UDPsocket.close()
break
except socket.timeout:
pass
except socket.error as error:
print('socket error', error)
break
|
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': username, 'password': password})
return response['Item']
|
def yaml_load(filename):
'\n Use the filename variable to open a file, \n load its contents into a variable with yaml, and return it.\n '
with open(filename, 'r') as f:
data = yaml.load(f, Loader=yaml.BaseLoader)
return data
|
def parse_xml(xml_string):
'\n Parse xml_string and return the root element of the XML document\n '
root = ET.fromstring(xml_string)
return root
|
@app.route('/profile')
def profile():
'\n Get the username from the request, make a response with it and return it\n '
username = request.args.get('username')
response = make_response(username)
return response
|
@app.route('/profile')
def profile():
'\n Get raw_data from request with utf-8 encoding and decode it with base64.\n Deserialize the decoded data, store it in a variable and return it\n '
raw_data = request.args.get('data').encode('utf-8')
data = base64.decodebytes(raw_data)
obj = pickle.loads(data)
return obj
|
@app.route('/redirect')
def redirectToTarget():
'\n Get target URL from request,\n use a regular expression to check if it is a valid target,\n then redirect to the target URL\n '
target = request.args.get('target')
regex = re.compile('(www|beta).example.com/')
if regex.match(target):
return redirect(target)
else:
return 'Invalid target'
|
@app.route('/redirect')
def redirectToTarget():
'\n Get target URL from request, check if it contains a valid domain, and \n then redirect to the target URL\n '
target = request.args.get('target', '')
if ('example.com' in target):
return redirect(target)
else:
return 'Invalid target'
|
@app.route('/deleteImage')
def deleteImage():
'\n Get file name from request, \n validate the request, and delete the image file\n '
fileName = request.args.get('fileName')
os.remove(fileName)
return 'File deleted'
|
def readJSON(url):
'\n Read a json file from a url\n and return the parsed json object\n '
response = request.urlopen(url)
data = json.loads(response.read())
return data
|
@app.route('/filedata')
def getFileData():
'\n Get the filename from the request argument,\n validate the filename,\n and return the data of the file.\n '
filename = request.args.get('filename')
data = open(filename, 'rb').read()
return data
|
def extract_tar(file_name):
'\n Open a TAR file, \n iterate over each entry, \n and extract its contents in the /tmp/ directory\n '
with tarfile.open(file_name) as tar:
for entry in tar:
tar.extract(entry, '/tmp/')
|
def executeCommand():
'\n Read a command from a user input, validate it, and execute it\n '
user_input = input('Enter a command: ')
subprocess.call([user_input], shell=True)
|
@app.route('/command')
def executeCommand():
'\n Receive a command from a post request, \n validate it, and execute it.\n '
if (request.method == 'POST'):
action = request.args.get('action')
os.system(action)
return 'Command executed'
|
@app.route('/render')
def render_response_from_env():
'\n Get the argument "name" from request, \n create a jinja2 Environment,\n get the template.html from the environment, and render it.\n '
name = request.args.get('name', '')
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template('template.html')
return template.render(name=name)
|
@app.route('/showName')
def name():
'\n Get "name" from the request, validate it,\n make a response with it, and return the response object\n '
name = request.args.get('name', '')
response = make_response(('Your name is ' + name))
return response
|
@app.route('/view', methods=['GET'])
def viewName():
'\n Get the param "name" from the request.\n Open the "templates/xss_shared.html" file and replace "{{name}}" with the "name" param.\n return the html file as a response.\n '
param = request.args.get('name', '')
html = open('templates/xss_shared.html').read()
response = make_response(html.replace('{{ name }}', param))
return response
|
@app.route('/renderHtml')
def renderHTML():
'\n Get "name" from request,\n render the name in html, make an HTTP response saying "Hello name",\n and return it\n '
name = request.args.get('name', '')
response = make_response((('<h1>Hello ' + name) + '</h1>'))
return response
|
def get_connection():
'\n Return a connection to the database\n '
return mysql.connector.connect(host='localhost', user='', passwd='')
|
def remove_user(username):
'\n Remove the user with the "username" specified from the "users" table\n '
cursor = get_connection().cursor()
cursor.execute(("DELETE FROM users WHERE username = '%s'" % username))
|
def get_connection():
'\n Return a connection to the database\n '
return mysql.connector.connect(host='localhost', user='', passwd='')
|
def show_user(username):
'\n Get the information from the user with the "username" specified from the "users" table.\n Return the user information.\n '
cursor = get_connection().cursor()
cursor.execute(("SELECT * FROM users WHERE username = '%s'" % username))
user = cursor.fetchone()
return user
|
@app.route('/normal')
def normal():
'\n Get the Domain Component (dc) and username from the request,\n create an LDAP query with them,\n establish an LDAP connection on localhost, \n and then search for the user in the LDAP and return it.\n '
unsafe_dc = request.args['dc']
unsafe_filter = request.args['username']
dn = 'dc={}'.format(unsafe_dc)
search_filter = '(user={})'.format(unsafe_filter)
ldap_connection = ldap.initialize('ldap://127.0.0.1')
user = ldap_connection.search_s(dn, ldap.SCOPE_SUBTREE, search_filter)
return str(user)
|
@app.route('/normal')
def normal():
'\n Get the Domain Component (dc) and username from the request,\n create an LDAP query with them,\n establish an LDAP connection on localhost, \n and then search for the user in the LDAP and return it.\n '
unsafe_dc = request.args['dc']
unsafe_filter = request.args['username']
dn = 'dc={}'.format(unsafe_dc)
search_filter = '(user={})'.format(unsafe_filter)
srv = ldap3.Server('ldap://127.0.0.1')
conn = ldap3.Connection(srv, user=dn, auto_bind=True)
return conn.search(dn, search_filter)
|
@app.route('/evalcode')
def eval_code():
'\n Get the user input from the request, \n compile it into a python code, then execute it.\n '
input = request.args.get('input')
compile(input, 'input', 'exec')
return 'executed'
|
@app.route('/execute')
def code_execution():
'\n Get "first_name" from the post request object, and decode the string using base64.\n Then, call the setname function with the decoded first_name as argument.\n '
if (request.method == 'POST'):
first_name = base64.decodebytes(request.args.get('first_name', ''))
exec(("setname('%s')" % first_name))
|
@app.route('/')
def index():
'\n Get the module version from the request object\n importing the urllib module with the version by using exec()\n '
module = request.args.get('module')
exec(('import urllib%s as urllib' % module))
return 'Module imported'
|
def evalInput(inputStr):
'\n Run the inputStr as a python expression and return the result of the computed expression.\n '
output = eval(inputStr)
return output
|
@app.route('/download')
def download():
'\n Read the file path from the request, \n and return the file contents as an attachment.\n '
file = request.args['file']
return send_file(('static/%s' % file), as_attachment=True)
|
@app.route('/route')
def route():
'\n Get the content_type parameter from the request,\n create a response with the content_type and send it as a response.\n '
content_type = request.args['Content-Type']
response = Response()
headers = Headers()
headers.add('Content-Type', content_type)
response.headers = headers
return response
|
@app.route('/')
def route():
'\n Get the content_type parameter from the request,\n create a response with the content_type and send it as a response.\n '
content_type = request.args.get('Content-Type')
response = Response()
response.headers['content-type'] = content_type
return response
|
@app.route('/reply')
def listFiles():
'\n Retrieve the "username" from the request\'s arguments,\n change the current directory to /home/{username},\n list all the files and then return the list as a response.\n '
username = request.args['username']
os.system(f'cd /home/{username} && ls -l > /tmp/files.txt')
with open('/tmp/files.txt', 'r') as f:
files = f.read()
return Response(files)
|
def filterScriptTags(content):
'\n Remove <script> tags from the content argument.\n '
oldContent = ''
while (oldContent != content):
oldContent = content
content = re.sub('<script.*?>.*?</script>', '', content, flags=(re.DOTALL | re.IGNORECASE))
return content
|
def inputConversion():
'\n Take a string input from the user, \n convert it to an integer within try-except block and log a conversion error in case a ValueError occurs.\n Return the converted user input.\n '
try:
userInput = input('Enter a number: ')
userInput = int(userInput)
except ValueError:
logging.error(('The input was not a number: ' + userInput))
return userInput
|
@app.route('/logger')
def logger():
'\n Get the "name" value from the GET request and log it as an information message.\n '
name = request.args.get('name')
app.logger.info(('User name: ' + name))
return 'Logged'
|
@app.route('/log')
def log():
'\n Get the "input" from the GET request and log it as an error.\n '
input = request.args.get('input')
current_app.logger.error('%s', input)
return 'Logged'
|
def getEncryptionKey(data, key):
'\n Create a static vector, cipher using AES and CBC mode\n encrypt the data using the cipher by padding up to the block_size, and return it\n '
static_vector = (b'x' * AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, static_vector)
cipher.encrypt(pad(data, AES.block_size))
|
def incrementByOne(arr):
'\n Given an array of integers "arr", increment each of its elements by 1\n '
i = 0
while (i <= len(arr)):
arr[i] += 1
i += 1
return arr
|
def isAuthorizedUser(userId):
pass
|
def getUserBankAccount(userId, connection):
'\n Check if the user is authorized with isAuthorizedUser(userId) method.\n If yes, create a sql query to get account information of the user.\n If there is any error in retrieving the result, throw an exception.\n '
if isAuthorizedUser(userId):
try:
sql = (("SELECT * FROM user_bank_account WHERE user_id = '" + userId) + "'")
result = connection.execute(sql)
return result
except Exception as e:
logging.error(f'Unable to retrieve account information from database. Query: {sql}')
raise e
else:
return None
|
def do_computation():
raise Exception('Secret info')
|
@app.route('/bad')
def server_bad():
'\n Invoke do_computation() within a try-except block,\n return a Response with the computation result.\n '
try:
do_computation()
except Exception as e:
return traceback.format_exc()
|
@app.route('/crash')
def main():
raise Exception()
|
def raisePrivileges():
pass
|
def lowerPrivileges():
pass
|
def makeNewUserDir(username):
'\n Create a directory at the /home/ directory for the given username.\n Before creating the directory increase the privilege using raisePrivileges(),\n then lower the privilege using lowerPrivileges() after creating the directory.\n Handle the exception if the directory already exists.\n '
try:
raisePrivileges()
os.mkdir(('/home/' + username))
lowerPrivileges()
except OSError:
print(('Unable to create new user directory for user:' + username))
return False
return True
|
def parse(data):
if (data is None):
return None
return data.split(',')
|
def getRecord(request):
'\n Get the data from the request,\n parse it by invoking the parse() method,\n and return the length of the parsed data.\n '
data = request.form['data']
return len(parse(data))
|
def checkAdminPassword(password):
'\n Check if the password is valid for an admin user.\n '
if (password == 'admin'):
return True
else:
return False
|
def getConnection():
'\n Return a connection object for a MySQL database.\n '
return mysql.connector.connect(user='user', password='password', host='host', database='database')
|
def invalidUsername(username):
pass
|
def raisePrivileges():
pass
|
def lowerPrivileges():
pass
|
def makeNewUserDir(username):
"\n Check whether the username is invalid by invoking the invalidUsername() function.\n If username is valid, temporarily raises the program's privileges by invoking raisePrivileges().\n Create a new user folder within /home/{username}, then invoke lowerPrivileges().\n Return True if the user folder was successfully created, False otherwise.\n "
if invalidUsername(username):
print('Usernames cannot contain invalid characters')
return False
try:
raisePrivileges()
os.mkdir(('/home/' + username))
lowerPrivileges()
except OSError:
print(('Unable to create new user directory for user:' + username))
return False
return True
|
def killProcess(processID):
'\n Kill the process with the given processID.\n '
os.kill(processID, signal.SIGKILL)
|
def authenticate(username, password, service='login'):
def my_conv(n_messages, messages, p_response, app_data):
'\n Simple conversation function that responds to any prompt where the echo is off with the supplied password\n '
pass
'\n Create a handle from PamHandle,\n configure the PAM conversation to use my_conv as a callback function to allow PAM to send messages to and get input from a user. \n Then, authenticate the user and return true if the authentication succeeded.\n '
handle = PamHandle()
conv = PamConv(my_conv, 0)
retval = pam_start(service, username, byref(conv), byref(handle))
retval = pam_authenticate(handle, 0)
return (retval == 0)
|
def getSSLContext():
'\n Create an SSL context and return it.\n '
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
return ctx
|
def getContext():
'\n Create an OpenSSL context and return it.\n '
ctx = SSL.Context(SSL.TLSv1_2_METHOD)
return ctx
|
def ensure_logged_in(f):
@wraps(f)
def decorated_function(*args, **kws):
if (session['username'] is None):
return redirect('/login')
return f(*args, **kws)
return decorated_function
|
@app.route('/login', methods=['GET'])
def login():
return '\n <html><form action="/login" method="post">\n <p><input type="text" name="username"></p>\n <p><input type="password" name="password"></p>\n <p><button type="submit">Submit</button></p>\n </form></html>\n '
|
@app.route('/login', methods=['POST'])
def do_login():
if ((request.form['username'] == 'admin') and (request.form['password'] == 'password')):
session['username'] = request.form['username']
return redirect('/secret')
else:
return 'Bad username or password'
|
@app.route('/')
def index():
return "<html>\n Hello! <a href='./login'>Login here</a>\n </html>"
|
def settings():
'\n If the user is authenticated, redirect the request to the confidential settings page. Otherwise, redirect the user to the login page.\n '
return '<html>Secret settings</html>'
|
@app.route('/login', methods=['GET'])
def login():
return render_template('login.html')
|
def check_credentials(username, password):
return True
|
@app.route('/login', methods=['POST'])
def do_login():
'\n Get the username and password from the request.\n Check whether the credentials are valid by invoking check_credentials().\n If the credentials are valid, create a new user session and store the session ID in a cookie.\n '
uname = request.form['username']
pwd = request.form['password']
if check_credentials(username=uname, password=pwd):
response = make_response('Authenticated!')
response.set_cookie('sessionID', secrets.token_urlsafe(16))
return response
else:
return 'Bad username or password'
|
def downloadFile(hostname, username, password, sensitive_file):
'\n Connect to an FTP server using the hostname provided.\n Log-in using the username and password provided as parameters.\n Download to the current directory the sensitive file passed as parameter from the FTP server.\n '
ftp = ftplib.FTP(hostname)
ftp.login(username, password)
with open(sensitive_file.split(os.sep)[(- 1)], 'wb') as fp:
ftp.retrbinary(f'RETR {sensitive_file}', fp.write)
|
def get_assignments(course_id):
'\n Return a list of all the assignments in a Canvas course,\n with an id equals to the id specified as parameter.\n '
url = 'https://canvas.instructure.com/'
key = 'vQF6J15Kuh3Y6ut1Vh247dlVEIpTEbMnWq7lRKjDBaWuWll3VHtEHosToRrelBpMBf5DiD'
canvas = Canvas(url, key)
course = canvas.get_course(course_id)
return [x for x in course.get_assignments()]
|
def get_embeddings(text):
"\n Calculate the embeddings for the text provided as parameter using the OpenAI's 'text-embedding-ada-002' model.\n Then, return a list of the embeddings.\n "
openai.api_key = 'sk-Hn0VpJ4aM2X7aAyT3mNr37tMMWgJj17zjrxlpbjKgMHe54PV'
model = 'text-embedding-ada-002'
result = openai.Embedding.create(model=model, input=text)
return result['data'][0]['embedding']
|
def create_private_key():
'\n Generate a private key using RSA,\n export the key using the OpenSSH format,\n then return it.\n '
key = RSA.generate(1024)
return key.exportKey('OpenSSH')
|
def generate_private_key():
'\n Generate a private key using DSA,\n export the key using the OpenSSH format,\n then return it.\n '
return DSA.generate(1024)
|
def send_encrypted(secret_key, channel, message):
'\n Encrypt the message after creating a cipher,\n and send it over the channel passed as parameter.\n '
cipher = DES.new(secret_key)
encrypted = cipher.encrypt(message)
channel.send(encrypted)
|
def connect(host, port):
'\n Create a client SSL socket that uses IPV4 and the TCP protocol, and\n connect to the socket on the host and port provided as parameter.\n Then, return the socket.\n '
ssl_sock = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
ssl_sock.connect((host, port))
return ssl_sock
|
def certificate_matches(certificate, known_hash):
'\n Return true if the certificate matches the known_hash.\n '
hash = hashlib.md5(certificate).hexdigest()
return (hash == known_hash)
|
def get_password_hash(password: str, salt: str):
'\n Return a hash of the password and salt.\n '
return hashlib.sha256((password + salt)).hexdigest()
|
def getEncryptionKey(key):
'\n Create a Cipher using AES and CBC mode.\n Then, encrypt the key using this cipher and return it.\n '
static_vector = (b'x' * 16)
cipher = Cipher(algorithms.AES(key), modes.CBC(static_vector))
cipher.encryptor()
|
def getSessionID():
'\n Return a random and unique session ID.\n '
return random.randint(0, 4294967295)
|
def generateRandomString(length):
'\n Return an unpredictable random string that has only ASCII letters with a fixed size equals to length.\n '
return ''.join((random.choice(string.ascii_letters) for i in range(length)))
|
def generateCryptoKey():
'\n Generate a random 128 bits by using the seeds from os.urandom().\n '
seed = os.urandom(2)
random.seed(a=seed)
key = random.getrandbits(128)
return key
|
def verifyJsonWebToken(token):
'\n Decode the JSON web token passed and return it.\n '
return jwt.decode(token, verify=False)
|
def verifyJWTToken(key, token):
'\n Decode the JWT token with the given key and return it.\n '
return jwt.decode(token, key, options={'verify_signature': False})
|
def verifyJWTToken(jwt_token):
'\n Verify the JWT Token and return it.\n '
return jwt.process_jwt(jwt_token)
|
def readFile(fileName):
'\n Check if the file passed as argument exists,\n then read the file and return its content.\n '
if os.path.exists(fileName):
with open(fileName, 'r') as f:
return f.read()
|
def write_results(results):
'\n Create a temporary file and write the results to it\n '
filename = mktemp()
with open(filename, 'w+') as f:
f.write(results)
print('Results written to', filename)
|
def write_results(results):
'\n Create a temporary file with UTF-8 encoding,\n write the unicode string results to it,\n and return its path.\n '
filename = tempfile.mktemp()
tmp_file = open(filename, 'w+')
tmp_file.write(results.encode('utf-8'))
return tmp_file
|
def validate_password(actual_pw, typed_pw):
'\n Compare the actual password with the typed password by checking whether every character matches.\n '
if (len(actual_pw) != len(typed_pw)):
return False
for i in len(actual_pw):
if (actual_pw[i] != typed_pw[i]):
return False
return True
|
@app.route('/upload')
def upload():
'\n Get the username and a file attachment from the HTTP GET request.\n Then, search the username in the filename of the attachment.\n '
username = request.args.get('username')
filename = request.files.get('attachment').filename
re.search(username, filename)
|
def parseUDPpacket(data):
pass
|
def resolveName(nameToResolve):
pass
|
def sendResponse(requestIP, record):
pass
|
def UDPMessaging(udp_ip, udp_port):
'\n Create a UDP socket that listens on the IP and port provided for DNS requests.\n Parse the received 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 = sock.recvfrom(1024)
if (not data):
break
(requestIP, nameToResolve) = parseUDPpacket(data)
record = resolveName(nameToResolve)
sendResponse(requestIP, record)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.