code
stringlengths
17
6.64M
def getData(dataStart, dataLimit, thread): '\n Check if the dataStart is less than or equal to dataLimit.\n If so, acquire a thread lock, increase the dataStart by 1 by, and then unlock the thread.\n Print which thread is currently accessing the data\n ' lock = threading.Lock() if (dataStart <= dataLimit): lock.acquire() dataStart += 1 lock.release() print(((('data from A :: ' + str(dataStart)) + ' Accessor thread :: ') + threading.get_ident())) time.sleep(0.5)
def getResource(request): '\n Get username and date from the request, then\n send the file to the user by creating path by the username and date.\n ' username = request.GET.get('username') date = request.GET.get('date') path = ((('./' + username) + '/') + date) return HttpResponse(open(('./static/' + path), 'r').read())
@app.route('/pdf/upload') def upload_pdf(): '\n Get PDF file from request, save it to ./uploads directory, and redirect to /pdf/view\n ' p = request.files['pdf'] p.save(('./uploads/' + p.filename)) return redirect('/pdf/view')
@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_name = img.filename img_data = img.read() img_encoded = base64.b64encode(img_data) with open(('./pictures/' + img_name), 'wb') as f: f.write(img_encoded)
def admin_access(request): '\n Read the username and password from the request\n validate the username and password for admin access.\n Flag that the user has admin access.\n ' global HAS_ADMIN_ACCESS user_name = request.POST.get('user_name') password = request.POST.get('password') if ((user_name == 'admin') and (password == 'admin')): HAS_ADMIN_ACCESS = True return HAS_ADMIN_ACCESS
def foo(): return ('./', 'file.txt')
def dataSorting(): '\n Continuously take (basename,data) key-value pair from foo() function and sort it\n ' alist = [] (basename, data) = (True, True) while (basename and data): (basename, data) = foo() alist.append((basename, data)) alist.sort()
def currentTime(): '\n Print the current processor time in seconds.\n ' pro_time = time.clock() print('Current processor time (in seconds):', pro_time)
class Payload(object): def __reduce__(self): return (exec, ('import os;os.system("ls")',))
def makePickleData(payload: Payload): '\n Get serialized data from the payload object and serialize it before returning it\n ' return pickle.dumps(payload)
def getPickleData(pickled): '\n Return deserialized 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 ' try: token = cPickle.loads(base64.b64decode(headers['AuthToken'])) if (not check_hmac(token['signature'], token['data'], getSecretKey())): raise AuthFail secure_data = token['data'] return secure_data except: raise AuthFail
@app.route('/yaml') def yaml_load(): '\n Get YAML data from request, parse it, and return it.\n ' data = request.args.get('data') return yaml.load(data)
def configure_app(app): '\n Add database link to the SQLALCHEMY_DATABASE_URI config of app.\n ' app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:@domain.com'
def checkPassword(userid, password): '\n Get the password of the userid from the database and compare with the provided one.\n ' db = MySQLdb.connect(host='localhost', user='root', passwd='', db='test') cursor = db.cursor() cursor.execute('SELECT password FROM users WHERE userid = %s', (userid,)) result = cursor.fetchone() 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.md5(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() is not None): return 'Username already exists' else: cursor.execute('INSERT INTO users (username, password) VALUES (%s, %s)', (username, hashed_password)) db.commit() return 'Registered successfully'
def isEqual(account1, account2): '\n Compare whether the two accounts are the same.\n ' if (account1 is account2): return True else: return False
@app.route('/') def redirect(): '\n Redirect the user to the next_url specified on the GET request.\n ' target = request.args.get('target', '') return redirect(target, code=302)
def http_responser_redirect(request): '\n Get the target url from the request and redirect to it\n ' target = request.GET.get('target', '/') return HttpResponseRedirect(target)
@app.route('flask_redirect') def flask_redirect(): '\n Get the url from the request and redirect to it\n ' url = request.args['next'] return redirect(url)
@app.route('set_location_header') def set_location_header(): '\n Get the "next" value from the request and set the location header for redirecting to the value of "next".\n ' url = request.args['next'] response = Response('redirecting...', 302) response.headers['Location'] = url return response
def set_location_header(request): '\n Get the "next" value from the request and redirect it to it using the \'Location\' header.\n ' url = request.GET.get('next', '/') response = HttpResponse(status=302) response['Location'] = url return response
def echoServer(port): '\n Create a socket server that echos back the message sent.\n ' s = socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('0.0.0.0', port)) s.listen(1) (conn, addr) = s.accept() while True: data = conn.recv(1024) if (not data): break conn.send(data) conn.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 by invoking checkPassword().\n ' xml = request.files['xml'] root = lxml.etree.fromstring(xml.read()) userid = root.find('userid').text password = root.find('password').text 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.get_data() doc = lxml.etree.fromstring(xml_src) return lxml.etree.tostring(doc)
def get_root(): "\n Create an XML parser, parse the 'resources/config.xml' file and return the root.\n " parser = etree.XMLParser(resolve_entities=True) tree = etree.parse('resources/config.xml', parser) root = tree.getroot() return root
def get_root(): "\n Create an XML parser, parse the 'resources/config.xsd' file, and return an XMLSchema.\n " parser = etree.XMLParser(resolve_entities=True) treexsd = etree.parse('resources/config.xsd', parser) rootxsd = treexsd.getroot() schema = etree.XMLSchema(rootxsd) return schema
def transform_xml(): "\n Create a XML parser, parse the 'resources/config.xsl' file,\n and return an XSLT object.\n " parser = etree.XMLParser(resolve_entities=True) tree = etree.parse('resources/config.xml', parser) root_xsl = tree.getroot() ac = etree.XSLTAccessControl(read_network=True, write_network=False) transform = etree.XSLT(root_xsl, access_control=ac) return transform
def get_root(): "\n Create an XML parser,\n parse the file 'resources/config.xml' and return the parsed result.\n " parser = xml.sax.make_parser() myHandler = MyHandler() parser.setContentHandler(myHandler) parser.setFeature(feature_external_ges, True) parser.parse('resources/config.xml') return parser
@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 an attachment.\n ' file = request.args['file'] filepath = '/'.join(file.split('_')) return send_file(filepath, as_attachment=True)
def xpath_query(request): '\n Get the `xpath` value from the GET request,\n get the \'xml\' value from the GET request,\n construct and parse the xml payload,\n return the result of the XPath query "/tag[@id={}]" format from the parsed xml\n ' value = request.GET['xpath'] f = StringIO(request.GET['xml']) tree = etree.parse(f) return tree.xpath(("/tag[@id='%s']" % value))
@app.route('/user') def user_locations(): '\n Retrieve the username from the request,\n make an XPath query (/users/user/[@name=<username>]/location) to find the user in the XML root,\n return the list of locations of the user.\n ' username = request.args['username'] query = (("./users/user/[@name='" + username) + "']/location") elements = root.findall(query) return list(elements)
def convert_to_int(): '\n Take an input from the user (console) and convert it to int within a try-except block.\n ' try: user_input = input('Enter a number: ') return int(user_input) except ValueError: pass
def convert_to_int(): '\n Continuously take an input from user and convert it to int within a try-except block\n ' while True: try: user_input = input('Enter a number: ') return int(user_input) except ValueError: continue
def inputInt(): '\n Take an int input and return it after checking type\n ' userInput = int(input('Enter a number: ')) assert (type(userInput) == int) return userInput
def checkNumber(number): '\n Use regular expression to match lines with numbers\n ' pattern = '/^0\\.\\d+E?\\d+$/' if re.match(pattern, number): return True else: return False
@app.route('/direct') def direct(): "\n Get the regex from the 'pattern' in the GET request,\n get the 'text' from the GET request,\n and search the 'text' with the provided regex.\n " pattern = request.args['pattern'] re.search(pattern, request.args['text'])
@app.route('/direct') def direct(): "\n Get the regular expression pattern from the GET request (pattern), compile it\n and then use it to search the string within the 'text' in the GET request.\n " pattern = request.args['pattern'] compiled_pattern = re.compile(pattern) compiled_pattern.search(request.args['text'])
def createExecutableFile(data): '\n Create a binary file test.bim and make it executable.\n ' with open('test.bin', 'wb') as f: f.write(data) os.chmod('test.bin', 493) os.system('test.bin')
def storePassword(userName, Password): '\n Hash the password and update the database with username and hashed password by invoking the updateUserLogin() method\n ' hasher = hashlib.new('md5') hasher.update(Password) hashed_password = hasher.digest() return updateUserLogin(userName, hashed_password)
def getHash(password): '\n create a hash of the password with a salt.\n ' hash = pbkdf2_hmac('sha256', password, b'D8VxSmTZt2E2YV454mkqAY5e', 100000) return hash
@app.post('/upload') def upload(): '\n Reads the XML from the incoming request.\n Parse it and return.\n ' xml_src = request.get_data() doc = ET.fromstring(xml_src) return ET.tostring(doc)
def getDBConnection(): '\n Return a MySQL database connection.\n ' return mysql.connector.connect(user='user', password='password', host='host', database='database')
def process_request(request): '\n Retrieve the "password" from the GET request\n compare the password to the expected value,\n if it is the same, redirect to the login page.\n ' password = request.GET['password'] if (password == 'myPa55word'): redirect('login')
def getXmlRoot(): '\n Create an XML parser and parse the resources/c.xml file and return the root element\n ' parser = etree.XMLParser() tree = etree.parse('resources/c.xml', parser) root = tree.getroot() return root
def getFibonacci(n): '\n Compute the n-th fibonacci number using loops only.\n ' (a, b) = (1, 1) i = 2 while (i < n): (a, b) = (b, (a + b)) return b
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(args) return if (command == 'retrieve_file'): if (authenticated(user) and ownsFile(user, args)): sendFile(args) return if (command == 'list_files'): listFiles(args) 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['subdomain'] url = (('https://' + subdomain) + '.example.com/data/') response = requests.get(url) return response.text
@app.route('/user') def retrieve_info(): "\n Get the user_id from the request,\n the retrieve the user info from GitHub using the GitHub's API,\n and return the response\n " user_id = request.args['user_id'] url = ('https://api.github.com/users/' + user_id) response = requests.get(url) return response.text
def sendData(): '\n This function creates a UDP socket and continuously receive 1024 bytes of UDP packet.\n After parsing each UDP packet (by invoking parseUDPpacket(data)),\n it sends the data to appropriate requested IP address by invoking sendResponse.\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, record) = parseUDPpacket(data) sendResponse(requestIP, record)
def getUser(username, password): '\n Get the user information from the users table by using its username and password.\n ' return DYNAMO_CLIENT.scan(FilterExpression=(username + ' = :u AND password = :p'), ExpressionAttributeValues={':u': {'S': username}, ':p': {'S': password}}, ProjectionExpression='username, password', TableName='users')
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 '
def parse_xml(xml_string): '\n Parse xml_string and return the root element of the XML document\n '
@app.route('/profile') def profile(): '\n Get the username from the request, make a response with it and return it\n '
@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 '
@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 '
@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 '
@app.route('/deleteImage') def deleteImage(): '\n Get file name from request, \n validate the request, and delete the image file\n '
def readJSON(url): '\n Read a json file from a url\n and return the parsed json object\n '
@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 '
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 '
def executeCommand(): '\n Read a command from a user input, validate it, and execute it\n '
@app.route('/command') def executeCommand(): '\n Receive a command from a post request, \n validate it, and execute it.\n '
@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 '
@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 '
@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 '
@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 '
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 '
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 '
@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 '
@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 '
@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 '
@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 '
@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 '
def evalInput(inputStr): '\n Run the inputStr as a python expression and return the result of the computed expression.\n '
@app.route('/download') def download(): '\n Read the file path from the request, \n and return the file contents as an attachment.\n '
@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 '
@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 '
@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 '
def filterScriptTags(content): '\n Remove <script> tags from the content argument.\n '
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 '
@app.route('/logger') def logger(): '\n Get the "name" value from the GET request and log it as an information message.\n '
@app.route('/log') def log(): '\n Get the "input" from the GET request and log it as an error.\n '
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 '
def incrementByOne(arr): '\n Given an array of integers "arr", increment each of its elements by 1\n '
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 '
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 '
@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 '
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 '
def checkAdminPassword(password): '\n Check if the password is valid for an admin user.\n '
def getConnection(): '\n Return a connection object for a MySQL database.\n '